Logistic Regression with a Neural Network mindset
用神经网络的思想来实现Logistic回归
学习目标
- 构建深度学习算法的基本结构,包括:
- 初始化参数
- 计算损失函数和它的梯度
- 使用优化算法(梯度下降法)
- 将上述三种函数按照正确的顺序集中在一个主函数中
1. 依赖包
*numpy——python中用于科学计算的库,多用于计算矩阵
*h5py——在Python提供读取HDF5二进制数据格式文件的接口,本次的训练及测试图片集是以HDF5储存的
*matplotlib——Python中著名的绘图库
*PIL——Python Image Library,为Python提供图像处理功能
*scipy——基于NumPy来做高等数学、信号处理、优化、统计和许多其它科学任务的拓展库
为了使用上述依赖包(库),使用如下代码导入:
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset
注意:在Ipython编译器中可以使用%matplotlib inline,而其它编译器中使用该魔发指令会编译报错,需要自己添加plt.show()函数才能显示图片,这在接下来的数据集可视化中用得到。
2. 总览问题集
问题陈述:给定一个数据集(“data.h5”),其中包含:
- 包含m个已标注数据的训练集,其中若是猫(y=1),不是猫(y=0)
- 包含m个已标注数据集的测试集,同样分为猫或者非猫
- 每一幅图的shape为(num_px,num_px,3),其中3代表3通道(RGB)。因此,每一幅图都是正方形的,及长宽相等
使用如下代码读取(载入)数据:
# Loading the data (cat/non-cat)
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
这里再训练集和测试集的样本后面加_orig,是因为随后还要对这些数据reshape进行处理,此时它们还是拥有二维结构的矩阵。
可以通过下列代码将数据集中的数据实现可视化:
# Example of a picture
index = 24
plt.imshow(train_set_x_orig[index])
print ("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode("utf-8") + "' picture.")
通过改变index = 后面的数字值,可以查看数据集中不同的图片。
执行结果:
注意:保证数据集中每一个数据的尺寸的统一,将对减少程序中的bug帮助很大。
小练习:
- 认识到m_train中的样本个数
- 认识到m_test中的样本个数
- 认识到num_px的数值,即了解图像的大小(是多少像素*多少像素)
这里老师提示说,我们先前提到的未处理的数据集,即带有orig的数据集,它的尺寸为(m_train,num_px,num_px,3)。我的个人理解就是(训练集的个数,图像高的像素值,图像宽的像素值,3通道)。
使用如下代码,来实现小练习中的任务要求:
### START CODE HERE ### (≈ 3 lines of code)
m_train = train_set_x_orig.shape[0]
m_test = test_set_x_orig.shape[0]
num_px = train_set_x_orig.shape[1]
### END CODE HERE ###
print ("Number of training examples: m_train = " + str(m_train))
print ("Number of testing examples: m_test = " + str(m_test))
print ("Height/Width of each image: num_px = " + str(num_px))
print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)")
print ("train_set_x shape: " + str(train_set_x_orig.shape))
print ("train_set_y shape: " + str(train_set_y.shape))
print ("test_set_x shape: " + str(test_set_x_orig.shape))
print ("test_set_y shape: " + str(test_set_y.shape))
而shape[0]中的0,我的个人理解就是0访问的是shape的参数中第一个的数,1为第二位……以此类推
因此执行结果:
Number of training examples: m_train = 209 Number of testing examples: m_test = 50 Height/Width of each image: num_px = 64 Each image is of size: (64, 64, 3) train_set_x shape: (209, 64, 64, 3) train_set_y shape: (1, 209) test_set_x shape: (50, 64, 64, 3) test_set_y shape: (1, 50)
也就是说,数据集中,训练集有209副图,测试集有50幅图,每一幅图是64*64的大小(上面可视化的执行结果就可以看出来)。
还记得老师上课说过,我们要将3个叠加在一起的矩阵展开,变成一个一维数组,那么对于其中的一幅图,它将由(64,64,3)的结构展开成(64*64*3,1)的结构。而我们拥有m(209)个训练样本,那么所有的输入将会变为一个12288行,m(209)列的矩阵。而为了实现上述操作,我们使用reshape操作。
小练习:将形状为(num_px,num_px,3)的训练集和数据集展为一维的(num_px*num_px*3,1)的向量。
小窍门:当欲将一个形如(a,b,c,d)的矩阵X展平为一个形如(b*c*d,a)的矩阵,可以使用
X_flatten = X.reshape(X.shape[0], -1).T # X.T is the transpose of X
使用如下代码,进行reshape操作:
# Reshape the training and test examples
### START CODE HERE ### (≈ 2 lines of code)
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
### END CODE HERE ###
print ("train_set_x_flatten shape: " + str(train_set_x_flatten.shape))
print ("train_set_y shape: " + str(train_set_y.shape))
print ("test_set_x_flatten shape: " + str(test_set_x_flatten.shape))
print ("test_set_y shape: " + str(test_set_y.shape))
print ("sanity check after reshaping: " + str(train_set_x_flatten[0:5,0]))
这里解释一下train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T这句中的-1参数,-1代表的是行数(因为后面有转置)由系统自己决定,大意就是反正我丢给你这么一个矩阵,我需要209列,多少行你自己看着办吧!系统一看,明白了大哥,知道了大哥,小的这就去办,变成了64*64*3的行数。
输出结果:
最后一行是输出了train_set_x_flatten中前5个数的值,用于检查。
老师这里说需要牢记的是:
一般预处理一个数据集的步骤如下:
- 计算出数据集的维度和形状(如训练集的个数、测试集的个数、图片的大小等等)
- 像例子中那样reshape数据集,将其变为一个向量(num_px*numpx*3,1)
- 标准化数据
为何要标准化我这里产生了疑问,这里引用博主index20001的内容:
数据的标准化(normalization)是将数据按比例缩放,使之落入一个小的特定区间。在一些数据比较和评价中常用到。典型的有归一化法,还有比如极值法、标准差法。
归一化方法的主要有两种形式:一种是把数变为(0,1)之间的小数,一种是把有量纲表达式变为无量纲表达式。在数字信号处理中是简化计算的有效方式。
而在本例中,我们处理的数据集是图像,每一个值都是像素值,介于0~255之间,那么对于这样的数据进行标准化很简单,只需要进行:
train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.
因为0/255=0, 255/255=1,轻松地将数据变为了(0,1)的量。
3. 学习算法的一般结构
说了这么多,终于到构建算法来区分猫图的时候了。
我们使用神经网络的思想来实现logistic回归,正如上图所示,是一种十分简单的神经网络。
从数学角度来解释算法:
对于单一的一幅图
回顾以前学习的内容,成本函数为:
关键步骤:在这个练习中执行以下步骤:
- 初始化模型参数
- 通过最小化成本来习得参数
- 通过习得的参数来进行预测(在测试集上)
- 分析结果得出结论
4. 分部实现算法
建立神经网络的主要步骤如下:
1. 定义模型结构(例如输入的特征数)
2.初始化模型参数
3.循环:
- 计算当前损失(前向传播)
- 计算当前梯度(反向传播)
- 更新参数(梯度下降)
通常将1~3步单独建立,然后最后整合在一个叫做model()的函数中。
4.1 辅助函数
小练习:建立sigmoid()函数。sigmoid函数定义为:,使用np.exp()来构建sigmoid函数。
函数代码如下:
# GRADED FUNCTION: sigmoid
def sigmoid(z):
"""
Compute the sigmoid of z
Arguments:
z -- A scalar or numpy array of any size.
Return:
s -- sigmoid(z)
"""
### START CODE HERE ### (≈ 1 line of code)
s = 1 / (1 + np.exp(-z))
### END CODE HERE ###
return s
做个小测试:
print ("sigmoid([0, 2]) = " + str(sigmoid(np.array([0,2]))))
输出结果
sigmoid([0, 2]) = [0.5 0.88079708]
4.2 初始化参数
小练习:使用np.zeros()函数初始化参数,将w初始化为0向量。
代码如下:
# GRADED FUNCTION: initialize_with_zeros
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)
"""
### START CODE HERE ### (≈ 1 line of code)
w = np.zeros((dim, 1))
b = 0
### END CODE HERE ###
assert(w.shape == (dim, 1))
assert(isinstance(b, float) or isinstance(b, int))
return w, b
其中w=np.zeros((dim,1))中dim的理解就是说还是待定,它可以随着我们输入的向量X随时变化。
关于np.zeros()函数的详细说明可以参考云金杞博主的文章。
比如我们设置维度dim=2,输出一个示例:
dim = 2
w, b = initialize_with_zeros(dim)
print ("w = " + str(w))
print ("b = " + str(b))
输出结果:
w = [[0.] [0.]] b = 0
那么对于我们这个例子中,dim的取值就是num_px*num_px*3=12288维。
4.3 前向和反向传播
初始化了向量之后,就可以进行前向传播和反向传播步骤了。
小练习:定义函数propagate()来计算成本函数和它的梯度。
提示:
前向传播:
现在有了输入X
计算A,
计算成本函数:
这里需要用到两个公式:
代码如下:
# GRADED FUNCTION: propagate
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
Tips:
- Write your code step by step for the propagation. np.log(), np.dot()
"""
m = X.shape[1]
# FORWARD PROPAGATION (FROM X TO COST)
### START CODE HERE ### (≈ 2 lines of code)
A = sigmoid(np.dot(w.T, X) + b) # compute activation
cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A)) # compute cost
### END CODE HERE ###
# BACKWARD PROPAGATION (TO FIND GRAD)
### START CODE HERE ### (≈ 2 lines of code)
dw = 1 / m * np.dot(X, (A - Y).T)
db = 1 / m * np.sum(A - Y)
### END CODE HERE ###
assert(dw.shape == w.shape)
assert(db.dtype == float)
cost = np.squeeze(cost)
assert(cost.shape == ())
grads = {"dw": dw,
"db": db}
return grads, cost
测试输出结果:
定义w,b,X,Y如下:
w, b, X, Y = np.array([[1],[2]]), 2, np.array([[1,2],[3,4]]), np.array([[1,0]])
计算dw、db和cost
grads, cost = propagate(w, b, X, Y)
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
print ("cost = " + str(cost))
输出结果如下:
最优化
- 目前已经初始化了参数
- 目前可以计算成本函数和它的梯度
- 现在,需要使用梯度下降方法来更新参数
小练习:定义优化函数,目标是通过习得w和b的值来最小化成本函数J。用θ举例的话:θ=θ-αdθ,其中α是学习率。
代码如下:
# GRADED FUNCTION: optimize
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.
Tips:
You basically need to write down two steps and iterate through them:
1) Calculate the cost and the gradient for the current parameters. Use propagate().
2) Update the parameters using gradient descent rule for w and b.
"""
costs = []
for i in range(num_iterations):
# Cost and gradient calculation (≈ 1-4 lines of code)
### START CODE HERE ###
grads, cost = propagate(w, b, X, Y)
### END CODE HERE ###
# Retrieve derivatives from grads
dw = grads["dw"]
db = grads["db"]
# update rule (≈ 2 lines of code)
### START CODE HERE ###
w = w - learning_rate * dw
b = b - learning_rate * db
### END CODE HERE ###
# 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
测试输出:
params, grads, costs = optimize(w, b, X, Y, num_iterations= 100, learning_rate = 0.009, print_cost = False)
print ("w = " + str(params["w"]))
print ("b = " + str(params["b"]))
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
print("costs="+str(costs))
结果如下
w = [[0.1124579 ] [0.23106775]] b = 1.5593049248448891 dw = [[0.90158428] [1.76250842]] db = 0.4304620716786828 costs=[6.000064773192205]
小练习:通过上述函数我们计算出了习得的w和b的值,我们通过习得的w和b的值来预测数据集X的标签。通过定义predict()函数,用如下两步计算预测值:
1.计算yhat,
2.将预测结果转化为0(如果激活值<=0.5)或者1(激活值>=0.5),将预测结果储存在向量y_prediction中。如果你想的话,可以在for循环中使用if/else语句。
代码如下:
# GRADED FUNCTION: predict
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
### START CODE HERE ### (≈ 1 line of code)
A = sigmoid(np.dot(w.T, X) + b)
### END CODE HERE ###
for i in range(A.shape[1]):
# Convert probabilities A[0,i] to actual predictions p[0,i]
### START CODE HERE ### (≈ 4 lines of code)
if A[0, i] <= 0.5:
Y_prediction[0, i] = 0
else:
Y_prediction[0, i] = 1
### END CODE HERE ###
assert(Y_prediction.shape == (1, m))
return Y_prediction
需要记住的是:我们已经定义了多个函数:
- 初始化函数,initialize(w,b)
- 通过反复迭最优化parameters(w,b):
- 计算成本和和它的梯度
- 通过梯度下降法更新参数
- 使用习得的(w,b)来预测给定样本的标签。
5. 将所有函数整合在model中
现在要将之前分别定义的每一个函数按照正确顺序整合在model中。
小练习:按照如下的提示构建model()函数:
- Y_prediction用来表示测试集上的预测值
- Y_prediction_train用来表示训练集上的预测值
- w,costs,grads用来作为optimize()的输出
代码如下:
# GRADED FUNCTION: model
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.
"""
### START CODE HERE ###
# initialize parameters with zeros (≈ 1 line of code)
w, b = initialize_with_zeros(X_train.shape[0])
# Gradient descent (≈ 1 line of code)
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 (≈ 2 lines of code)
Y_prediction_test = predict(w, b, X_test)
Y_prediction_train = predict(w, b, X_train)
### END CODE HERE ###
# 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
输出测试:
d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)
输出结果:
Cost after iteration 0: 0.693147 Cost after iteration 100: 0.584508 Cost after iteration 200: 0.466949 Cost after iteration 300: 0.376007 Cost after iteration 400: 0.331463 Cost after iteration 500: 0.303273 Cost after iteration 600: 0.279880 Cost after iteration 700: 0.260042 Cost after iteration 800: 0.242941 Cost after iteration 900: 0.228004 Cost after iteration 1000: 0.214820 Cost after iteration 1100: 0.203078 Cost after iteration 1200: 0.192544 Cost after iteration 1300: 0.183033 Cost after iteration 1400: 0.174399 Cost after iteration 1500: 0.166521 Cost after iteration 1600: 0.159305 Cost after iteration 1700: 0.152667 Cost after iteration 1800: 0.146542 Cost after iteration 1900: 0.140872 train accuracy: 99.04306220095694 % test accuracy: 70.0 %
注解:训练的准确率接近100%。这证明我们定义的模型起作用了,并且对于训练集的适应性很高。测试准确率68%,对于一个简单的模型来说这个结果并不差,给定一个小的数据集通过logistic做线性分类,已经不错了。
当前还存在针对训练集过拟合的问题,待会可以通过正则化来减少过拟合。
使用如下代码来测试当前模型对图片的分类能力:
# Example of a picture that was wrongly classified.
index = 1
plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))
print ("y = " + str(test_set_y[0,index]) + ", you predicted that it is a \"" + classes[int(d["Y_prediction_test"][0,index])].decode("utf-8") + "\" picture.")
这里说一下,因为准确率只有68%左右,因此测试结果很容易出错。
y = 1, you predicted that it is a "cat" picture.
y = 0, you predicted that it is a "non-cat" picture.
通过下面的代码来显示成本的值和梯度:
# Plot learning curve (with costs)
costs = np.squeeze(d['costs'])
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
plt.title("Learning rate =" + str(d["learning_rate"]))
plt.show()
注解:图中可以看到成本值不断下降,这表明参数已经习得。
在这里说一下过拟合,当我们增加迭代次数,我们会发现在训练集上的准确率提高了,但是测试集上准确率反而下降。
迭代2000次:
点错迭代了70000次之后……发现
Cost after iteration 69700: 0.004497 Cost after iteration 69800: 0.004490 Cost after iteration 69900: 0.004484 train accuracy: 100.0 % test accuracy: 72.0 %
这……
6. 进一步分析(选修练习)
选择学习率
提醒:为了让梯度下降可以有效地进行,必须选择合适的学习率。学习率α代表我们更新参数的快速程度。学习率太大我们可能会错过最优解,同样的,太小的话我们需要迭代很多次才能找到最优解。这就是使用合适的学习率的重要性。
让我们比对选择不同学习率时我们设立模型的学习曲线。
代码如下:
learning_rates = [0.01, 0.001, 0.0001]
models = {}
for i in learning_rates:
print ("learning rate is: " + str(i))
models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False)
print ('\n' + "-------------------------------------------------------" + '\n')
for i in learning_rates:
plt.plot(np.squeeze(models[str(i)]["costs"]), label= str(models[str(i)]["learning_rate"]))
plt.ylabel('cost')
plt.xlabel('iterations')
legend = plt.legend(loc='upper center', shadow=True)
frame = legend.get_frame()
frame.set_facecolor('0.90')
plt.show()
执行结果如下:
learning rate is: 0.01 train accuracy: 99.52153110047847 % test accuracy: 68.0 % ------------------------------------------------------- learning rate is: 0.001 train accuracy: 88.99521531100478 % test accuracy: 64.0 % ------------------------------------------------------- learning rate is: 0.0001 train accuracy: 68.42105263157895 % test accuracy: 36.0 % -------------------------------------------------------
、
7 用自己的图片做测试(选修练习)
将自己的图片放好后,修改下列代码中图片的名称后执行代码来预测:
## START CODE HERE ## (PUT YOUR IMAGE NAME)
my_image = "cat_in_iran.jpg" # change this to the name of your image file
## END CODE HERE ##
# 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)
print("y = " + str(np.squeeze(my_predicted_image)) + ", your algorithm predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") + "\" picture.")
执行结果:
y = 1.0, your algorithm predicts a "cat" picture.
y = 0.0, your algorithm predicts a "non-cat" picture.
效果还不错,:-p
总结
1. 预处理数据集是很重要的
2. 单独建立了所需函数:initialize()、propagate()、optimize()。最后将他们整合在model()中。
3. 调整学习率将对算法产生巨大的改变。