-
Numpy: main package for scientific computing in python
**더하기, 빼기 등 연산시 np.add, np.multipy, np.sum 사용하기**
1) building basic functions w/ numpy
1-1 sigmoid function, np.exp():
- math.exp(): 지수함수(x -> e^x)
import math def basic_sigmoid(x): """ Compute sigmoid of x. Arguments: x -- A scalar Return: s -- sigmoid(x) """ s = 1/ (1 + math.exp(-x)) return s
- 하지만 딥러닝에서는 행렬과 벡터를 더 많이 사용 -> numpy를 사용한다!
- x = (x1, x2, ..., xn)일 때, np.exp(x) = (e^x1, e^x2, ..., e^xn)
import numpy as np # example of np.exp x = np.array([1, 2, 3]) print(np.exp(x)) # result is (exp(1), exp(2), exp(3))
result: [ 2.71828183 7.3890561 20.08553692]
- numpy에서 sigmoid 함수:
import numpy as np # this means you can access numpy functions by writing np.function() instead of numpy.function() def sigmoid(x): """ Compute the sigmoid of x Arguments: x -- A scalar or numpy array of any size Return: s -- sigmoid(x) """ s = 1 / (1+ np.exp(-x)) return s x = np.array([1, 2, 3]) sigmoid(x)
result: array([ 0.73105858, 0.88079708, 0.95257413])
1-2 Sigmoid gradient
- backpropagation을 사용하여 loss function을 업데이트하기 위해 gradient를 계산
sigmoid_derivative(x) = σ'(x) = σ(x)(1-σ(x))
def sigmoid_derivative(x): """ Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x. You can store the output of the sigmoid function into variables and then use it to calculate the gradient. Arguments: x -- A scalar or numpy array Return: ds -- Your computed gradient. """ s = 1 / (1+ np.exp(-x)) ds = np.multiply(s, 1-s) return ds x = np.array([1, 2, 3]) print ("sigmoid_derivative(x) = " + str(sigmoid_derivative(x)))
result: sigmoid_derivative(x) = [ 0.19661193 0.10499359 0.04517666]
1-3 Reshaping arrays
- 딥러닝에서 많이 사용되는 np함수 중에는 np.shape, np.reshape가 있음.
- np.shape(): 행렬이나 벡터 X에 대한 모양(차원)을 알려주는 함수
- np.reshape(): X를 다른 차원으로 바꿔주기 위해 사용.
3차원의 이미지(length, height, depth = 3) -> 1차원 벡터(length * height * 3, 1), 즉 3D 배열을 1D 벡터로 unroll/reshape ex) 3차원 -> 1차원으로 변환
# GRADED FUNCTION: image2vector def image2vector(image): """ Argument: image -- a numpy array of shape (length, height, depth) Returns: v -- a vector of shape (length*height*depth, 1) """ # image.shape[0]: length, image.shape[1]: height, image.shape[2]: depth v = image.reshape((image.shape[0]*image.shape[1]*image.shape[2], 1)) return v # This is a 3 by 3 by 2 array, typically images will be (num_px_x, num_px_y,3) where 3 represents the RGB values image = np.array([[[ 0.67826139, 0.29380381], [ 0.90714982, 0.52835647], [ 0.4215251 , 0.45017551]], [[ 0.92814219, 0.96677647], [ 0.85304703, 0.52351845], [ 0.19981397, 0.27417313]], [[ 0.60659855, 0.00533165], [ 0.10820313, 0.49978937], [ 0.34144279, 0.94630077]]]) print ("image2vector(image) = " + str(image2vector(image)))
result: image2vector(image) = [[ 0.67826139] [ 0.29380381] [ 0.90714982] [ 0.52835647] [ 0.4215251 ] [ 0.45017551] [ 0.92814219] [ 0.96677647] [ 0.85304703] [ 0.52351845] [ 0.19981397] [ 0.27417313] [ 0.60659855] [ 0.00533165] [ 0.10820313] [ 0.49978937] [ 0.34144279] [ 0.94630077]]
1-4 Normalizing rows
- 머신러닝과 딥러닝에서 많이 쓰이는 또 다른 기법은 data normalization
- normalization 이후에는 gradient descent도 빠르게 수렴하기 때문에 better performance를 보이게 됨.
ex) x = [0, 3, 4], [2, 6, 4]]
||x|| = np.linalg.norm(x, axis =1, keepdims = True) = [[5], [√56]]
x_normalized = x / ||x|| = [[0, 3/5, 4/5], [2/√56, 6/√56,4/√56]]
def normalizeRows(x): """ Implement a function that normalizes each row of the matrix x (to have unit length). Argument: x -- A numpy matrix of shape (n, m) Returns: x -- The normalized (by row) numpy matrix. You are allowed to modify x. """ x_norm = np.linalg.norm(x, axis =1, keepdims = True) # Divide x by its norm. x = x / x_norm return x x = np.array([ [0, 3, 4], [1, 6, 4]]) print("normalizeRows(x) = " + str(normalizeRows(x)))
result: normalizeRows(x) = [[ 0. 0.6 0.8 ] [ 0.13736056 0.82416338 0.54944226]]
1-5 Broadcasting and the softmax function(https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
- numpy에서는 broadcasting이 매우 중요하다.
- broadcasting은 numpy가 다른 모양의 배열을 어떻게 다룰지에 대한 것으로, 어떠한 조건을 만족하는 경우 배열의 크기가 다르더라도 연산이 가능해진다.
1) 차원의 크기가 1일 때
2) 축의 크기가 같은 경우 연산이 가능!
2) Vectorization
- 딥러닝에서는 엄청나게 큰 데이터셋들을 다루게 된다. 따라서 코드가 계산하기에 효율적이여야 계산 중간에 문제가 생기지 않는다.
- vectorized implementation이 훨씬 더 깔끔하고 효율적인 동작을 한다.
2-1 Implement the L1 and L2 loss functions
- loss는 모델의 performance를 평가하기 위해 사용된다. loss가 클수록 ŷ와 y 간에 차이가 커지게 된다. 딥러닝은 이러한 loss를 줄이기 위한 방향으로 모델을 학습시켜나간다.
-np.abs(): 절댓값 함수
L1 loss def L1(yhat, y): """ Arguments: yhat -- vector of size m (predicted labels) y -- vector of size m (true labels) Returns: loss -- the value of the L1 loss function defined above """ loss = np.sum(np.abs(y - yhat)) return loss yhat = np.array([.9, 0.2, 0.1, .4, .9]) y = np.array([1, 0, 0, 1, 1]) print("L1 = " + str(L1(yhat,y)))
result: L1 = 1.1
- np.dot(): 곱한다음 합해주는 함수.(예를 들어 x = [x1, x2, ..., xn], np.dot(x, x) = x^2의 합)
L2 loss '연구실' 카테고리의 다른 글
#6. Building your Deep Neural Network: Step by Step (0) 2019.10.04 #5. Classification with one hidden layer (0) 2019.10.02 #4. Logistic Regression with a Neural Network midset (0) 2019.09.29 #2. CNN (0) 2019.09.23 #1. Backpropagation (0) 2019.09.23