Lec-02 Simple Liner Regression LAB

leban·2021년 10월 11일
0

딥러닝

목록 보기
3/18

>> Hypothesis and Cost

Hypothesis

Cost

  • cost가 최소화 되는 W와 b값을 구하는 것을 학습이라고 할 수 있음.

cost function을 tesorflow로 어떻게 옮길까?
x_data = [1,2,3,4,5]
y_data = [1,2,3,4,5]

W = tf.Variable(2.9)
b = tf.Variable(0.5)
hypothesis = W * x_data + b
cost(W,b)
cost = tf.reduce_mean(tf.square(hypothesis - y_data))

: 입력과 출력 x와 y값이 같으려면 W값은 1, b값은 0이 되어야 한다.

tf.reduce_mean()
v = [1., 2., 3., 4.] 
tf.reduce_mean(v) #2.5
tf.square()
tf.square(3) #9

Gradient descent (=경사 하강 알고리즘)
: minimize cost(W,b)
: learning_rate = 0.01

# 변수(W,b)에 대한 정보 tape에 기록_
with tf.GradientTape() as tape: 	 
    hypothesis = W * x_data + b
    cost = tf.reduce_mean(tf.square(hypothesis - y_data))
#기울기 값 즉 미분값을 구함._
W_grad, b_grad = tape.gradient(cost, [W,b]) 
W.assign_sub(learning_rate * W_grad)
b.assign_sub(learning_rate * b_grad)
  • A.assign_sub(B)
    : A = A - B
    : A-=B

Full Code

import tensorflow as tf
#Data
x_data = [1,2,3,4,5]
y_data = [1,2,3,4,5]
  
# W, b initialize
W = tf.Variable(2.9)
b = tf.Variable(0.5)
  
learning_rate = 0.01
  
for i in range(100+1): # W, b update
# Gradient descent
    with tf.GradientTape() as tape:
        hypothesis = W * x_data + b
        cost = tf.reduce_mean(tf.square(hypothesis - y_data))
    W_grad, b_grad = tape.gradient(cost, [W,b])
    W.assign_sub(learning_rate * W_grad)
    b.assign_sub(learning_rate * b_grad)
    if i % 10 == 0:
        print("{:5}|{:10.4f}|{:10.4}|{:10.6f}".format(i, W.numpy(), b.numpy(), cost))

Colab을 사용하여 실행해본 코드 결과

모두를 위한 딥러닝 시즌2 - Tensorflow

0개의 댓글