深度學習筆記-Hyperparameter tuning-2.1.1-initialization初始化

Improving Deep Neural Networks-Hyperparameter tuning, Regularization and Optimization:https://www.coursera.org/learn/deep-neural-network

這段時間會一直更深度學習的內容。
先明確說明代碼不是我寫的,我只是整理,來源於Cousera的代碼,將代碼大幅度縮短,補充說明。

這個章節屬於Hyperparameter tuning, Regularization and OptimizationPractical aspects of Deep Learninginitialization
這個章節不止有隨機初始化,還有正則化和梯度檢測,這是第一個。
完整目錄從這裏跳轉

這一章的代碼分成幾部分

0.模塊準備
1.Neural Network model算法模塊
2.Zero initialization-零初始化
3.Random initialization-隨機初始化
4.He initialization-He初始化

先看一下整體的效果圖

0.效果圖

已經把代碼縮短了,也上傳了。
https://download.csdn.net/download/qq_42731466/10946787
在這裏插入圖片描述

1.代碼

import numpy as np
import matplotlib.pyplot as plt
import h5py
import sklearn
import sklearn.datasets

# 0.模塊準備
sigmoid = lambda x:1/(1+np.exp(-x))
relu = lambda x:np.maximum(0,x)
predict_dec = lambda parameters, X:(forward_propagation(X, parameters)[0]>0.5)

def forward_propagation(X, parameters):

    W1,W2,W3 = parameters["W1"],parameters["W2"],parameters["W3"]
    b1,b2,b3 = parameters["b1"],parameters["b2"],parameters["b3"]
    
    z1 = np.dot(W1, X) + b1
    a1 = relu(z1)
    z2 = np.dot(W2, a1) + b2
    a2 = relu(z2)
    z3 = np.dot(W3, a2) + b3
    a3 = sigmoid(z3)
    cache = (z1, a1, W1, b1, z2, a2, W2, b2, z3, a3, W3, b3)
    return a3, cache

def predict(X, y, parameters):

    m = X.shape[1]
    p = np.zeros((1,m), dtype = np.int)
    a3, caches = forward_propagation(X, parameters)
    
    # 0/1
    for i in range(0, a3.shape[1]):
        if a3[0,i] > 0.5:
            p[0,i] = 1
        else:
            p[0,i] = 0

    print("擬合度: "  + str(np.mean((p[0,:] == y[0,:]))))
    
    return p

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
    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
    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(-1), cmap=plt.cm.Spectral)
    plt.show()
    
    

plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

np.random.seed(1)
train_X, train_Y = sklearn.datasets.make_circles(n_samples=300, noise=.05)
np.random.seed(2)
test_X, test_Y = sklearn.datasets.make_circles(n_samples=100, noise=.05)

# 數據可視化
plt.scatter(train_X[:, 0], train_X[:, 1], c=train_Y, s=40, cmap=plt.cm.Spectral);
train_X = train_X.T
train_Y = train_Y.reshape((1, train_Y.shape[0]))
test_X = test_X.T
test_Y = test_Y.reshape((1, test_Y.shape[0]))


# 0.算法模塊
def model(X, Y, learning_rate = 0.01, num_iterations = 15000, print_cost = True, initialization = "he"):
        
    grads = {}
    costs = []                                          # 跟蹤損失函數值
    m = X.shape[1]                                      # 訓練集
    layers_dims = [X.shape[0], 10, 5, 1]
    

    parameters = {}
    L = len(layers_dims)                                # network的層數
    np.random.seed(3)                                   # 固定隨機的值
    
    for l in range(1, L):
        parameters['W' + str(l)] = np.random.randn(layers_dims[l],layers_dims[l-1])
        parameters['b' + str(l)] = np.zeros((layers_dims[l],1))
            
    if initialization == "zeros":
        for l in range(1, L):
            parameters['W' + str(l)] *= 0
            parameters['b' + str(l)] = np.zeros((layers_dims[l],1))

    elif initialization == "random":
        for l in range(1, L):
            parameters['W' + str(l)] *= 10

    elif initialization == "he":
        L -= 1                                         # 注意這裏有一個細微的變化
        for l in range(1, L+1):
            parameters['W' + str(l)] *= np.sqrt(2./layers_dims[l-1])

            
    for i in range(0, num_iterations):

        # 前向傳播
        W1,W2,W3 = parameters["W1"],parameters["W2"],parameters["W3"]
        b1,b2,b3 = parameters["b1"],parameters["b2"],parameters["b3"]
        z1 = np.dot(W1, X) + b1
        a1 = relu(z1)
        z2 = np.dot(W2, a1) + b2
        a2 = relu(z2)
        z3 = np.dot(W3, a2) + b3
        a3 = sigmoid(z3)
        cache = (z1, a1, W1, b1, z2, a2, W2, b2, z3, a3, W3, b3)

        
        # 損失計算
        m = Y.shape[1]                                   # Y標籤
        logprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y)
        cost = 1./m * np.nansum(logprobs)


        # 反向傳播
        dz3 = 1./m * (a3 - Y)
        dW3 = np.dot(dz3, a2.T)
        db3 = np.sum(dz3, axis=1, keepdims = True)

        da2 = np.dot(W3.T, dz3)
        dz2 = np.multiply(da2, np.int64(a2 > 0))
        dW2 = np.dot(dz2, a1.T)
        db2 = np.sum(dz2, axis=1, keepdims = True)

        da1 = np.dot(W2.T, dz2)
        dz1 = np.multiply(da1, np.int64(a1 > 0))
        dW1 = np.dot(dz1, X.T)
        db1 = np.sum(dz1, axis=1, keepdims = True)

        gradients = {"dz3": dz3, "dW3": dW3, "db3": db3,
                     "da2": da2, "dz2": dz2, "dW2": dW2, "db2": db2,
                     "da1": da1, "dz1": dz1, "dW1": dW1, "db1": db1}        
        
        # 參數更新
        L = len(parameters) // 2                            # 神經網絡層數
        for k in range(L):
            parameters["W" + str(k+1)] = parameters["W" + str(k+1)] - learning_rate * gradients["dW" + str(k+1)]
            parameters["b" + str(k+1)] = parameters["b" + str(k+1)] - learning_rate * gradients["db" + str(k+1)]

        # 1000次迭代
        if print_cost and i % 1000 == 0:
            print("迭代{}次的損失: {}".format(i, cost))
            costs.append(cost)

    # 損失繪製
    plt.plot(costs)
    plt.ylabel('cost')
    plt.xlabel('iterations (per 100)')
    plt.title("Learning rate =" + str(learning_rate))
    plt.show()
    
    return parameters



# 1.零初始化進行梯度下降
parameters = model(train_X, train_Y, initialization = "zeros")
print ("訓練集擬合度:")
predictions_train = predict(train_X, train_Y, parameters)
print ("測試集擬合度:")
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])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)



# 2.隨機初始化
parameters = model(train_X, train_Y, initialization = "random")
print ("訓練集擬合度:")
predictions_train = predict(train_X, train_Y, parameters)
print ("測試集擬合度:")
predictions_test = predict(test_X, test_Y, parameters)

plt.title("Model with large random initialization")
axes = plt.gca()
axes.set_xlim([-1.5,1.5])
axes.set_ylim([-1.5,1.5])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)



# 3.He初始化
parameters = model(train_X, train_Y, initialization = "he")
print ("訓練集擬合度:")
predictions_train = predict(train_X, train_Y, parameters)
print ("測試集擬合度:")
predictions_test = predict(test_X, test_Y, parameters)

plt.title("Model with He initialization")
axes = plt.gca()
axes.set_xlim([-1.5,1.5])
axes.set_ylim([-1.5,1.5])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)

2.補充

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章