코세라) 신경망 및 딥러닝 - 얕은 신경망 - Planar data classification with one hidden layer (2)

생각보다 간단쓰 도함수 계산과정 좀 다시한번 봐야되겠네요. 너무 새롭네 Exercise 5 - compute_cost 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 # GRADED FUNCTION: compute_cost def compute_cost(A2, Y): """ Computes the cross-entropy cost given in equation (13) Arguments: A2 -- The sigmoid output of the second activation, of shape (1, number of examples) Y -- "true" labels vector of shape (1, number of examples) Returns: cost -- cross-entropy cost given equation (13) """ m = Y.shape[1] # number of examples # Compute the cross-entropy cost # (≈ 2 lines of code) # logprobs = ... # cost = ... # YOUR CODE STARTS HERE logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1-A2), 1-Y) cost = - 1 * np.sum(logprobs) / m # YOUR CODE ENDS HERE cost = float(np.squeeze(cost)) # makes sure cost is the dimension we expect. # E.g., turns [[17]] into 17 return cost Exercise 6 - backward_propagation 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 # GRADED FUNCTION: backward_propagation def backward_propagation(parameters, cache, X, Y): """ Implement the backward propagation using the instructions above. Arguments: parameters -- python dictionary containing our parameters cache -- a dictionary containing "Z1", "A1", "Z2" and "A2". X -- input data of shape (2, number of examples) Y -- "true" labels vector of shape (1, number of examples) Returns: grads -- python dictionary containing your gradients with respect to different parameters """ m = X.shape[1] # First, retrieve W1 and W2 from the dictionary "parameters". #(≈ 2 lines of code) # W1 = ... # W2 = ... # YOUR CODE STARTS HERE W1 = parameters["W1"] W2 = parameters["W2"] # YOUR CODE ENDS HERE # Retrieve also A1 and A2 from dictionary "cache". #(≈ 2 lines of code) # A1 = ... # A2 = ... # YOUR CODE STARTS HERE A1 = cache["A1"] A2 = cache["A2"] # YOUR CODE ENDS HERE # Backward propagation: calculate dW1, db1, dW2, db2. #(≈ 6 lines of code, corresponding to 6 equations on slide above) # dZ2 = ... # dW2 = ... # db2 = ... # dZ1 = ... # dW1 = ... # db1 = ... # YOUR CODE STARTS HERE dZ2 = A2 - Y dW2 = np.dot(dZ2, A1.T) / m db2 = np.sum(dZ2, axis=1, keepdims = True) / m dZ1 = np.dot(W2.T, dZ2) * (1 - np.power(A1, 2)) dW1 = np.dot(dZ1, X.T) / m db1 = np.sum(dZ1, axis=1, keepdims = True) / m # YOUR CODE ENDS HERE grads = {"dW1": dW1, "db1": db1, "dW2": dW2, "db2": db2} return grads Exercise 7 - update_parameters 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 # GRADED FUNCTION: update_parameters def update_parameters(parameters, grads, learning_rate = 1.2): """ Updates parameters using the gradient descent update rule given above Arguments: parameters -- python dictionary containing your parameters grads -- python dictionary containing your gradients Returns: parameters -- python dictionary containing your updated parameters """ # Retrieve a copy of each parameter from the dictionary "parameters". Use copy.deepcopy(...) for W1 and W2 #(≈ 4 lines of code) # W1 = ... # b1 = ... # W2 = ... # b2 = ... # YOUR CODE STARTS HERE parameters_cp = copy.deepcopy(parameters) W1 = parameters_cp["W1"] b1 = parameters_cp["b1"] W2 = parameters_cp["W2"] b2 = parameters_cp["b2"] # YOUR CODE ENDS HERE # Retrieve each gradient from the dictionary "grads" #(≈ 4 lines of code) # dW1 = ... # db1 = ... # dW2 = ... # db2 = ... # YOUR CODE STARTS HERE dW1 = grads["dW1"] db1 = grads["db1"] dW2 = grads["dW2"] db2 = grads["db2"] # YOUR CODE ENDS HERE # Update rule for each parameter #(≈ 4 lines of code) # W1 = ... # b1 = ... # W2 = ... # b2 = ... # YOUR CODE STARTS HERE W1 = W1 - learning_rate * dW1 b1 = b1 - learning_rate * db1 W2 = W2 - learning_rate * dW2 b2 = b2 - learning_rate * db2 # YOUR CODE ENDS HERE parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} return parameters Exercise 8 - nn_model 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 # GRADED FUNCTION: nn_model def nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False): """ Arguments: X -- dataset of shape (2, number of examples) Y -- labels of shape (1, number of examples) n_h -- size of the hidden layer num_iterations -- Number of iterations in gradient descent loop print_cost -- if True, print the cost every 1000 iterations Returns: parameters -- parameters learnt by the model. They can then be used to predict. """ np.random.seed(3) n_x = layer_sizes(X, Y)[0] n_y = layer_sizes(X, Y)[2] # Initialize parameters #(≈ 1 line of code) # parameters = ... # YOUR CODE STARTS HERE parameters = initialize_parameters(n_x, n_h, n_y) # YOUR CODE ENDS HERE # Loop (gradient descent) for i in range(0, num_iterations): #(≈ 4 lines of code) # Forward propagation. Inputs: "X, parameters". Outputs: "A2, cache". # A2, cache = ... # Cost function. Inputs: "A2, Y". Outputs: "cost". # cost = ... # Backpropagation. Inputs: "parameters, cache, X, Y". Outputs: "grads". # grads = ... # Gradient descent parameter update. Inputs: "parameters, grads". Outputs: "parameters". # parameters = ... # YOUR CODE STARTS HERE A2, cache = forward_propagation(X, parameters) cost = compute_cost(A2, Y) grads = backward_propagation(parameters, cache, X, Y) parameters = update_parameters(parameters, grads) # YOUR CODE ENDS HERE # Print the cost every 1000 iterations if print_cost and i % 1000 == 0: print ("Cost after iteration %i: %f" %(i, cost)) return parameters Exercise 9 - predict 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 # GRADED FUNCTION: predict def predict(parameters, X): """ Using the learned parameters, predicts a class for each example in X Arguments: parameters -- python dictionary containing your parameters X -- input data of size (n_x, m) Returns predictions -- vector of predictions of our model (red: 0 / blue: 1) """ # Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as the threshold. #(≈ 2 lines of code) A2, cache = forward_propagation(X, parameters) predictions = np.round(A2) # YOUR CODE STARTS HERE # YOUR CODE ENDS HERE return predictions

8월 15, 2024 · Jaejin Jang

코세라) 신경망 및 딥러닝 - 얕은 신경망 - Planar data classification with one hidden layer

행렬간 차원의 개수와 수식이 쪼~금 이해가 되네요 Exercise 2 - layer_sizes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 # GRADED FUNCTION: layer_sizes def layer_sizes(X, Y): """ Arguments: X -- input dataset of shape (input size, number of examples) Y -- labels of shape (output size, number of examples) Returns: n_x -- the size of the input layer n_h -- the size of the hidden layer n_y -- the size of the output layer """ #(≈ 3 lines of code) # n_x = ... # n_h = ... # n_y = ... # YOUR CODE STARTS HERE n_x = X.shape[0] n_h = 4 n_y = Y.shape[0] # YOUR CODE ENDS HERE return (n_x, n_h, n_y) Exercise 3 - initialize_parameters 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 # GRADED FUNCTION: initialize_parameters def initialize_parameters(n_x, n_h, n_y): """ Argument: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: params -- python dictionary containing your parameters: W1 -- weight matrix of shape (n_h, n_x) b1 -- bias vector of shape (n_h, 1) W2 -- weight matrix of shape (n_y, n_h) b2 -- bias vector of shape (n_y, 1) """ #(≈ 4 lines of code) # W1 = ... # b1 = ... # W2 = ... # b2 = ... # YOUR CODE STARTS HERE 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)) # YOUR CODE ENDS HERE parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} return parameters Exercise 4 - forward_propagation 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 # GRADED FUNCTION:forward_propagation def forward_propagation(X, parameters): """ Argument: X -- input data of size (n_x, m) parameters -- python dictionary containing your parameters (output of initialization function) Returns: A2 -- The sigmoid output of the second activation cache -- a dictionary containing "Z1", "A1", "Z2" and "A2" """ # Retrieve each parameter from the dictionary "parameters" #(≈ 4 lines of code) # W1 = ... # b1 = ... # W2 = ... # b2 = ... # YOUR CODE STARTS HERE W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] # YOUR CODE ENDS HERE # Implement Forward Propagation to calculate A2 (probabilities) # (≈ 4 lines of code) # Z1 = ... # A1 = ... # Z2 = ... # A2 = ... # YOUR CODE STARTS HERE Z1 = np.dot(W1, X) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) # YOUR CODE ENDS HERE assert(A2.shape == (1, X.shape[1])) cache = {"Z1": Z1, "A1": A1, "Z2": Z2, "A2": A2} return A2, cache

8월 14, 2024 · Jaejin Jang

코세라) 신경망 및 딥러닝 - 파이썬과 벡터화 - 신경망 사고방식의 로지스틱 회귀 분석

단순하지만 기본이 되는 매우 중요한 과제입니다. 원래 기본이 가장 중요한 것 로지스틱 회귀 모델을 구축하여 고양이 이미지를 인식하는 시스템을 만드는 과제입니다. 기본적인 로지스틱 회귀 모델의 구현과 평가 방법을 익히며, 딥러닝의 기초적인 개념을 이해하고, 실질적인 머신러닝 모델을 만들어 봅니다. Exercise 1 shape를 통해 길이관련 정보에 접근할 수 있다는 것을 알아야 합니다. output을 보면 아시겠지만 트레이닝 이미지가 4차원 배열입니다.. 숫자로 적혀있으니 별 것 아닌것 같지만, 우리가 현실세계에서 4차원 공간을 마주할 일을 없습니다. 그것을 잘 표현해 놓은것이 인터스텔라의 테서렉트입니다(제 인생영화중에 하나라서 괜히 말함) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 # YOUR CODE STARTS HERE m_train = train_set_x_orig.shape[0] m_test = test_set_x_orig.shape[0] num_px = train_set_x_orig.shape[1] # YOUR CODE ENDS HERE print ("Number of training examples: m_train = " + str(m_train)) print ("Number of testing examples: m_test = " + str(m_test)) print ("Height/Width of each image: num_px = " + str(num_px)) print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)") print ("train_set_x shape: " + str(train_set_x_orig.shape)) print ("train_set_y shape: " + str(train_set_y.shape)) print ("test_set_x shape: " + str(test_set_x_orig.shape)) print ("test_set_y shape: " + str(test_set_y.shape)) ## output Number of training examples: m_train = 209 Number of testing examples: m_test = 50 Height/Width of each image: num_px = 64 Each image is of size: (64, 64, 3) train_set_x shape: (209, 64, 64, 3) train_set_y shape: (1, 209) test_set_x shape: (50, 64, 64, 3) test_set_y shape: (1, 50) Exercise 2 reshape에서 -1의 의미를 알아야 합니다. 하나의 인자만 -1로 넘길 수 있는데, -1인 부분은 나머지 값을 통해 추론하겠다라는 의미입니다. 1 2 train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T Exercise 3 - sigmoid 1 2 3 def sigmoid(z): s = 1/(1+np.exp(-z)) return s Exercise 4 - initialize_with_zeros 1 2 3 4 def initialize_with_zeros(dim): w = np.zeros((dim, 1)) b = 0.0 return w, b Exercise 5 - propagate 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 def propagate(w, b, X, Y): m = X.shape[1] A = cost = dw = db = cost = np.squeeze(np.array(cost)) grads = {"dw": dw, "db": db} return grads, cost Exercise 6 - optimize 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 def optimize(w, b, X, Y, num_iterations=100, learning_rate=0.009, print_cost=False): w = copy.deepcopy(w) b = copy.deepcopy(b) costs = [] for i in range(num_iterations): grads, cost = propagate(w, b, X, Y) dw = grads["dw"] db = grads["db"] w = w - learning_rate*dw b = b - learning_rate*db # Record the costs if i % 100 == 0: costs.append(cost) if print_cost: print ("Cost after iteration %i: %f" %(i, cost)) params = {"w": w, "b": b} grads = {"dw": dw, "db": db} return params, grads, costs Exercise 7 - predict 1 2 3 4 5 6 7 8 9 10 11 12 13 14 def predict(w, b, X): m = X.shape[1] Y_prediction = np.zeros((1, m)) w = w.reshape(X.shape[0], 1) Z = np.dot(w.T, X) + b A = 1 / (1 + np.exp(-Z)) for i in range(A.shape[1]): if A[0, i] > 0.5 : Y_prediction[0,i] = 1 else: Y_prediction[0,i] = 0 return Y_prediction Exercise 8 - model 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False): w, b = initialize_with_zeros(X_train.shape[0]) params, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, True) w = params["w"] b = params["b"] Y_prediction_test = predict(w, b, X_test) Y_prediction_train = predict(w, b, X_train) if print_cost: print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100)) print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100)) d = {"costs": costs, "Y_prediction_test": Y_prediction_test, "Y_prediction_train" : Y_prediction_train, "w" : w, "b" : b, "learning_rate" : learning_rate, "num_iterations": num_iterations} return d

7월 27, 2024 · Jaejin Jang

코세라) 신경망 및 딥러닝 - 파이썬과 벡터화 - 넘파이를 사용한 파이썬 기초

기본적인 Python과 Numpy 라이브러리 사용법을 익히고, 머신 러닝 모델의 기본적인 수학적 구성 요소를 작성해보는 과제입니다. Exercise 2 - basic_sigmoid 시그모이드 함수를 math 라이브러리를 이용하여 구현한 것입니다. 일반적으로 행열을 처리할 수 있는 np를 쓰는데, 그 반대의 경우(math)를 보여줌으로써 np를 강조하는건가 봐요. 1 2 3 4 5 import math def basic_sigmoid(x): s = 1/(1+math.exp(-x)) return s Exercise 3 - sigmoid np를 이용해 구현합니다. 1 2 3 def sigmoid(x): s = 1/(1+np.exp(-x)) return s Exercise 4 - sigmoid_derivative 1 2 3 4 def sigmoid(x): s = 1/(1+np.exp(-x)) ds = s*(1-s) return ds Exercise 5 - image2vector reshape() 차원인자에 한개의 -1을 전달할 수 있습니다. -1로 전달하면 나머지 차원인자로 부터 차원을 추론하여 동작합니다. 1 2 3 4 5 def image2vector(image): v = image.reshape(image.shape[0] * image.shape[1] * image.shape[2], 1) # v = image.reshape(-1, 1) # v = np.reshape(image, (image.shape[0] * image.shape[1] * image.shape[2], 1)) return v Exercise 6 - normalize_rows 1 2 3 4 def normalize_rows(x): x_norm = np.linalg.norm(x, axis=1, keepdims = True) x = np.divide(x, x_norm) return x Exercise 7 - softmax axis는 0과 1에 따라 행으로 동작(column-wise)할건지 열(row-wise)로 동작할것인지, keepdims는 브로드캐스팅 유무입니다 1 2 3 4 5 def softmax(x): x_exp = np.exp(x) x_sum = np.sum(x_exp, axis=1, keepdims = True) s = np.divide(x_exp, x_sum) return s Exercise 8 - L1 1 2 3 def L1(yhat, y): loss = np.sum(abs(np.subtract(yhat, y))) return loss Exercise 9 - L2 1 2 3 def L2(yhat, y): loss = np.sum(np.dot(np.subtract(yhat, y),np.subtract(yhat, y))) return loss

7월 17, 2024 · Jaejin Jang

코세라) 신경망 및 딥러닝 - 파이썬과 벡터화

1. Vectorization 벡터화가 무엇인지 프로그래밍 관점에서 설명하고 있습니다. 벡터화하지 않으면 반복문을 돌아야 하지만, 백터화하면 반복문없이 수행할 수 있습니다. SIMD(Single instruction, multiple data)가 GPU에서만 수행되는 것은 아닙니다. CPU에서도 수행됩니다. (저는 GPU에서만 되는줄 알고 있었뜸..) 벡터화와 SIMD가 연결되는 것은 자연스러운 전개입니다. n개의 w와 x가 한번의 명령에 의해 처리(SIMD)되니까요. 2. More vectorization examples ...

7월 16, 2024 · Jaejin Jang

코세라) 신경망 및 딥러닝 - 신경망으로서의 로지스틱 회귀

1. Binary Classification y가 0, 1일 때 사용하는 분류입니다. 로지스틱 회귀(Logistic regression)는 이진 분류를 위한 알고리즘 중 하나입니다. 2. Notation ...

7월 14, 2024 · Jaejin Jang

코세라) 신경망 및 딥러닝 - 딥러닝 소개

1. 단일 신경망의 예 집의 크기를 특징으로 가격을 예층하는 단일 신경망이라고 볼 수 있습니다. 그래프를 보아하니 Relu 함수로 표현할 수 있습니다. 2. 댜중 신경망의 예 ...

7월 9, 2024 · Jaejin Jang