前言
不管是兴趣还是趋势,笔者开始尝试入坑机器学习,慢慢做一点笔记学习下。。由于是菜鸟,数学原理就不写了,贴一些流程和公式,专业词汇可能也有点不到位问题。这里记录的是怎么训练一个识别猫的程序(来源是Coursera)
用到的python库
numpy 矩阵计算必备
PIL和scipy将图片转为矩阵
import numpy as np
import scipy
from PIL import Image
from scipy import ndimage
训练数据定义
数据来源是Coursera上面的,注意文中所有的矩阵都是numpy.array类型哦
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y = load_dataset()
train_set_x_orig是训练图片集209张图片,每张图片 64x64x3(RGB)
所以是(209,64,64,3)的矩阵
test_set_x_orig 是测试用图片集 ,基本同上,就是图片数量不一样,50个,所以是
(50,64,64,3)
train_set_y 是训练用的结果集合,是一个一维的矩阵,每一个值对应的是训练用图片的正确输出值
,显然这个是人工录好的,在这个识别猫的程序里,图片是猫就输出1,不是就输出0,这是一个
(1,209)的矩阵
test_set_y则是测试的结果矩阵,同上,也是数量不一样,为(1,50)
然后根据训练集拿到一些有用的参数
#训练图片数
m_train = len(train_set_x_orig)
#测试图片数
m_test = len(test_set_x_orig)
#像素宽
num_px = train_set_x_orig[0].shape[0]
操作流程
1.把图集平铺开,每张图是由 64,64,3的矩阵构成,那么可以转为64x64x3的一维矩阵
所以图集也可变为(64x64x3,209)的矩阵,测试图集也是一样
train_set_x_flatten = train_set_x_orig.reshape(m_train , -1).T
test_set_x_flatten = test_set_x_orig.reshape(m_test, -1).T
#rgb的值就是255,除以255得到对应的小数,这样能加快计算效率,这里 train_set_x_flatten和test_set_x_flatten的类型都是
#numpy.array哦
train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.
sigmoid函数,处理数据用
def sigmoid(z):
"""
Compute the sigmoid of z
Arguments:
z -- A scalar or numpy array of any size.
Return:
s -- sigmoid(z)
"""
s = 1/(1+np.exp(-z))
return s
初始化一些参数
def initialize_with_zeros(dim):
"""
This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.
Argument:
dim -- size of the w vector we want (or number of parameters in this case)
Returns:
w -- initialized vector of shape (dim, 1)
b -- initialized scalar (corresponds to the bias)
"""
w = np.zeros((dim ,1))
b = 0
assert(w.shape == (dim, 1))
assert(isinstance(b, float) or isinstance(b, int))
return w, b
前向传播和反向传播,已经获得降低cost
下面几个公式很有用
A是预测结果的函数,最终目标就是找到最优的w和b的值,然后
输入图片,通过A函数求值,判断输出
cost J 公式如下,cost理论上越小越好
cost 对w和b的偏导数如下
对应的代码
def propagate(w, b, X, Y):
"""
Implement the cost function and its gradient for the propagation explained above
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (num_px * num_px * 3, number of examples)
Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples)
Return:
cost -- negative log-likelihood cost for logistic regression
dw -- gradient of the loss with respect to w, thus same shape as w
db -- gradient of the loss with respect to b, thus same shape as b
"""
m = X.shape[1]
# FORWARD PROPAGATION (FROM X TO COST)
A = sigmoid(np.dot(w.T,X)+b)
# compute activation
cost = np.sum(Y*np.log(A)+np.log(1-A)*(1-Y))/-m
print(cost)
# compute cost
# BACKWARD PROPAGATION (TO FIND GRAD)
dw = np.dot(X,(A-Y).T)/m
db = np.sum(A-Y)/m
assert(dw.shape == w.shape)
assert(db.dtype == float)
cost = np.squeeze(cost)
assert(cost.shape == ())
grads = {"dw": dw,
"db": db}
return grads, cost
然后对cost 这些参数可以优化,拿到个局部最优解
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
"""
This function optimizes w and b by running a gradient descent algorithm
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of shape (num_px * num_px * 3, number of examples)
Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples)
num_iterations -- number of iterations of the optimization loop
learning_rate -- learning rate of the gradient descent update rule
print_cost -- True to print the loss every 100 steps
Returns:
params -- dictionary containing the weights w and bias b
grads -- dictionary containing the gradients of the weights and bias with respect to the cost function
costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve.
"""
costs = []
for i in range(num_iterations):
# Cost and gradient calculation
grads, cost = propagate(w,b,X,Y)
# Retrieve derivatives from grads
dw = grads["dw"]
db = grads["db"]
# update rule
w = w-learning_rate*dw
b = b-learning_rate*db
# Record the costs
if i % 100 == 0:
costs.append(cost)
# Print the cost every 100 training examples
if print_cost and i % 100 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
params = {"w": w,
"b": b}
grads = {"dw": dw,
"db": db}
return params, grads, costs
预测结果
def predict(w, b, X):
'''
Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (num_px * num_px * 3, number of examples)
Returns:
Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X
'''
m = X.shape[1]
Y_prediction = np.zeros((1,m))
w = w.reshape(X.shape[0], 1)
# Compute vector "A" predicting the probabilities of a cat being present in the picture
A = sigmoid(np.dot(w.T,X)+b)
for i in range(A.shape[1]):
# Convert probabilities A[0,i] to actual predictions p[0,i]
Y_prediction[0,i]=0 if A[0,i]<=0.5 else 1
assert(Y_prediction.shape == (1, m))
return Y_prediction
整个代码组合下就是
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
"""
Builds the logistic regression model by calling the function you've implemented previously
Arguments:
X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train)
Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train)
X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test)
Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test)
num_iterations -- hyperparameter representing the number of iterations to optimize the parameters
learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize()
print_cost -- Set to true to print the cost every 100 iterations
Returns:
d -- dictionary containing information about the model.
"""
# initialize parameters with zeros
w, b = initialize_with_zeros(len(X_train))
# Gradient descent
parameters, grads, costs = optimize(w,b,X_train,Y_train,num_iterations , learning_rate , print_cost )
# Retrieve parameters w and b from dictionary "parameters"
w = parameters["w"]
b = parameters["b"]
# Predict test/train set examples
Y_prediction_test = predict(w,b,X_test)
Y_prediction_train = predict(w,b,X_train)
# Print train/test Errors
print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))
d = {"costs": costs,
"Y_prediction_test": Y_prediction_test,
"Y_prediction_train" : Y_prediction_train,
"w" : w,
"b" : b,
"learning_rate" : learning_rate,
"num_iterations": num_iterations}
return d
跑了model函数以后的,验证代码
d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 3000, learning_rate = 0.007, print_cost = True)
my_image = "timg.jpg" # change this to the name of your image file
# We preprocess the image to fit your algorithm.
fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T
my_predicted_image = predict(d["w"], d["b"], my_image)
plt.imshow(image)#在ui上显示图片
print("y = " + str(np.squeeze(my_predicted_image)) + ")
结语
有些线代方面的知识已经还给老师了,有时间还是要搞本周志华老师的西瓜书看看,总之还是好好学习天天向上吧。