관리 메뉴

ComputerVision Jack

[모두의 딥러닝 Chapter09] 본문

DeepLearning/DL_ZeroToAll

[모두의 딥러닝 Chapter09]

JackYoon 2020. 1. 21. 16:23
반응형

[9-1 xor]

심층 신경망이 나오게 된 배경.

데이터가 선형으로 분리할 수 없게 등장하기 시작했다. (실제의 모든 데이터는 선형이지 않는다.)

그 중 대표적인 문제 xor 문제이다.

 

x_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype = np.float32)

y_data = np.array([[0], [1], [1], [0]], dtype = np.float32)

#xor dataset을 준비한다.

 

X = tf.placeholder(tf.float32, [None, 2])

Y = tf.placeholder(tf.float32, [None, 1])

#placeholder 공간 설정

 

W = tf.Variable(tf.random_normal([2, 1]), name = 'weight')

b = tf.Variable(tf.random_normal([1]), name ='bias')

#가중치와 편향을 설정한다.

 

hypothesis = tf.sigmoid(tf.matmul(X, W) + b)

#xor문제도 이진 분류기이기 떄문에 sigmoid활성함수를 사용하여 출력한다.

 

cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) * tf.log(1 - hypothesis))

train = tf.train.GradientDescentOptimizer(learning_rate = 0.1).minimize(cost)

#cost함수와 optimizer를 설정한다.

 

predicted = tf.cast(hypothesis > 0.5, dtype = tf.float32)

accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype = tf.float32))

#정확도를 예측하기 위한 작업을 설정한다.

 

with tf.Session() as sess:

  sess.run(tf.global_variables_initializer())

  for step in range(10001):

    _,cost_val,W_val = sess.run([train, cost, W], feed_dict = {X: x_data, Y: y_data})

    if step % 100 == 0:

      print(step, cost_val, W_val)

  h, c, a = sess.run([hypothesis, predicted, accuracy], feed_dict = {X:x_data, Y: y_data})

  print("Hypothesis : ", h, "\nCorrect : ", c, "\nPrediction : ", a)

#실제로 학습을 시킨 결과 절대로 완벽하게 분리해 낼 수 없다.

정확도가 1이 되지 않는다. Prediction이 잘 나와야 0.5

[9-2 xor-nn]

심층망 생성

따라서 이번엔 내부의 신경망의 깊이를 추가하여 학습을 시킨다.

(도메인 차원을 늘린다고 생각하면된다. 2차원에선 분류되지 않지만 3차원은 분류할 수 있다.)

 

W1 = tf.Variable(tf.random_normal([2, 1]), name ='weight1')

b1 = tf.Variable(tf.random_normal([2]), name = 'bias1')

layer1 = tf.sigmoid(tf.matmul(X, W1) + b1)

#layer1을 만든다. 여기다 layer2를 연결하여 학습 시킨다.

 

W2 = tf.Variable(tf.random_normal([2, 1]), name= 'weight2')

b2 = tf.Variable(tf.random_normal([1]), name= 'bias2')

hypothesis = tf.sigmoid(tf.matmul(layer1, W2) + b2)

#layer2를 생성하여 layer1과 연결한다.

layer를 추가하여 학습을 시킨경우 정확도가 1.0이 되고, 학습이 제대로 이루어진다.

[9-3 xor-nn-wide-deep]

심층 신경망 생성.

더 wide하게 신경망을 구성하자. 9-2는 2개의 레이어층을 사용했지만, 2개말고 더 깊게 연결해보는 예제

W1 = tf.Variable(tf.random_normal([2, 10]), name ='weight1')

b1 = tf.Variable(tf.random_normal([10]), name = 'bias1')

layer1 = tf.sigmoid(tf.matmul(X, W1) + b1)

 

W2 = tf.Variable(tf.random_normal([10, 10]), name= 'weight2')

b2 = tf.Variable(tf.random_normal([10]), name='bias2')

layer2 = tf.sigmoid(tf.matmul(layer1, W2) + b2)

 

W3 = tf.Variable(tf.random_normal([10, 10]), name= 'weight3')

b3 = tf.Variable(tf.random_normal([10]), name='bias3')

layer3 = tf.sigmoid(tf.matmul(layer2, W3) + b3)

 

W4 = tf.Variable(tf.random_normal([10, 1]), name= 'weight4')

b4 = tf.Variable(tf.random_normal([1]), name = 'bias4')

hypothesis = tf.sigmoid(tf.matmul(layer3, W4) + b4)

#총 레이어 층을 4개로 연결하여 신경망을 학습시킨다.

신경망을 깊게 연결해도 제대로 학습이 연결되는 것을 확인할 수 있다.

하지만 무조건 신경망을 깊게 연결해서 좋은것은 없다.

[9-5 linear_back_prop]

신경망을 학습 시키기 위한 방법. 출력부터 입력층 까지 w,b에 대해서 거슬러 올라가며 수정하는 알고리즘

역전파. tensorflow는 복잡한 역전파에 대해서 기능을 지원한다.

 

hypothesis = tf.matmul(X, W) + b

#우선 모델을 설정한다.

 

d_l1 = diff

d_b = d_l1

d_w = tf.matmul(tf.transpose(X), d_l1)

#chain Rule인 역전파 알고리즘을 생성한다.

 

learning_rate = 0.1

step = [

        tf.assign(W, W - learning_rate * d_w),

        tf.assign(b, b - learning_rate * tf.reduce_mean(d_b)),

]

#learning_rate을 설정하고 단계별로 가중치와 편향을 할당한다.

 

RMSE = tf.reduce_mean(tf.square((Y - hypothesis)))

#RMSE오차 방법을 사용한다.

 

for i in range(1000):

  print(i, sess.run([step, RMSE], feed_dict = {X: x_data, Y: y_data}))

#결과 실행

[9-6 multi-linear-back_prop]

이번엔 multi linear에 대한 back_prop에 대하여 알아본다.

x_data = [[73., 80., 75.],

          [93., 88., 93.],

          [89., 91., 90.],

          [96., 98., 100.],

          [73., 66., 70.]]

y_data = [[152.],[185.],[180.], [196.], [142.]]

#multi variable에 대한 dataset을 준비한다.

 

hypothesis = tf.matmul(X, W) + b

#사용될 모델을 설정한다.

 

assert hypothesis.shape.as_list() == Y.shape.as_list()

diff = (hypothesis - Y)

d_l1 = diff

d_b = d_l1

d_w = tf.matmul(tf.transpose(X), d_l1)

#back_prop에 대하여 설정한다. 거슬러 올라간다고 생각하면 된다.

 

learning_rate = 1e-6

step = [

        tf.assign(W, W - learning_rate * d_w),

        tf.assign(b, b - learning_rate * tf.reduce_mean(d_b)),

]

#learning_Rate을 부여하고 단계별로 거슬러 올라갈때의 w와 b를 추정한다.

 

RMSE = tf.reduce_mean(tf.square((Y - hypothesis)))

#cost함수는 마찬가지로 RMSE 오차를 사용한다.

[9-7 sigmoid_back_prop]

sigmoid함수가 적용되는 예제에 대한 back_prop 적용을 확인한다.

assert y_pred.shape.as_list() == target.shape.as_list()

d_loss = (y_pred - target) / (y_pred * (1. - y_pred) + 1e-7)

d_sigma = sigma_prime(layer_1)

d_layer = d_loss * d_sigma

d_b = d_layer

d_W = tf.matmul(tf.transpose(X), d_layer)

#별 어려운거 없이. 똑같이 back_prop작업을 설정하고 적용시키면된다.

 

learning_rate = 0.01

train_step = [

    tf.assign(W, W - learning_rate * d_W),

    tf.assign(b, b - learning_rate * tf.reduce_sum(d_b)),

]

#learning_Rate설정과 단계별로 w와b를 적용시킨다.

학습을 시키면 겨로가를 알 수 있다.

[9-x xor-nn-back_prop]

앞의 xor문제에 대한 back_prop설정을 확인한다.

레이어에 대한 back_prop을 설정하여 적용해야한다.

d_sigma2 = Y_pred * (1 - Y_pred)

d_a2 = d_Y_pred * d_sigma2

d_p2 = d_a2

d_b2 = d_a2

d_W2 = tf.matmul(tf.transpose(l1), d_p2)

 

d_b2_mean = tf.reduce_mean(d_b2, axis=[0])

d_W2_mean = d_W2 / tf.cast(tf.shape(l1)[0], dtype=tf.float32)

 

d_l1 = tf.matmul(d_p2, tf.transpose(W2))

d_sigma1 = l1 * (1 - l1)

d_a1 = d_l1 * d_sigma1

d_b1 = d_a1

d_p1 = d_a1

d_W1 = tf.matmul(tf.transpose(X), d_a1)

 

d_W1_mean = d_W1 / tf.cast(tf.shape(X)[0], dtype=tf.float32)

d_b1_mean = tf.reduce_mean(d_b1, axis=[0])

#layer층에 대한 back_prop작업을 설정한다.

 

step = [

  tf.assign(W2, W2 - learning_rate * d_W2_mean),

  tf.assign(b2, b2 - learning_rate * d_b2_mean),

  tf.assign(W1, W1 - learning_rate * d_W1_mean),

  tf.assign(b1, b1 - learning_rate * d_b1_mean)

]

#step별로 layer1과 layer2에 적용될 값을 정리한다.

학습을 시키면 back_prop에 대해 알 수 있다.

 

중요한 것은, 데이터가 선형이 아닌 경우 신경망을 깊게 연결하여 해결하는 것과

신경망의 w와 b값을 알아내어 최적화 시키는 방법으로 역전파 알고리즘이 있다는 것이다.

09-1-xor.ipynb
0.01MB
09-2-xor-nn.ipynb
0.01MB
09-3-xor-nn-wide-deep.ipynb
0.01MB
09-4-xor-tensorfboard.ipynb
0.01MB
09-5-linear_back_prop.ipynb
0.08MB
09-6-multi-linear_back_prop.ipynb
1.16MB
09-7-sigmoid_back_prop.ipynb
0.02MB
09-x-xor-nn-back_prop.ipynb
0.01MB

반응형

'DeepLearning > DL_ZeroToAll' 카테고리의 다른 글

[모두의 딥러닝 Chapter11]  (0) 2020.01.23
[모두의 딥러닝 Chapter10]  (0) 2020.01.22
[모두의 딥러닝 Chapter08]  (0) 2020.01.20
[모두의 딥러닝 Chapter07]  (0) 2020.01.19
[모두의 딥러닝 Chapter06]  (0) 2020.01.17
Comments