# 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^π?
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.
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.
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.
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.
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.
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()