参考链接:https://blog.csdn.net/u013733326/article/details/79847918
与原博文不同,我直接改动了第一课第四周的作业代码,只测试了L2正则化和随机初始化的效果。L2正则化可以明显的缓解过度拟合的情况
代码:
# coding=utf-8 # This is a sample Python script. # Press ⌃R to execute it or replace it with your code. # Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings. import numpy as np import matplotlib.pyplot as plt import sklearn import sklearn.datasets import init_utils #第一部分,初始化 import reg_utils #第二部分,正则化 import gc_utils #第三部分,梯度校验 from dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward np.random.seed(3) lambd = 0.75 #%matplotlib inline #如果你使用的是Jupyter Notebook,请取消注释。 def init(layers_dims): parameters = {} L = len(layers_dims) for l in range(1, L): # print("l:", l) parameters["W" + str(l)] = np.random.randn(layers_dims[l], layers_dims[l - 1]) / np.sqrt(layers_dims[l - 1]) * 2 parameters["b" + str(l)] = np.zeros((layers_dims[l], 1)) assert parameters["W" + str(l)].shape == (layers_dims[l], layers_dims[l - 1]) assert parameters["b" + str(l)].shape == (layers_dims[l], 1) return parameters 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 liner_activation_forward(A_pre, W, b, activation): if activation == "sigmoid": Z, linear_cache = linear_forward(A_pre, W, b) A, activation_cache = sigmoid(Z) elif activation == "relu": Z, linear_cache = linear_forward(A_pre, W, b) A, activation_cache = relu(Z) assert A.shape == (W.shape[0], A_pre.shape[1]) cache = (linear_cache, activation_cache) return A, cache def l_model_forward(X, parameters): caches = [] A = X L = len(parameters) // 2 for l in range(1, L): A_prev = A A, cache = liner_activation_forward(A_prev, parameters["W" + str(l)], parameters["b" + str(l)], activation="relu") caches.append(cache) AL, cache = liner_activation_forward(A, parameters["W" + str(L)], parameters["b" + str(L)], activation="sigmoid") caches.append(cache) assert AL.shape == (1, X.shape[1]) return AL, caches def cal_cost(AL, Y, parameters): m = Y.shape[1] L = len(parameters) // 2 cost = -np.sum(np.multiply(Y, np.log(AL)) + np.multiply(1 - Y, np.log(1 - AL))) / m cost = np.squeeze(cost) tmp = 0 for i in range(L): tmp = tmp + np.sum(np.square(parameters["W" + str(i + 1)])) cost = cost + tmp / (2 * m) assert cost.shape == () return cost # Press the green button in the gutter to run the script. def liner_backward(dZ, cache): A_prev, W, b = cache m = A_prev.shape[1] dW = np.dot(dZ, A_prev.T) / m + ((lambd * W) / m) dB = np.sum(dZ, axis=1, keepdims=True) / m 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 liner_activation_backward(dA, cache, activation): liner_cache, activation_cache = cache if activation == "relu": dZ = relu_backward(dA, activation_cache) dA_prev, dW, db = liner_backward(dZ, liner_cache) elif activation == "sigmoid": dZ = sigmoid_backward(dA, activation_cache) dA_prev, dW, db = liner_backward(dZ, liner_cache) return dA_prev, dW, db def L_model_backward(AL, Y, caches): grads = {} L = len(caches) m = AL.shape[1] Y = Y.reshape(AL.shape) dAL = -(np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) current_cache = caches[L - 1] grads["dA" + str(L)], grads["dW" + str(L)], grads["db" + str(L)] = liner_activation_backward(dAL, current_cache, "sigmoid") for l in reversed((range(L - 1))): current_cache = caches[l] dA_prev_tmp, dW_tmp, db_tmp = liner_activation_backward(grads["dA" + str(l + 2)], current_cache, "relu") grads["dA" + str(l + 1)] = dA_prev_tmp grads["dW" + str(l + 1)] = dW_tmp grads["db" + str(l + 1)] = db_tmp return grads def update(parameters, grads, learning_rate, m): L = len(parameters) // 2 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 predict(X, parameters): m = X.shape[1] n = len(parameters) // 2 # 神经网络的层数 p = np.zeros((1, m)) # 根据参数前向传播 probas, caches = l_model_forward(X, parameters) p = (probas > 0.5) # 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 predicts(X, y, parameters): m = X.shape[1] n = len(parameters) // 2 # 神经网络的层数 p = np.zeros((1, m)) # 根据参数前向传播 probas, caches = l_model_forward(X, parameters) p = (probas > 0.5) print("准确度为: " + str(float(np.sum((p == y)) / m))) return p def solve(X, Y, layer_dims, learning_rate, num_iterations): costs = [] parameters = init(layer_dims) for i in range(0, num_iterations): AL, caches = l_model_forward(X, parameters) cost = cal_cost(AL, Y, parameters) grads = L_model_backward(AL, Y, caches) parameters = update(parameters, grads, learning_rate, len(parameters) // 2) if i % 100 == 0: costs.append(cost) # 是否打印成本值 print("第", i, "次迭代,成本值为:", np.squeeze(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 if __name__ == '__main__': train_X, train_Y, test_X, test_Y = reg_utils.load_2D_dataset(is_plot=True) # plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots # plt.rcParams['image.interpolation'] = 'nearest' # plt.rcParams['image.cmap'] = 'gray' # plt.show() # layers_dims = [12288, 20, 7, 5, 1] # 5-layer model layers_dims = [train_X.shape[0], 30, 20, 10, 5, 1] parameters = solve(train_X, train_Y, layers_dims, 0.01, num_iterations=25000) # predictions_train = predict(train_X, train_Y, parameters) # 训练集 # predictions_test = predict(test_X, test_Y, parameters) # 测试集 plt.title("Model with Zeros initialization") axes = plt.gca() axes.set_xlim([-1.5, 1.5]) axes.set_ylim([-1.5, 1.5]) # parameters = model(train_X, train_Y, initialization="zeros", is_polt=True) init_utils.plot_decision_boundary(lambda x: predict(x.T, parameters), train_X, train_Y) predicts(train_X, train_Y, parameters) predicts(test_X, test_Y, parameters) # See PyCharm help at https://www.jetbrains.com/help/pycharm/