欢迎来到你的第一个编程作业,在这次作业中你将会用逻辑回归去识别一个猫。并且在这次作业中你将会用神经网络的思维去一步一步的去解决这个问题和磨练你的深度学习的直觉。
说明:
- 在你的代码中不能使用for或while循环,除非说明明确要你这么做。
你将会学习到:
1.建立一个学习算法的一般结构,包括
- 初始化参数
- 计算代价函数和它的梯度
- 使用最优化算法(梯度下降)
2.用正确的顺序将上面三个函数集合到一个主函数模型里。
1 程序包
h5py 是与存储在一个H5文件上的数据集交互的公共包。
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
%matplotlib inline
2 问题集的概述
问题集合”data.h5”包括
- 被标记的训练集m_train
- 未标记的测试集m_test
- 每个图像由(num_px, num_px, 3)构成,对应于(height ,width,channels)
# Loading the data (cat/non-cat)
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
我们在图像集前加了 “_orig” 表示预处理前。
我们也可以通过索引显示出来。
# Example of a picture
index = 25
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.")
问题:找出下面的值
- m_train(训练样例的个数)
- m_test(测试样例的个数)
- num_px (= height = width 的训练图片)
### 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))
输出: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: (209L, 64L, 64L, 3L)
train_set_y shape: (1L, 209L)
test_set_x shape: (50L, 64L, 64L, 3L)
test_set_y shape: (1L, 50L)
问题: 重构训练集和测试集使得一个矩阵图像扁平成一个向量。
X_flatten = X.reshape(X.shape[0], -1).T # X.T is the transpose of X
# 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 shape: (12288L, 209L)
train_set_y shape: (1L, 209L)
test_set_x_flatten shape: (12288L, 50L)
test_set_y shape: (1L, 50L)
sanity check after reshaping: [17 31 56 22 33]
归一化数据集
train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.
这部分内容需要你记住的是:
预处理一个数据集的一般步骤是
- 找出数据集的维度和形状(m_train, m_test, num_px, …)
- 重构数据集为一个向量 (num_px * num_px * 3, 1)
- 归一化数据
3 学习算法的一般架构
以下过程解释了为什么逻辑回归是一个非常简单的神经网络
算法的数学表达式
通过对所有样例之和,求代价函数
关键步骤:
- 初始化模型参数
- 通过最小化代价函数,学习模型参数
- 通过学习到的模型在测试集做预测
- 分析结果和总结
4 构建算法的各个部分
建立神经网络的主要步骤:
- 定义模型结构(例如输入特征的数量)
- 初始化模型参数
- 循环部分
计算当前的损失函数(向前传播);
计算损失函数的梯度(反向传播);
更新参数(梯度下降)。
通常构建1—3个函数,并把它们集合到一个主函数main()中。
4.1 辅助函数
为了做预测,利用上次作业的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 = N1 / (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 初始化参数
将w初始化为与x同维度的零向量
# 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
dim = 2
w, b = initialize_with_zeros(dim)
print ("w = " + str(w))
print ("b = " + str(b))
输出:w = [[ 0.]
[ 0.]]
b = 0
如果输入为图片,w将会是(num_px ×× num_px ×× 3, 1)。
4.3 向前传播和向后传播
实现propagate(),计算代价函数和他的梯度。
# 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 = np.array([[1],[2]]), 2, np.array([[1,2],[3,4]]), np.array([[1,0]])
grads, cost = propagate(w, b, X, Y)
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
print ("cost = " + str(cost))
输出:dw = [[ 0.]
[ 0.]]
db = 0.0
cost = 12.0001295464
用梯度下降的方法进行优化
通过最小化损失函数J,学习参数w,b。对于参数P,
更新法则是P=P - a dP,在这里a是学习速率
# 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)
输出:w = [[ 1.]
[ 2.]]
b = 2.0
dw = [[ 0.]
[ 0.]]
db = 0.0
[12.000129546384411]
通过w和b预测X的标签
- 计算
- 以0.5为阈值,预测X的标签。
# 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
print ("predictions = " + str(predict(w, b, X)))
输出:predictions = [[ 1. 1.]]
你需要记住的是,你可以实现一系列的函数
- 初始化(w,b)
- 从学习到的(w,b)当中最优化
计算损失函数和它的梯度
利用梯度下降更新参数 - 根据学习到的(w,b)预测样本集的标签
5 将所有函数集合在模型当中
利用先前的符号,实现模型函数
- 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: 144.867761
Cost after iteration 100: 144.867761
Cost after iteration 200: 144.867761
Cost after iteration 300: 144.867761
Cost after iteration 400: 144.867761
Cost after iteration 500: 144.867761
Cost after iteration 600: 144.867761
Cost after iteration 700: 144.867761
Cost after iteration 800: 144.867761
Cost after iteration 900: 144.867761
Cost after iteration 1000: 144.867761
Cost after iteration 1100: 144.867761
Cost after iteration 1200: 144.867761
Cost after iteration 1300: 144.867761
Cost after iteration 1400: 144.867761
Cost after iteration 1500: 144.867761
Cost after iteration 1600: 144.867761
Cost after iteration 1700: 144.867761
Cost after iteration 1800: 144.867761
Cost after iteration 1900: 144.867761
train accuracy: 65.5502392344 %
test accuracy: 34.0 %
改变索引值,观察对测试集的预测
# 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.")
输出:y = 1, you predicted that it is a “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()
解释
可以看到损失函数在下降。它显示了这些参数正在被学习。但是,也可以看到,在训练集上对模型进行更多的训练,尝试增加单元中的迭代次数,并重新运行单元格。可能会看到训练集的准确性提高了,但是测试集的准确性下降了。这就是所谓的过度拟合。
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 %
解释:
- 不同的学习速率将会有不同的代价函数,因此有不同的预测结果。
- 学习速率太大(0.01),代价函数可能出现最大的波动。
- 代价函数太低,要注意过多你喝的发生。
- 在深度学习中推荐
降低代价函数的学习速率。
如果模型出现过拟合,我们可以采用其他方法降低过拟合。
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.
我们在这次的作业中需要意识到:
- 对数据集的预处理很重要。
- 独立实现每一个函数(initialize(), propagate(), optimize()),然后构建你的模型model()。
- 学习速率将会对算法产生巨大的影响。
另外的练习
- 试验学习速率和迭代次数的关系。
- 尝试不同的初始化方式,并比较其影响。
- 测试其他的预处理(数据中心,或者按其标准偏差划分每一行)
参考文献:
http://www.wildml.com/2015/09/implementing-a-neural-network-from-scratch/
https://stats.stackexchange.com/questions/211436/why-do-we-normalize-images-by-subtracting-the-datasets-image-mean-and-not-the-c