احتمال و یادگیری ماشین
5 subscribers
13 photos
Probability and Machine Learning
Download Telegram
# Data Science and Machine Learning 
# Seyed Mahmoud Mirkhan, 1404
# Chapter 1 Computer Programming

# R, Sequence of even numbers from 1 to 10.
seq1 = 0
i = 1; j = 2
while(j <= 10) {
seq1[i] = j
i = i + 1
j = j + 2 }
print(seq1)

# Python, Sequence of even numbers from 1 to 10.
seq1 = []
i = 1; j = 2
while j <= 10:
seq1.append(j)
i = i + 1
j = j + 2

print(seq1)

% Matlab, Sequence of even numbers from 1 to 10.
seq1 = 0;
i = 1; j = 2;
while(j <= 10)
seq1(i) = j;
i = i + 1;
j = j + 2;
end
disp(seq1)

# ans: [1] 2 4 6 8 10

# ---------------------------
# R, Sequence of even numbers from 1 to 10.
for(i in seq(2,10,2))
print(i)

# Python, Sequence of even numbers from 1 to 10.
import numpy as np
for i in np.arange(2,11,2):
print(i)

% Matlab, Sequence of even numbers from 1 to 10.
for(i = 2:2:10)
disp(i)
end

# -----------------------
# R, Sequence of even numbers from 1 to 10.
seq(2,10,2)

# Python, Sequence of even numbers from 1 to 10.
np.arange(2,11,2)

% Matlab, Sequence of even numbers from 1 to 10.
2:2:10
مثال ) تکرار دلخواه چاپ یک کلمه مانند Hello World را با تابع بازگشتی می نویسیم

Example ) We write the desired repetition of printing a word like Hello World using a recursive function.
# Data Science and Machine Learning 
# Seyed Mahmoud Mirkhan, 1404
# Chapter 1 Computer Programming

# R, Function and Recursive Function
f2 = function(txt, n = 1) {
if (n >= 1){
for(i in 1:n)
print(txt) } }
f2("Hello World", 2)
# --------------------
f3 = function(txt, n = 1) {
if (n <= 1)
print(txt)
else {
print(txt)
f3(txt, n-1) } }
f3('Hello World', 2)

# Python, Recursive Function
def f3(txt, n = 1):
if n <= 1:
print(txt)
else:
print(txt)
f3(txt, n-1)

f3('Hello World', 2)

% Matlab, Recursive Function, save with f3.m and put in Documents/Matlab
function [y] = f3(txt, n)
if ~exist('n')
n = 1;
end
if ( n <= 1 )
disp(txt)
else
disp(txt)
f3(txt, n-1)
end
end

% Run this command in Matlab
f3("Hello World",2)
1 - 2 ابعاد و انواع داده
در یک نگرش، داده ورودی به عنوان های متغیر، ويژگی یا صفت با ابعاد و نوع آن بر اساس ذخیره در کامپیوتر معرفی می شوند که در این بخش آنها را همراه با توابع و ابزارهای کنترل برنامه نویسی بخش قبل بیان می کنیم. در مباحث یادگیری ماشین و یادگیری عمیق داده ورودی سیستم می تواند از انواع ابعاد داده باشد.
داده بر اساس نوع ابعاد آن به دسته های زیر تفکیک می شوند.


- داده صفر بعدی 0D، متغیری تک مقداری از نوع عدد x، رشته متن y یا دودویی z است.
x=1 ;y=' Hello' ;z=TRUE


- داده یک بعدی 1D در دو نوع بردار x و لیست y با مولفه داده 0D تعریف می شود. متغیر برداری سطری، ستونی یا آرایه از یک نوع داده 0D بوده و متغیر لیست شامل مولفه هایی از انواع داده است.
x=[1 ,2 ,3] ;y=list(1 ,"Hello" ,TRUE)


- داده دو بعدی 2D به دو شکل ماتریس ریاضی x و فرم داده آماری y به کار می رود. ماتریس با سطر و ستون نمایش داده می شود که همه مولفه های آن از یک نوع داده 0D مانند پیکسل تصویر سیاه و سفید تشکیل شده اند. فرم داده از متغیرهای ستونی با نام سرستون و هر ستون از یک نوع داده 0D تشکیل شده که معمولا در جداول پایگاه داده ذخیره می گردند.


- داده ابعاد بالا nD مانند لیست (و تنسور) در R، آرایه سلولی در Matlab و تنسور در Python تعریف می شود. مثلا عکس رنگی RGB داده سه بعدی 3D متشکل از سه ماتریس پیکسل هر رنگ است و با افزودن تعداد تصویر به آن، تنسور یا داده چهار بعدی 4D تشکیل می شود. ابعاد بعدی ممکن است زمان و غیره باشد.
1 - 2 Dimensions and Types of Data
From one perspective, input data is introduced as variables, features, or attributes with dimensions and types based on how they are stored in the computer.
Data based on its dimensional type is classified into the following categories:


- Zero-dimensional (0D) data: a single-valued variable of type number x, text string y, or boolean z.
x = 1 ; y = ^'Hello^' ; z = TRUE


- One-dimensional (1D) data: defined in two forms, vector x and list y, with 0D data components. A vector variable can be a row, column, or array of a single 0D data type, and a list variable includes components of various data types.
x = [1, 2, 3] ; y = list(1, "Hello", TRUE)


- Two-dimensional (2D is used in two forms: as a mathematical matrix x and as a statistical data form y. A matrix is represented with rows and columns, where all of its components are of a single 0D data type, such as pixels of a black-and-white image. The data form consists of column variables with header names, and each column is made up of a single 0D data type, which is usually stored in database tables.


- High-dimensional nD data, such as a list (and tensor) in R, a cell array in Matlab, and a tensor in Python, is defined. For example, an RGB color image is a three-dimensional 3D dataset composed of three pixel matrices for each color, and by adding the number of images, a tensor or four-dimensional 4D dataset is formed. Further dimensions may include time and so on.
مثال ) انواع گرد کردن عدد 3.14159 را به دست می آوریم

Example ) We get the different ways of rounding the number 3.14159
# Data Science and Machine Learning 
# Seyed Mahmoud Mirkhan, 1404
# Chapter 1 Computer Programming


# R, Functions of Numbers
x = 3.14159
print(round(x, 3))
floor(x); floor(x) + 1
library(MASS)
fractions(3.14) # ans: 157/50
print(Inf)

# Python, Functions of Numbers
import numpy as np
x = 3.14159
print(np.round(x, 3))
np.floor(x); np.ceil(x)
from fractions import Fraction
print(Fraction(3.14)) # ans: ! 7070651414971679/2251799813685248
print(float('inf')

% Matlab, Functions of Numbers
x = 3.14159;
disp(round(x, 3))
floor(x); ceil(x)
rats(3.14) % ans = ' 157/50 '
disp(Inf)
مثال ) کدامیک از اعداد π^e و e^π بزرگتر از دیگری است

Example ) Which number is larger, π^e or e^π?
# Data Science and Machine Learning 
# Seyed Mahmoud Mirkhan, 1404
# Chapter 1 Computer Programming

# R
print(paste(exp(pi), pi ^ exp(1)))

# Python
import numpy as np
print(np.exp(np.pi), np.pi ** np.exp(1))

% Matlab
sprintf("%f %f", exp(1) ^ pi, pi ^ exp(1))
مثال ) اندیس های بردار را انتخاب می کنیم.

Example) We select the vector indices.
# Data Science and Machine Learning 
# Seyed Mahmoud Mirkhan, 1404
# Chapter 1 Computer Programming

# R, Vector indices with conditions
a <- seq(0, 1, length.out=11) # or a<-seq(0, 1 0.1)
a[] # Create vector 0, 0.1, …, 0.9, 1
a[c(2, 4, 6)] # Select indices 2, 4 and 6 of vector
a[-c(2, 4, 6)] # Select indices except 2, 4 and 6
# ---------------------------------
a[length(a)-1] # Select index second from end
a[1:3] # Select indices 1 through 3
a[seq(1,10,2)] # Select odd indices of vector
a[seq(11,1,-1)] # Select reverse indices
# ---------------------------------
a[a > 0.5] # Select vector greater than 0.5
which(a > 0.5) # Select indices greater than 0.5
a[a > 0.8 | a <= 0.1] # Select a > 0.8 or a <= 0.1
which(a > 0.8 | a <= 0.1) # Select indices
# ---------------------------------

# Python, Vector indices with conditions
import numpy as np
a = np.linspace(0, 1, 11); # a or print(a) or a[:]
a[np.array([1, 3, 5])]
# ---------------------------------
# Show array indices except above indices
import itertools
[item for idx, item in enumerate(a) if idx not in {1,3,5}]
indices = [1, 3, 5]
b = np.where(np.isin(np.arange(len(a)), indices), -1, a)
print(b[b != -1])
# ---------------------------------
a[-2]
a[0:3]
a[0:10:2] # a[::2]
a[::-1]
# ---------------------------------
a[a > 0.5]
np.where(a > 0.5)
a1 = [a for a in a if a > 0.8 or a <= 0.1]
print(a1)
a[(a <= 0.1) | (a > 0.8)]
print(np.concatenate((np.where(a <= 0.1), np.where(a > 0.8)), axis=1))
a[np.logical_or(a <= 0.1 , a > 0.8)]
func = np.vectorize(lambda t: t<= 0.1 or t > 0.8)
a[func(a)]

% Matlab, Vector indices with conditions
a = linspace(0, 1, 11)
a([2 4 6])
a(setdiff(1:end, [2 4 6]))
% ---------------------------------
a(length(a)-1)
a(1:3)
a(1:2:10)
a(10:-1:1)
a(a > 0.5)
find(a > 0.5)
a(a > 0.8 | a <= 0.1)
find(a > 0.8 | a <= 0.1)
مثال ) اندیس های ماتریس را انتخاب می کنیم.

Example) We select the Matrix indices.
# Data Science and Machine Learning 
# Seyed Mahmoud Mirkhan, 1404
# Chapter 1 Computer Programming

# R, Selection of Component of Matrix
a = matrix(1:9, nrow=3, byrow=TRUE); a
a[2,3] # component(2,3) of matrix
a[2,] # Second row
a[,3] # Third column
a[1:2, 2:3] # Submatrix, rows(1,2) and columns (2,3)
a[seq(1,3,2), seq(1,3,2)] # Selection submatrix
# a[row(a) > 2] # ans: [1] 7 8 9
# a[row(a) > 2 & col(a) > 2] # ans: [1] 9
which(a > 6, arr.ind = TRUE)

# Python, Selection of Component of Matrix
import numpy as np
a = np.array([[1,2,3], [4,5,6], [7,8,9]]); a
a[1,2]
a[1,:]
a[:,2]
a[[[0],[1]], [1,2]]
a[np.ix_(np.arange(0,3,2), np.arange(0,3,2))]
np.where(a > 6)

% Matlab, Selection of Component of Matrix
a = [1 2 3;4 5 6; 7 8 9]
a(2,3)
a(2,:)
a(:,3)
a(1:2, 2:3)
a(1:2:3, 1:2:3)
[row, col] = find(a > 6)
مثال ) داده گل زنبق را خوانده و دو متغیر آن را رسم می کنیم.

Example ) We read the iris flower dataset and plot its two variables.
# Data Science and Machine Learning 
# Seyed Mahmoud Mirkhan, 1404
# Chapter 1 Computer Programming

# R, show iris data, The file is in the R software
head(iris) # help(iris)
iris1 = read.table("d:/data/iris.csv", header=TRUE, sep=",")
write.csv(iris, file="d:/data/iris.csv", row.names=FALSE)
plot(iris[,1], iris[,3], col=iris[,5], pch=16)

# Python, Show iris data
import pandas as pd
iris1 = pd.read_csv("d:/data/iris.csv") # or read file, iris_1
iris1.head()

% Matlab, Show iris data
iris1 = iris_dataset; size(iris1)
iris1(:,1:6)
iris2 = readtable("d:/data/iris.csv"); iris2(1:6,:)
مثال ) داده ارقام دستنویس را می خوانیم و یک عدد را نمایش می دهیم.

Example) We read handwritten digits MNIST and display a number.
# Data Science and Machine Learning 
# Seyed Mahmoud Mirkhan, 1404
# Chapter 1 Computer Programming

# Python, MNIST data of handwriting set of images
import tensorflow as tf
import numpy as np
from tensorflow.keras.datasets import mnist
from matplotlib import pyplot
(train_X, train_y), (test_X, test_y) = mnist.load_data()
i = 31 # Showing digit 8 with index 31
pyplot.imshow(train_X[i])
pyplot.show()
pyplot.imshow(train_X[i], cmap=pyplot.get_cmap('gray'))
pyplot.show()
print(train_X[i])
print(np.shape(train_X[i]))

% Matlab, MNIST data of handwriting set of images
load('d:/data/mnist.mat'); help('mnist.mat')
size(training.images)
size(test.images) %image (training.images(:,:,18)*255);
image (rescale(training.images(:,:,18),0,255));
axis square equal
colormap(gray) % Change color Image to Gray Style
colorbar
training.labels(18)
title (sprintf ("Digit: %d", training.labels(18)))
training; training.images(:,:,18)*255

# R, MNIST data of handwriting set of images
data <- read.csv("d:/data/train.csv")
dim(data); head(data[1:6]); unique(unlist(data[1]))
min(data[2:785]); max(data[2:785])
sample_8 <- matrix(as.numeric(data[31,-1]), nrow=28, byrow=TRUE)
# Rotate the matrix by reversing elements in each column
rotate <- function(x) t(apply(x, 2, rev))
par(mfrow = c(1,2))
image(rotate(sample_8))
image(rotate(sample_8), col = grey.colors(255))
# Write matrix data to clipboard and paste to excel
write.table(sample_8, 'clipboard', sep='\t')
مثال ) گل و نام آن را نمایش می دهیم.

Example ) We display the flower and its name.
# Data Science and Machine Learning 
# Seyed Mahmoud Mirkhan, 1404
# Chapter 1 Computer Programming

% Matlab, List of name and image of flowers
flowers = {};
flowers_name = {}
flowers_name{1} = "Sunflower";
flowers{1} = "d:/data/flower_photos/sunflowers/678714585_addc9aaaef.jpg";
flowers_name{2} = " Rose ";
flowers{2} = "d:/data/flower_photos/roses/5402157745_a384f0583d_n.jpg";
for (i = 1:2)
a = imread(flowers{i});
subplot(1,2,i)
imshow(a);
title(flowers_name{i});
end

# R, List of name and image of flowers
flowers = list(); flowers_name = list()
flowers_name[[1]] = "Sunflower"
flowers[[1]]="d:/data/flower_photos/sunflowers/678714585_addc9aaaef.jpg"
flowers_name[[2]] = " Rose "
flowers[[2]] = "d:/data/flower_photos/roses/5402157745_a384f0583d_n.jpg"
# ------------------------------------------
library("jpeg"); par(mfrow=c(1,2))
for (i in 1:2){
a <- readJPEG(flowers[[i]])
plot(0:1, 0:1, type="n", ann=FALSE, axes=FALSE)
rasterImage(a,0,0,1,1)
title(flowers_name[[i]]) }
par(mfrow=c(1,1))
# ------------------------------------------
library(imager);
par(mfrow=c(1,2))
for (i in 1:2){
a <- load.image(flowers[[i]])
plot(a)
title(flowers_name[[i]]) }
par(mfrow=c(1,1))


# Python, List of dictionaries with name and image of flowers
flowers = [
{"name": "Sunflower", "image": "d:/data/flower_photos/sunflowers/678714585_addc9aaaef.jpg"},
{"name": "Rose", "image": "d:/data/flower_photos/roses/5402157745_a384f0583d_n.jpg"}]
from matplotlib import pyplot as plt
from matplotlib import image as mpimg
for flower in flowers:
a = mpimg.imread(flower["image"])
plt.title(flower["name"])
plt.imshow(a)
plt.show()

fig, (ax1, ax2) = plt.subplots(1, 2)
a1 = mpimg.imread(flowers[0]["image"])
ax1.set_title(flowers[0]["name"])
ax1.imshow(a1)
a2 = mpimg.imread(flowers[1]["image"])
ax2.set_title(flowers[1]["name"])
ax2.imshow(a2)
plt.show()