【Deep Learning】L1W4作业
本文为吴恩达 Deep Learning 作业,深层神经网络,识别猫
获得数据
主要算法
模型结构:
2 层神经网络:
LINEAR -> RELU -> LINEAR -> SIGMOID
。 L 层神经网络:
[LINEAR -> RELU] × (L-1) -> LINEAR -> SIGMOID
。
初始化
def initialize_parameters_deep(layer_dims):
np.random.seed(1)
parameters = {}
L = len(layer_dims) # number of layers in the network
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
- 初始化
W
时,不需要*0.01
,因为最开始使用ReLU
。
向前传播
向前传播:
\[Z^{[l]} = W^{[l]}A^{[l-1]}+b^{[l]}
\]
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
正向激活:
\[A^{[l]} = g(Z^{[l]}) = g(W^{[l]}A^{[l-1]}+b^{[l]})
\]
def linear_activation_forward(A_prev, W, b, activation):
A, linear_cache, activation_cache = 0, 0, 0
if activation == "sigmoid":
# Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
Z, linear_cache = linear_forward(A_prev, W, b)
A, activation_cache = sigmoid(Z)
elif activation == "relu":
# Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
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)
return A, cache
L 层模型:
def L_model_forward(X, parameters):
caches = []
A = X
L = len(parameters) // 2 # number of layers in the neural network
# Implement [LINEAR -> RELU]*(L-1). Add "cache" to the "caches" list.
for l in range(1, L):
A_prev = A
A, cache = linear_activation_forward(
A_prev, parameters['W' + str(l)], parameters['b' + str(l)], "relu") # 重点
caches.append(cache)
# Implement LINEAR -> SIGMOID. Add "cache" to the "caches" list.
AL, cache = linear_activation_forward(
A, parameters['W' + str(L)], parameters['b' + str(L)], "sigmoid") # 重点
caches.append(cache)
assert (AL.shape == (1, X.shape[1]))
return AL, caches
计算代价
-
AL
的维度是 \((1, m)\),Y
的维度是 \((1, m)\)。 -
计算代价的公式是:
\[\frac{1}{m} \sum_{i = 1}^m(y^{(i)}\log a^{[l](i)} + (1-y^{(i)}) \log (1-a^{[l](i)})) \] -
cost = (1. / m) * (-np.dot(Y, np.log(AL).T) - np.dot(1 - Y, np.log(1 - AL).T))
与cost = (-1. / m) * np.sum(Y * np.log(AL) + (1 - Y) * np.log(1 - AL), axis=1, keepdims=True)
等价。
def compute_cost(AL, Y):
m = Y.shape[1]
# Compute loss from aL and y.
cost = (1. / m) * (-np.dot(Y, np.log(AL).T) - np.dot(1 - Y, np.log(1 - AL).T)) # 重点
# To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).
cost = np.squeeze(cost) # 重点
assert (cost.shape == ())
return cost
反向传播
反向传播:
\[dW^{[l]} = \frac{1}{m}dZ^{[l]} \cdot A^{[l-1]\mathrm{T}} \\
db^{[l]} = \frac{1}{m} \sum_{i=1}^m dZ^{[l](i)} \\
dA^{[l-1]} = W^{[l]\mathrm{T}} \cdot dZ^{[l]}
\]
def linear_backward(dZ, cache):
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
反向激活:
\[dZ^{[l]} = dA^{[l]} * g^{[l]'}(Z^{[l]})
\]
def linear_activation_backward(dA, cache, activation):
dA_prev, dW, db = 0, 0, 0
linear_cache, activation_cache = cache
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
L 层模型:
\[dA^{[L]} = -(\frac{Y}{A^{}[L]}-\frac{1-Y}{1-A^{[L]}})
\]
def L_model_backward(AL, Y, caches):
grads = {}
L = len(caches) # the number of layers
m = AL.shape[1]
Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL
# Initializing the backpropagation
dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) # 重点
# Lth layer (SIGMOID -> LINEAR) gradients.
# Inputs: "AL, Y, caches". Outputs: "grads["dAL"], grads["dWL"], grads["dbL"]
current_cache = caches[L - 1]
grads["dA" + str(L)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, "sigmoid") # 重点
for l in reversed(range(L - 1)):
# lth layer: (RELU -> LINEAR) gradients.
current_cache = caches[l]
dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l + 2)], current_cache, "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 # number of layers in the neural network
# Update rule for each parameter. Use a for loop.
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
整合
2 层神经网络
def two_layer_model(X, Y, layers_dims, learning_rate=0.0075, num_iterations=2500, print_cost=False):
np.random.seed(1)
grads = {}
costs = [] # to keep track of the cost
(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, activation="relu")
A2, cache2 = linear_activation_forward(A1, W2, b2, activation="sigmoid")
cost = compute_cost(A2, Y)
dA2 = - (np.divide(Y, A2) - np.divide(1 - Y, 1 - A2))
dA1, dW2, db2 = linear_activation_backward(dA2, cache2, activation="sigmoid")
dA0, dW1, db1 = linear_activation_backward(dA1, cache1, activation="relu")
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"]
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)
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
return parameters
L 层神经网络
def L_layer_model(X, Y, layers_dims, learning_rate=0.0075, num_iterations=2500, print_cost=False):
np.random.seed(1)
costs = [] # keep track of cost
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) # 重点
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)
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]
probas, caches = L_model_forward(X, parameters)
p = np.round(probas)
print("Accuracy: " + str(np.sum((p == y) / m)))
return p
main 函数
def main():
train_x_orig, train_y, test_x_orig, test_y, classes = load_data()
# The "-1" makes reshape flatten the remaining dimensions
train_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T
test_x_flatten = test_x_orig.reshape(test_x_orig.shape[0], -1).T
train_x = train_x_flatten / 255.
test_x = test_x_flatten / 255.
# parameters = two_layer_model(train_x, train_y, (12288, 7, 1), 0.0075, 2500, True)
parameters = L_layer_model(train_x, train_y, (12288, 20, 7, 5, 1), 0.0075, 2500, True)
pred_train = predict(train_x, train_y, parameters)
pred_test = predict(test_x, test_y, parameters)
print_mislabeled_images(classes, test_x, test_y, pred_test)
绘图
def print_mislabeled_images(classes, X, Y, p):
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"))
plt.show()
关于 Python
np
np.where
:
np.where(condition, x, y)
- 当只有一个参数时,那个参数表示条件,当条件成立时,返回的是每个符合条件元素的坐标 (元组形式)。
- 当有三个参数时,第一个参数表示条件,当条件成立时,返回
x
;当条件不成立时,返回y
。
np.asarray
:
np.asarray(a, dtype=None, order=None)
- 将结构数据转化为
ndarray
。
plt
put.imshow
:
interpolation='nearest'
设置图片的模糊度,不是什么重要的事情。