1- 准备工作:
需要预先安装的环境:
- numpy
- matplotlib
- h5py
- PIL 和scipy
- dnn_app_utils是自定义的函数列表,该函数在上一次的作业中(Building your Deep Neural Network: Step by Step)有使用到。
- np.random.seed(1) 是为了确保所有的随机函数在调用的时候具有一致性。
环境测试:
import time
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
from dnn_app_utils_v2 import *
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
%load_ext autoreload
%autoreload 2
np.random.seed(1)
2- 数据集
本文依旧是采用之前用过的猫分类的数据集(“data.h5”):
- m_train个训练样本。已经做标注cat (1) or non-cat (0)
- m_test个测试样本,同样也做了标注。
- 每个图像的尺寸是 (num_px, num_px, 3) 其中3表示RGB通道。
数据加载和显示。
load_data函数的定义在附属的文件中:
train_x_orig, train_y, test_x_orig, test_y, classes = load_data()
index = 7
plt.imshow(train_x_orig[index])
print ("y = " + str(train_y[0,index]) + ". It's a " + classes[train_y[0,index]].decode("utf-8") + " picture.")
输出结果:
y = 1. It's a cat picture.
可以改变index值,显示不同的图像。
获取数据集的尺寸信息:
# Explore your dataset
m_train = train_x_orig.shape[0]
num_px = train_x_orig.shape[1]
m_test = test_x_orig.shape[0]
print ("Number of training examples: " + str(m_train))
print ("Number of testing examples: " + str(m_test))
print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)")
print ("train_x_orig shape: " + str(train_x_orig.shape))
print ("train_y shape: " + str(train_y.shape))
print ("test_x_orig shape: " + str(test_x_orig.shape))
print ("test_y shape: " + str(test_y.shape))
输出结果:
Number of training examples: 209
Number of testing examples: 50
Each image is of size: (64, 64, 3)
train_x_orig shape: (209, 64, 64, 3)
train_y shape: (1, 209)
test_x_orig shape: (50, 64, 64, 3)
test_y shape: (1, 50)
同样,我们需要对图像进行reshape操作,使得每一张图像在输入矩阵上是一个列向量。
图像reshape操作:
# Reshape the training and test examples
train_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T # The "-1" makes reshape flatten the remaining dimensions
test_x_flatten = test_x_orig.reshape(test_x_orig.shape[0], -1).T
# Standardize data to have feature values between 0 and 1.
train_x = train_x_flatten/255.
test_x = test_x_flatten/255.
print ("train_x's shape: " + str(train_x.shape))
print ("test_x's shape: " + str(test_x.shape))
输出结果:
train_x's shape: (12288, 209)
test_x's shape: (12288, 50)
3- 模型框架
本文将创建2个模型,一个是双层的神经网络,一个是L层的神经网络。
在此基础上,可以对不同的L值模型进行对比。
3-1 双层神经网络
该模型可以简化为: INPUT -> LINEAR -> RELU -> LINEAR -> SIGMOID -> OUTPUT.
我们需要注意:
- 输入图像尺寸= (64,64,3) ,通过reshape操作之后变为 (12288,1) 。
- 每个样本的输入形如: [x0,x1,...,x12287]T ,该输入矩阵再与权重矩阵 W[1] (尺寸= (n[1],12288) )相乘。
- 再加上偏移项,并输入到激活函数relu,其输出为 [a[1]0,a[1]1,...,a[1]n[1]−1]T .
- 将上述的输出结果和 权重矩阵 W[2] 相乘,再加上对应的偏移项。
- 将上述结果输入到sigmoid的激活函数,当输出结果>0.5, 则认为是猫。
3.2 - L层神经网络
L层神经网络模型:
该模型可以简化为: [LINEAR -> RELU] × (L-1) -> LINEAR -> SIGMOID
我们需要注意:
- 输入尺寸为(64,64,3)的图像,还是先被扁平化为(12288,1)的向量。
- 扁平化的输入向量 [x0,x1,...,x12287]T 再和权重矩阵 W[1] 想乘,结果在加上偏移量 b[1] 。这个过程称为linear unit。
- 紧接着将linear unit结果输入到relu激活函数 。由于该层神经网络存在多个神经元,所以该步骤会对位于该层的神经元,都处理一次。对应的权重矩阵为 (W[l],b[l]) 。
- 最后,将最终输出的 linear unit输入到sigmoid的激活函数,如果该激活函数的输出结果值>0.5,则视为是猫。
3.3 - 通用模型
我们一般是采用以下方法进行建模:
1. 参数初始化 / 定义超参数
2. 进行一定多次的迭代:
a. 前向传播
b. 计算代价函数
c. 后向传播
d. 参数更新
4. 采用训练得到的参数做预测
4- 双层神经网络
我们已经知道双层神经网络的模型是LINEAR -> RELU -> LINEAR -> SIGMOID.
结合之前的学习,我们需要以下的一些操作:
def initialize_parameters(n_x, n_h, n_y):
...
return parameters
def linear_activation_forward(A_prev, W, b, activation):
...
return A, cache
def compute_cost(AL, Y):
...
return cost
def linear_activation_backward(dA, cache, activation):
...
return dA_prev, dW, db
def update_parameters(parameters, grads, learning_rate):
...
return parameters
这些函数在之前都已经实现,在此不再详细说明。
# GRADED FUNCTION: two_layer_model
def two_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):
"""
Implements a two-layer neural network: LINEAR->RELU->LINEAR->SIGMOID.
Arguments:
X -- input data, of shape (n_x, number of examples)
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
layers_dims -- dimensions of the layers (n_x, n_h, n_y)
num_iterations -- number of iterations of the optimization loop
learning_rate -- learning rate of the gradient descent update rule
print_cost -- If set to True, this will print the cost every 100 iterations
Returns:
parameters -- a dictionary containing W1, W2, b1, and b2
"""
np.random.seed(1)
grads = {}
costs = [] # to keep track of the cost
m = X.shape[1] # number of examples
(n_x, n_h, n_y) = layers_dims
# Initialize parameters dictionary, by calling one of the functions you'd previously implemented
### START CODE HERE ### (≈ 1 line of code)
parameters = initialize_parameters(n_x, n_h, n_y)
### END CODE HERE ###
# Get W1, b1, W2 and b2 from the dictionary parameters.
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
# Loop (gradient descent)
for i in range(0, num_iterations):
# Forward propagation: LINEAR -> RELU -> LINEAR -> SIGMOID. Inputs: "X, W1, b1". Output: "A1, cache1, A2, cache2".
### START CODE HERE ### (≈ 2 lines of code)
A1, cache1 = linear_activation_forward(X, W1, b1, activation = "relu")
A2, cache2 = linear_activation_forward(A1, W2, b2, activation = "sigmoid")
### END CODE HERE ###
# Compute cost
### START CODE HERE ### (≈ 1 line of code)
cost = compute_cost(A2, Y)
### END CODE HERE ###
# Initializing backward propagation
dA2 = - (np.divide(Y, A2) - np.divide(1 - Y, 1 - A2))
# Backward propagation. Inputs: "dA2, cache2, cache1". Outputs: "dA1, dW2, db2; also dA0 (not used), dW1, db1".
### START CODE HERE ### (≈ 2 lines of code)
dA1, dW2, db2 = linear_activation_backward(dA2, cache2, activation = "sigmoid")
dA0, dW1, db1 = linear_activation_backward(dA1, cache1, activation = "relu")
### END CODE HERE ###
# Set grads['dWl'] to dW1, grads['db1'] to db1, grads['dW2'] to dW2, grads['db2'] to db2
grads['dW1'] = dW1
grads['db1'] = db1
grads['dW2'] = dW2
grads['db2'] = db2
# Update parameters.
### START CODE HERE ### (approx. 1 line of code)
parameters = update_parameters(parameters, grads, learning_rate)
### END CODE HERE ###
# Retrieve W1, b1, W2, b2 from parameters
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
# Print the cost every 100 training example
if print_cost and i % 100 == 0:
print("Cost after iteration {}: {}".format(i, np.squeeze(cost)))
if print_cost and i % 100 == 0:
costs.append(cost)
# plot the cost
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
return parameters
测试代码:
n_x = 12288# num_px * num_px * 3
n_h = 7
n_y = 1
layers_dims = (n_x, n_h, n_y)
parameters = two_layer_model(train_x, train_y, layers_dims = (n_x, n_h, n_y), num_iterations = 2500, print_cost=True)
测试代码运行结果:
Cost after iteration 0: 0.6930497356599888
Cost after iteration 100: 0.6464320953428849
Cost after iteration 200: 0.6325140647912677
Cost after iteration 300: 0.6015024920354665
Cost after iteration 400: 0.5601966311605747
Cost after iteration 500: 0.5158304772764729
Cost after iteration 600: 0.47549013139433255
Cost after iteration 700: 0.43391631512257495
Cost after iteration 800: 0.4007977536203886
Cost after iteration 900: 0.3580705011323798
Cost after iteration 1000: 0.3394281538366412
Cost after iteration 1100: 0.3052753636196264
Cost after iteration 1200: 0.2749137728213015
Cost after iteration 1300: 0.24681768210614846
Cost after iteration 1400: 0.19850735037466108
Cost after iteration 1500: 0.17448318112556654
Cost after iteration 1600: 0.17080762978096023
Cost after iteration 1700: 0.11306524562164728
Cost after iteration 1800: 0.09629426845937154
Cost after iteration 1900: 0.08342617959726861
Cost after iteration 2000: 0.07439078704319084
Cost after iteration 2100: 0.06630748132267932
Cost after iteration 2200: 0.05919329501038171
Cost after iteration 2300: 0.053361403485605564
Cost after iteration 2400: 0.04855478562877018
Figure 4: 代价函数随着迭代次数的变化
完成2层神经网络模型训练之后,可以进行预测操作:
predictions_train = predict(train_x, train_y, parameters)
运行结果:
Accuracy: 1.0
对于测试数据集:
predictions_test = predict(test_x, test_y, parameters)
准确率为Accuracy: 0.72
这高于之前的逻辑回归70%的分类结果。
在模型训练过程中,如果迭代次数少些,如1500,则测试数据集的准确率更高,这是所谓的early stopping,这可以有效地防止过拟合。
5- L层神经网络
模型可以简化为:[LINEAR -> RELU]××(L-1) -> LINEAR -> SIGMOID
在L层神经网络实现过程中,我们会用到之前编写的函数:
def initialize_parameters_deep(layer_dims):
...
return parameters
def L_model_forward(X, parameters):
...
return AL, caches
def compute_cost(AL, Y):
...
return cost
def L_model_backward(AL, Y, caches):
...
return grads
def update_parameters(parameters, grads, learning_rate):
...
return parameters
代码实现:
# GRADED FUNCTION: L_layer_model
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):#lr was 0.009
"""
Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID.
Arguments:
X -- data, numpy array of shape (number of examples, num_px * num_px * 3)
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
layers_dims -- list containing the input size and each layer size, of length (number of layers + 1).
learning_rate -- learning rate of the gradient descent update rule
num_iterations -- number of iterations of the optimization loop
print_cost -- if True, it prints the cost every 100 steps
Returns:
parameters -- parameters learnt by the model. They can then be used to predict.
"""
np.random.seed(1)
costs = [] # keep track of cost
# Parameters initialization.
### START CODE HERE ###
parameters = initialize_parameters_deep(layers_dims)#参数初始化
### END CODE HERE ###
# Loop (gradient descent)
for i in range(0, num_iterations):
# Forward propagation: [LINEAR -> RELU]*(L-1) -> LINEAR -> SIGMOID.
### START CODE HERE ### (≈ 1 line of code)
AL, caches = L_model_forward(X, parameters)
### END CODE HERE ###
# Compute cost.
### START CODE HERE ### (≈ 1 line of code)
cost = compute_cost(AL, Y)
### END CODE HERE ###
# Backward propagation.
### START CODE HERE ### (≈ 1 line of code)
grads = L_model_backward(AL, Y, caches)
### END CODE HERE ###
# Update parameters.
### START CODE HERE ### (≈ 1 line of code)
parameters = update_parameters(parameters, grads, learning_rate)
### END CODE HERE ###
# Print the cost every 100 training example
if print_cost and i % 100 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
if print_cost and i % 100 == 0:
costs.append(cost)
# plot the cost
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
return parameters
测试代码:
layers_dims = [12288, 20, 7, 5, 1] # 5-layer model
parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 2500, print_cost = True)
运行结果如下:
Cost after iteration 0: 0.771749
Cost after iteration 100: 0.672053
Cost after iteration 200: 0.648263
Cost after iteration 300: 0.611507
Cost after iteration 400: 0.567047
Cost after iteration 500: 0.540138
Cost after iteration 600: 0.527930
Cost after iteration 700: 0.465477
Cost after iteration 800: 0.369126
Cost after iteration 900: 0.391747
Cost after iteration 1000: 0.315187
Cost after iteration 1100: 0.272700
Cost after iteration 1200: 0.237419
Cost after iteration 1300: 0.199601
Cost after iteration 1400: 0.189263
Cost after iteration 1500: 0.161189
Cost after iteration 1600: 0.148214
Cost after iteration 1700: 0.137775
Cost after iteration 1800: 0.129740
Cost after iteration 1900: 0.121225
Cost after iteration 2000: 0.113821
Cost after iteration 2100: 0.107839
Cost after iteration 2200: 0.102855
Cost after iteration 2300: 0.100897
Cost after iteration 2400: 0.092878
对训练集进行预测:
pred_train = predict(train_x, train_y, parameters)
输出的准确率:
Accuracy: 0.985645933014
对测试数据集进行预测:
pred_test = predict(test_x, test_y, parameters)
输出的准确率:
Accuracy: 0.8
至此,我们完成5层神经网络的训练和预测,从结果可以看出测试数据集80%的准确率比双层神经网络的72%要更好。在后续,通过对超参数的优化,我们可以进一步提高准确率。
6- 结果分析
我们先来看下,上述L层模型中分错的结果:
def print_mislabeled_images(classes, X, y, p):
"""
Plots images where predictions and truth were different.
X -- dataset
y -- true labels
p -- predictions
"""
a = p + y
mislabeled_indices = np.asarray(np.where(a == 1))
plt.rcParams['figure.figsize'] = (40.0, 40.0) # set default size of plots
num_images = len(mislabeled_indices[0])
for i in range(num_images):
index = mislabeled_indices[1][i]
plt.subplot(2, num_images, i + 1)
plt.imshow(X[:,index].reshape(64,64,3), interpolation='nearest')
plt.axis('off')
plt.title("Prediction: " + classes[int(p[0,index])].decode("utf-8") + " \n Class: " + classes[y[0,index]].decode("utf-8"))
print_mislabeled_images(classes, test_x, test_y, pred_test)
运行结果:
从中我们可以看出这些图像的一些特性:
- 当猫的身体部分位于非常见位置时
- 当猫背景和猫的毛色相近时
- 猫颜色不常见或者猫本身的品种少见时
- 相机角度的影响
- 图像的亮度
- 比例误差 (猫在图像中的比例过大或者过小)
7- 在自己的数据集上测试
代码如下:
## START CODE HERE ##
my_image = "my_image1.jpg" # change this to the name of your image file
my_label_y = [1] # the true class of your image (1 -> cat, 0 -> non-cat)
## END CODE HERE ##
fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((num_px*num_px*3,1))
my_predicted_image = predict(my_image, my_label_y, parameters)
plt.imshow(image)
print ("y = " + str(np.squeeze(my_predicted_image)) + ", your L-layer model predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") + "\" picture.")
运行结果如下:
Accuracy: 1.0
y = 1.0, your L-layer model predicts a "cat" picture.
8- 参考:
http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython