본문 바로가기

딥러닝/DeepLearning.ai

4주차. Programming: Building deep neural network

1. Packages

import numpy as np
import h5py
import matplotlib.pyplot as plt
from testCases_v4a import *
from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward

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

%load_ext autoreload
%autoreload 2

np.random.seed(1)

2. Outline of Assignment

L개의 layer을 가진 neural network를 설계하는 과정

  • parameters(W1,b1, ... ,WL,bL)을 initialize 한다.
  • Forward propagation
    • Z[l]=W[l]*A[l-1]+b[l] : LINEAR PART
    • A[l]=relu(Z[l]) : ACTIVATION 
    • LINEAR -> ACTIVATION을 forward function으로 묶는다.
    • [LINEAR -> RELU forward]를 0층->1층, ... , L-2층->L-1층으로 L-1번 반복하고, [LINEAR -> SIGMOID forward]를 L-1층 -> L층으로 1번 수행한다. => L-model forward function
  • Loss를 계산한다.
  • Backward propagation
    • LINEAR PART
    • ACTIVATE PART
    • LINEAR -> ACTIVATION을 backward function으로 묶는다
    • [LINEAR -> RELU backward]를 L층 -> L-1층에서 수행하고, [LINEAR -> SIGMOID backward]를 L-1층 -> L-2층, ... , 1층 -> 0층으로 L-1번 반복한다
  • parameter를 update 한다. 

3. Initialization

1) 2 layer neural network

def initialize_parameters(n_x, n_h, n_y):
    
    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    

L=2일 때 W1,b1,W2,b2를 initialize 했다.

 

2) L-layer neural network

L개의 layer을 가진 deep neural network는 Wl,bl을 for 문을 통해 채워줄 것이다.

 

def initialize_parameters_deep(layer_dims):
   
    np.random.seed(3)
    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])* 0.01
        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[l] : (n[l], n[l-1])

b[l] : (n[l], 1)

W[1],b[1] ~ W[L-1], b[L-1]까지 parameter를 initialize 해줬다. 

layer_dims에는 [n[0], n[1], n[2], ... n[L])으로 layer의 unit 수를 넣어준다.

 

4. Forward Propagation Module

4.1 Linear forward

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

기본적으로 Z=np.dot(W,A)+b를 계산해 주는 코드이다.

 

4.2 Linear - Activation Forward

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)

    return A, cache

 

Z[l] = W[l] * A[l-1] + b[l], A[l] = activation_function(Z[l])을 계산하는 코드이다.

forward propagation에서 0층->1층, ... , L-2층->L-1층은 activation function으로 relu를 이용하지만 L-1층->L층은 sigmoid 함수를 이용한다. input에 A[l-1],W[l],b[l]과 activation="relu" 또는 "sigmoid"를 설정해 주고 activation에 따라 A를 다르게 처리해준다. A[l]과 cache를 돌려주는데, cache는 ((A[l-1],W[l],b[l]),Z[l])이다. A[l-1],W[l],b[l]는 input에서 넣어준 것과 동일하다.

 

4.3 L-layer model

 

linear_forward는 Z[l]을, linear_activation_forward는 A[l]을 계산해 주는 함수였다. L_model_forward 함수는 모든 층에 대해 Z[l], A[l]을 계산해 줄 것이다. 0층->1층, ... L-2층->L-1층의 [LINEAR -> RELU]를 L-1번 반복, L-1층->L층으로 [LINEAR -> SIGMOID]를 마지막으로 해주면서 forward propagation으로 A[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, parameters['W' + str(l)], parameters['b' + str(l)], activation="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)], activation="sigmoid")
    caches.append(cache)
    
    assert(AL.shape == (1,X.shape[1]))
            
    return AL, caches

 

for 문으로 l=1,2, ... , L-1일 때 parameters 딕셔너리의 Wl,bl, activation="relu"로 A[l]을 계산하고 그 때 cache: (A[l-1],W[l],b[l]),Z[l]))을 저장한다.

for 문이 끝나고 parameters의 WL,bL, activation="sigmoid"로 A[L]을 계산하고 cache를 저장한다.

A[L]과 caches가 출력되는데 caches는 ( ( A[0],W[1],b[1] ),Z[1] ), ... ,  ( A[L-1],W[L],b[L] ),Z[L] ) ) 으로 각 layer에 대해 tuple 형태로 저장된다.

 

5. Cost Function

 

 

def compute_cost(AL, Y):

    m = Y.shape[1]

    # Compute loss from aL and y.
    cost =  -np.sum(np.multiply(np.log(AL),Y) + np.multiply(np.log(1-AL),1-Y))/m
    
    cost = np.squeeze(cost)      # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).
    assert(cost.shape == ())
    
    return cost

 

forward propagation을 끝냈으니 A[L]과 Y를 비교하여 cost function을 계산한다.

 

6. Backward Propagation module

forward propagation으로 Z[l],A[l]을 계산하면서 cache에 ( ( A[l-1],W[l],b[l] ) ,Z[l] )을 저장했다면, 그것들로 backward propagation을 계산해야 한다.

 

6.1 Linear Backward

dZ[l]과 cache ( ( A[l-1],W[l],b[l] ) ,Z[l] ) 를 알고 있으면 Z[l]로부터 dW[l],db[l],dA[l-1]을 알 수 있다.

def linear_backward(dZ, cache):
    
    A_prev, W, b = cache
    m = A_prev.shape[1]

    dW = np.dot(dZ,A_prev.T)/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

 

6.2 Linear - Activation Backward

  • sigmoid backward: dZ[l] = sigmoid_backward(dA[l], activation_cache)
  • relu backward: dZ[l] = relu_backward(dA[l], activation_cache)

backward 과정을 할 때 activation function의 종류(sigmoid or relu)에 따라 g[l]()이 달라서 g'()이 다르기 때문에 dZ[l]을 계산하는 방법이 달라진다. 따라서 층에 따라 linear - activation backward를 다르게 처리해야 한다.

 

def linear_activation_backward(dA, cache, activation):
    
    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 = dZ = sigmoid_backward(dA, activation_cache)
        dA_prev, dW, db = linear_backward(dZ, linear_cache)
    
    return dA_prev, dW, db

 

linear_cache, activation_cache = cache를 하면, linear_cache에는 ( A[l-1],W[l],b[l] )가, activation_cache에는 Z[l]가 나온다.

relu_backward 또는 sigmoid_backward로 dZ[l] = dA[l] * g'[l](Z[l])을 계산해준다. 이 때 dA[l], activation_cache(Z[l])이 input으로 필요하고 dZ[l]이 출력된다.

linear_backward로는, relu/sigmoid_bacward로 계산된 dZ[l]와 linear_cache ( A[l-1],W[l],b[l] )로 dW[l], db[l], dA[l-1]을 계산한다. 

 

6.3 L-model backward

이제 각각의 layer에 대한 계산 말고, 한 번의 iteration 동안 backward propagation을 한 번에 수행하는 함수를 만들겠다. L층->L-1층으로 [LINEAR -> SIGMOID]를 수행하고, L-1층->L-2층, ... 1층->0층으로 [LINEAR -> RELU]를 L-1번 반복하겠다. 

L층->L-1층의  [LINEAR -> SIGMOID]에서는 dA[L]을 위와 같이 계산할 것이다.

여기서 받은 dA[L]로 [LINEAR -> RELU]에서 dA[l-1],dW[l],db[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: "dAL, current_cache". Outputs: "grads["dAL-1"], grads["dWL"], grads["dbL"]
    current_cache = caches[-1]
    grads["dA" + str(L-1)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, activation='sigmoid')
    
    # Loop from l=L-2 to l=0
    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 + 1)], current_cache, activation='relu')
        grads["dA" + str(l)] = dA_prev_temp
        grads["dW" + str(l + 1)] = dW_temp
        grads["db" + str(l + 1)] = db_temp

    return grads

[LINEAR -> SIGMOID]에서는 dA[L] 계산 후 linear_activation_backward에서 activation="sigmoid"로  dA[L-1],dW[L],db[L]을 계산하여 grads의 딕셔너리 안에 넣어줬다. 이 때 input으로 들어간 current_cache는 caches에서 L번째 tuple에 해당하는 cache이다.

다음 for문에서 [LINEAR -> RELU]을 계산하는데, L-1층->L-2층, ... , 1층->0층 이런 식으로 거꾸로 가니까 l을 reversed(range(L-1))로 설정하여 l = L-2, ... 0이 되게 한다.

current_cache는 caches에서 l번째 tuple에 해당하는 cache이다.

linear_activation_backward에서 activation="relu"로 dA[l+1]을 통해 dA[l],dW[l+1],db[l]을 계산하여 grads 딕셔너리 안에 넣어줬다. 

 

6.4 Update parameters

이제 L_model_backward를 통해 얻은 grads 안에 dW[1],db[1], ... dW[L],db[L]으로 update 된 W[1],b[1], ... W[L],b[L]을 얻을 수 있다.

 

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

 

grads 딕셔너리 안의 dW[l+1],db[l+1]로 새롭게 update 된 W[l+1],b[l+1]을 얻었고 이를 parameters 딕셔너리 안에 저장해준다.