主要步骤
-
初始化两层和深层的神经网络参数。
-
实现正向传播模块(紫色图)。
- 完成模型正向传播步骤的linear部分。
- 提供使用的activation函数(relu / Sigmoid)。
- 将前两个步骤合并为新的[linear->activation]前向函数。
- 堆叠[linear->relu]正向函数L-1次(第1到L-1层),并在末尾添加[linear-> sigmoid](最后的层),合成了一个新的L_model_forward函数。
3.计算损失。
4.实现反向传播模块(红色图)。
- 完成模型反向传播步骤的linear部分。
- 提供的activation函数的梯度(relu_backward / sigmoid_backward)
- 将前两个步骤组合成新的[linear-> sigmoid]反向函数。
- 将[linear->relu]向后堆叠L-1次,并在新的L_model_backward函数中后向添加[inear-> sigmoid] 最后更新参数。
运行结果
打印cost,画出cost下降曲线。
import numpy as np
import h5py
import matplotlib.pyplot as plt
import pylab
def sigmoid(Z):
A = 1 / (1 + np.exp(-Z))
cache = Z
return A, cache
def relu(Z):
A = np.maximum(0, Z)
assert (A.shape == Z.shape)
cache = Z
return A, cache
def relu_backward(dA, cache):
Z = cache
dZ = np.array(dA, copy=True) # just converting dz to a correct object.
# When z <= 0, you should set dz to 0 as well.
dZ[Z <= 0] = 0
assert (dZ.shape == Z.shape)
return dZ
def sigmoid_backward(dA, cache):
Z = cache
s = 1 / (1 + np.exp(-Z))
dZ = dA * s * (1 - s)
assert (dZ.shape == Z.shape)
return dZ
np.random.seed(1)
# 初始化参数,2层
def initialize_parameters(n_x, n_h, n_y):
np.random.seed(1)
W1=np.random.randn(n_h,n_x)*0.01
b1=np.zeros((n_h,1))
W2=np.random.randn(n_y,n_h)*0.01
b2=np.zeros((n_y,1))
# 使用断言确保我的数据格式是正确的
assert (W1.shape == (n_h, n_x))
assert (b1.shape == (n_h, 1))
assert (W2.shape == (n_y, n_h))
assert (b2.shape == (n_y, 1))
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
# 初始化参数,深层
def initialize_parameters_deep(layer_dims):
np.random.seed(3)
parameters = {}
L = len(layer_dims) # 网络层数
# 这里须明确矩阵维度
for l in range(1, L):
parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l - 1]) / np.sqrt(layer_dims[l - 1])
parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))
# 确保我要的数据的格式是正确的
assert (parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l - 1]))
assert (parameters['b' + str(l)].shape == (layer_dims[l], 1))
return parameters
#前向传播,分三步走
#第一步,实现前向传播,只有linear
def linear_forward(A, W, b):
Z = np.dot(W, A) + b
assert (Z.shape == (W.shape[0], A.shape[1]))
cache = (A, W, b)
return Z, cache
# 第二步,前向传播+激活函数
def linear_activation_forward(A_prev, W, b, activation):
if activation == "sigmoid":
Z, linear_cache = linear_forward(A_prev, W, b)
A, activation_cache = sigmoid(Z)
elif activation == "relu":
Z, linear_cache = linear_forward(A_prev, W, b)
A, activation_cache = relu(Z)
assert (A.shape == (W.shape[0], A_prev.shape[1]))
cache = (linear_cache, activation_cache)
# 最后cache里面包含A_prev W b Z
return A, cache
# 第三步,实现整个网络的前向传播
def L_model_forward(X, parameters):
caches = []
A = X
L = len(parameters) // 2 # 神经网络的层数
# L-1次linear-relu
for l in range(1, L):
A_prev = A
A, cache = linear_activation_forward(A_prev, parameters['W' + str(l)], parameters['b' + str(l)],
activation="relu")
caches.append(cache) # A_prev W b Z
# L层的linear+sigmoid
AL, cache = linear_activation_forward(A, parameters['W' + str(L)], parameters['b' + str(L)], activation="sigmoid")
caches.append(cache)
assert (AL.shape == (1, X.shape[1]))
# 最后caches里面包含了每一层的A_prev W b Z
return AL, caches
# 计算损失
def compute_cost(AL, Y):
# 获得样本数量
m = Y.shape[1]
cost = -1 / m * np.sum(Y * np.log(AL) + (1 - Y) * np.log(1 - AL), axis=1, keepdims=True)
cost = np.squeeze(cost)
return cost
# 向后传播,分三步走
# 线性部分向后传播
def linear_backward(dZ, cache):
#输入dZ,输出dW,db,dA_prev
# z=np.dot(W,A)+b
A_prev, W, b = cache
# 样本数量
m = A_prev.shape[1]
dW = 1 / m * np.dot(dZ, A_prev.T)
db = 1 / m * np.sum(dZ, axis=1, keepdims=True)
dA_prev = np.dot(W.T, dZ)
assert (dA_prev.shape == A_prev.shape)
assert (dW.shape == W.shape)
assert (db.shape == b.shape)
return dA_prev, dW, db
# 线性部分+激活函数的向后传播
def linear_activation_backward(dA, cache, activation):
linear_cache, activation_cache = cache
# A_prev W b Z
if activation == "relu":
dZ = relu_backward(dA, activation_cache)
dA_prev, dW, db = linear_backward(dZ, linear_cache)
elif activation == "sigmoid":
dZ = sigmoid_backward(dA, activation_cache)
dA_prev, dW, db = linear_backward(dZ, linear_cache)
return dA_prev, dW, db
# 整个网络向后传播
def L_model_backward(AL, Y, caches):
grads = {}
# 层数
L = len(caches)
# 样本数量
m = AL.shape[1]
# Y大小是 (1,m)
Y = Y.reshape(AL.shape)
# 初始化反向传播
dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))
# L层反向传播
current_cache = caches[L - 1]
grads["dA" + str(L)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache,
activation="sigmoid")
# L-1层反向传播
for l in reversed(range(L - 1)):
current_cache = caches[l]
dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l + 2)], current_cache,
activation="relu")
grads["dA" + str(l + 1)] = dA_prev_temp
grads["dW" + str(l + 1)] = dW_temp
grads["db" + str(l + 1)] = db_temp
return grads
def update_parameters(parameters, grads, learning_rate):
# 神经网络的层数
L = len(parameters)// 2
# 更新每个参数,使用 for 循环
for l in range(L):
parameters["W" + str(l + 1)] = parameters["W" + str(l + 1)] - learning_rate * grads["dW" + str(l + 1)]
parameters["b" + str(l + 1)] = parameters["b" + str(l + 1)] - learning_rate * grads["db" + str(l + 1)]
return parameters
# 搭建两层神经网路
def two_layer_model(X, Y, layers_dims, learning_rate=0.0075, num_iterations=3000, print_cost=False, isPlot=True):
np.random.seed(1)
grads = {}
costs = []
(n_x, n_h, n_y) = layers_dims
# 初始化参数
parameters = initialize_parameters(n_x, n_h, n_y)
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
# 开始进行迭代
for i in range(0, num_iterations):
# 前向传播
A1, cache1 = linear_activation_forward(X, W1, b1, "relu")
A2, cache2 = linear_activation_forward(A1, W2, b2, "sigmoid")
# 计算成本
cost = compute_cost(A2, Y)
# 后向传播
## 初始化后向传播
dA2 = - (np.divide(Y, A2) - np.divide(1 - Y, 1 - A2))
## 向后传播,输入:“dA2,cache2,cache1”。 输出:“dA1,dW2,db2;还有dA0(未使用),dW1,db1”。
dA1, dW2, db2 = linear_activation_backward(dA2, cache2, "sigmoid")
dA0, dW1, db1 = linear_activation_backward(dA1, cache1, "relu")
## 向后传播完成后的数据保存到grads
grads["dW1"] = dW1
grads["db1"] = db1
grads["dW2"] = dW2
grads["db2"] = db2
# 更新参数
parameters = update_parameters(parameters, grads, learning_rate)
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
# 打印成本值,如果print_cost=False则忽略
if i % 100 == 0:
# 记录成本
costs.append(cost)
# 是否打印成本值
if print_cost:
print("第", i, "次迭代,成本值为:", np.squeeze(cost))
# 迭代完成,根据条件绘制图
if isPlot:
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
# 返回 parameters
return parameters
# 搭建L层深度神经网络
def L_layer_model(X, Y, layers_dims, learning_rate=0.0075, num_iterations=3000, print_cost=False, isPlot=True):
np.random.seed(1)
costs = []
parameters = initialize_parameters_deep(layers_dims)
for i in range(0, num_iterations):
AL, caches = L_model_forward(X, parameters)
cost = compute_cost(AL, Y)
grads = L_model_backward(AL, Y, caches)
parameters = update_parameters(parameters, grads, learning_rate)
# 打印成本值,如果 print_cost=False 则忽略
if i % 100 == 0:
# 记录成本
costs.append(cost)
# 是否打印成本值
if print_cost:
print("第", i, "次迭代,成本值为:", np.squeeze(cost))
# 迭代完成,根据条件绘制图
if isPlot:
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
return parameters
# 预测
def predict(X, y, parameters):
m = X.shape[1]
n = len(parameters) // 2 # 神经网络的层数
p = np.zeros((1, m))
# 根据参数前向传播
probas, caches = L_model_forward(X, parameters)
for i in range(0, probas.shape[1]):
if probas[0, i] > 0.5:
p[0, i] = 1
else:
p[0, i] = 0
print("准确度为: " + str(float(np.sum((p == y)) / m)))
return p
# 加载数据集
def load_dataset():
# 本地路径
train_dataset = h5py.File('C:/Users/Dell/Desktop/datasets/train_catvnoncat.h5', "r")
train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # 209张 64*64*3的图像
train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # 0/1
test_dataset = h5py.File('C:/Users/Dell/Desktop/datasets/test_catvnoncat.h5', "r")
test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # 50张 64*64*3的图像
test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # 0/1
classes = np.array(test_dataset["list_classes"][:]) # non-cat / cat
train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))
return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes
train_set_x_orig , train_set_y , test_set_x_orig , test_set_y , classes=load_dataset()
train_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
test_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
train_x = train_x_flatten / 255
train_y = train_set_y
test_x = test_x_flatten / 255
test_y = test_set_y
'''
# 正式训练2层神经网络并预测
n_x = 12288
n_h = 7
n_y = 1
layers_dims = (n_x,n_h,n_y)
parameters = two_layer_model(train_x, train_set_y, layers_dims = (n_x, n_h, n_y), num_iterations = 2500, print_cost=True,isPlot=True)
predictions_train = predict(train_x, train_y, parameters) # 训练集
predictions_test = predict(test_x, test_y, parameters) # 测试集
'''
# 正式训练L层深度神经网络并预测
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,isPlot=True)
pred_train = predict(train_x, train_y, parameters) #训练集
pred_test = predict(test_x, test_y, parameters) #测试集
# 打印预测错误的图像,分析原因
def print_mislabeled_images(classes, X, y, p):
a = p + y # (1,m)
# 返回a==1的元素索引
mislabeled_indices = np.asarray(np.where(a == 1))
# print(mislabeled_indices)
# [[ 0 0 0 0 0 0 0 0 0 0 0]
# [ 5 6 13 19 28 29 34 44 45 46 48]]
# 第一个一维数组返回的是a==1的行索引
# 第二个一维数组返回的是a==1的列索引
plt.rcParams['figure.figsize'] = (40.0, 40.0) # 设置 plot 的默认大小
# 预测错图片的总数
num_images = len(mislabeled_indices[0]) # 11
# 显示预测错误的图片
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"))
pylab.show()
print_mislabeled_images(classes, test_x, test_y, pred_test)