主要内容:
与L1W2内容基本一致,只不过网络更加复杂,包含了一层隐含层。主要案例是通过单隐层的神经网络分类二维数据。直接上代码,千言万语皆在注释中。
一.引入包
import numpy as np
import matplotlib.pyplot as plt
import sklearn.linear_model
import pylab
# from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset
# 把planar_utils里面的copy过来
def load_planar_dataset():
np.random.seed(1)
m = 400 # number of examples
N = int(m / 2) # number of points per class
D = 2 # dimensionality
X = np.zeros((m, D)) # data matrix where each row is a single example
Y = np.zeros((m, 1), dtype='uint8') # labels vector (0 for red, 1 for blue)
a = 4 # maximum ray of the flower
for j in range(2):
ix = range(N * j, N * (j + 1))
t = np.linspace(j * 3.12, (j + 1) * 3.12, N) + np.random.randn(N) * 0.2 # theta
r = a * np.sin(4 * t) + np.random.randn(N) * 0.2 # radius
X[ix] = np.c_[r * np.sin(t), r * np.cos(t)]
Y[ix] = j
X = X.T
Y = Y.T
return X, Y
def plot_decision_boundary(model, X, Y):
# Set min and max values and give it some padding
x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1
y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1
h = 0.01
# Generate a grid of points with distance h between them
# xx,yy分别是x轴、y轴上的坐标网络
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# Predict the function value for the whole grid
# 将xx和yy扁平化为一维数组然后再将其按列拼接,每一行成为一个点的横纵坐标,预测输出
Z = model(np.c_[xx.ravel(), yy.ravel()])
# 调整成与原始网格点相同的形状,便于通过索引输出函数值
Z = Z.reshape(xx.shape)
# Plot the contour and training examples
# 等高线填充图
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
plt.ylabel('x2')
plt.xlabel('x1')
plt.scatter(X[0, :], X[1, :], c=Y.reshape(X[0, :].shape), cmap=plt.cm.Spectral)
def sigmoid(x):
s = 1 / (1 + np.exp(-x))
return s
二.具体实现
实现的神经网络结构如下图:
# 加载数据集
X,Y=load_planar_dataset()
'''
# 查看数据集
# 绘制散点图
plt.scatter(X[0, :], X[1, :], c=Y.reshape(X[0,:].shape), s=40, cmap=plt.cm.Spectral)
pylab.show()
shape_X = X.shape # (2,400)
shape_Y = Y.shape # (1,400)
m = shape_X[1] # 训练集里面的数量 # 400
print ('X的维度为: ' + str(shape_X))
print ('Y的维度为: ' + str(shape_Y))
print ("数据集里面的数据有:" + str(m) + " 个")
'''
# 训练逻辑回归分类器
clf = sklearn.linear_model.LogisticRegressionCV();
clf.fit(X.T, Y.T);
# 绘制决策边界
plot_decision_boundary(lambda x: clf.predict(x), X, Y)
pylab.show()
# 图标题
plt.title("Logistic Regression")
# 打印准确性
LR_predictions = clf.predict(X.T)
print ('逻辑回归的准确性:%d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +
'% ' + "(正确标记的数据点所占的百分比)") # 预测正确为1+预测正确为0
# 搭建神经网络模型
# 先实现各部分,然后整合成nn.model
def layer_sizes(X, Y):
# 输入层大小
n_x = X.shape[0] # 2
# 隐藏层大小
n_h = 4 # 4
# 输出层大小
n_y = Y.shape[0] # 1
return (n_x, n_h, n_y)
def initialize_parameters(n_x, n_h, n_y):
# 设置一个种子,这样输出能够匹配,尽管初始化是随机的。
np.random.seed(2)
# 初始化参数这一部分吴恩达老师已经详细讲过
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 forward_propagation(X, parameters):
# 从字典 “parameters” 中检索每个参数
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
# 实现前向传播计算
Z1 = np.dot(W1, X) + b1
A1 = np.tanh(Z1)
Z2 = np.dot(W2, A1) + b2
A2 = sigmoid(Z2)
# 使用断言确保我的数据格式是正确的
assert (A2.shape == (1, X.shape[1])) # (1,m)
cache = {"Z1": Z1,
"A1": A1,
"Z2": Z2,
"A2": A2}
return A2, cache
def compute_cost(A2, Y, parameters):
# 样本数量
m = Y.shape[1]
# 计算交叉熵代价
logprobs = Y * np.log(A2) + (1 - Y) * np.log(1 - A2)
cost = -1 / m * np.sum(logprobs)
# 确保损失是我们期望的维度
# 例如,turns [[17]] into 17
cost = np.squeeze(cost)
#断言语句,确保cost是cost是浮点类型
assert (isinstance(cost, float))
return cost
def backward_propagation(parameters, cache, X, Y):
# 样本数量
m = X.shape[1]
# 首先,从字典“parameters”中检索W1和W2。
W1 = parameters["W1"]
W2 = parameters["W2"]
# 还可以从字典“cache”中检索A1和A2。
A1 = cache["A1"]
A2 = cache["A2"]
# 反向传播:计算 dW1、db1、dW2、db2。
#重点是这里的推导理解
dZ2 = A2 - Y
dW2 = 1 / m * np.dot(dZ2, A1.T)
db2 = 1 / m * np.sum(dZ2, axis=1, keepdims=True)
dZ1 = np.dot(W2.T, dZ2) * (1 - np.power(A1, 2))
dW1 = 1 / m * np.dot(dZ1, X.T)
db1 = 1 / m * np.sum(dZ1, axis=1, keepdims=True)
# 将梯度用字典保存下来
grads = {"dW1": dW1,
"db1": db1,
"dW2": dW2,
"db2": db2}
return grads
def update_parameters(parameters, grads, learning_rate=1.2):
# 从字典“parameters”中检索每个参数
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
# 从字典“梯度”中检索每个梯度
dW1 = grads["dW1"]
db1 = grads["db1"]
dW2 = grads["dW2"]
db2 = grads["db2"]
# 每个参数的更新规则
W1 = W1 - learning_rate * dW1
b1 = b1 - learning_rate * db1
W2 = W2 - learning_rate * dW2
b2 = b2 - learning_rate * db2
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
# 整合成nn_model
def nn_model(X, Y, n_h, num_iterations=10000, print_cost=False):
# 取出n_x,n_y
np.random.seed(3)
n_x = layer_sizes(X, Y)[0]
n_y = layer_sizes(X, Y)[2]
# 初始化参数,然后取出 W1, b1, W2, b2。
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):
# 前项传播
A2, cache = forward_propagation(X, parameters)
# 计算成本
cost = compute_cost(A2, Y, parameters)
# 反向传播
grads = backward_propagation(parameters, cache, X, Y)
# 更新参数
parameters = update_parameters(parameters, grads)
# 每1000次迭代打印成本
if print_cost and i % 1000 == 0:
print("Cost after iteration %i: %f" % (i, cost))
return parameters
def predict(parameters, X):
# 使用前向传播计算概率,并使用 0.5 作为阈值将其分类为 0/1。
A2, cache = forward_propagation(X, parameters)
predictions = np.round(A2)
return predictions
# 训练模型
# 用 n_h 维隐藏层构建一个模型
parameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True)
# 绘制决策边界
plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
plt.title("Decision Boundary for hidden layer size " + str(4))
pylab.show()
# 打印准确率
predictions = predict(parameters, X)
print ('准确率: %d' % float((np.dot(Y, predictions.T) + np.dot(1 - Y, 1 - predictions.T)) / float(Y.size) * 100) + '%')
# 调节隐藏层节点数量
plt.figure(figsize=(16, 32))
hidden_layer_sizes = [1, 2, 3, 4, 5, 10, 20] # 隐藏层数量
for i, n_h in enumerate(hidden_layer_sizes):
# 显示图的位置
plt.subplot(5, 2, i+1)
plt.title('Hidden Layer of size %d' % n_h)
parameters = nn_model(X, Y, n_h, num_iterations = 5000)
plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
pylab.show()
predictions = predict(parameters, X)
accuracy = float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100)
print ("隐藏层的节点数量: {} ,准确率: {} %".format(n_h, accuracy))