-
Simple Linear Regression(단순선형회귀)Machine learning, Deep learning 2020. 6. 29. 21:53
Build a hypothesis and cost
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 + b hypothesis = W * x_data + b
cost = tf.reduce_mean(tf.square(hypothesis - y_data)) # 제곱의 평균 # tf.reduce_mean -> 차원이 줄어들면서 평균을 구한다 # tf.square -> 제곱
cost를 최소화하는 W,b를 찾는 minimizaiton 알고리즘들 중 gradient(경사, 기울기) descent(하강)가 유명하다.
"경사 내려가면서 cost가 작은 지점 찾자잉"
# Learning_rate initialzie learning_rate = 0.01 # 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) # learning_rate는 gradient 값을 얼마만큼 반영을 할지 정하는 것이다. 주로 작은 값을 사용한다. # 참고 A.assign_sub(B) A = A - B A -= B
# 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 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: # i 가 10의 배수일 때마다 print("{:5}|{:10.4f}|{:10.4}|{:10.6f}".format(i, W.numpy(), b.numpy(), cost))
i, W, b, cost순으로 결과값들이 나온다.
여러번 학습을 통해 cost가 0에 가까워진다.
'Machine learning, Deep learning' 카테고리의 다른 글
Multi-variable Linear Regression (0) 2020.07.03 Linear Regression and How to minimize cost (0) 2020.07.03 Lecture4_Backpropagation and Neural Networks (0) 2020.07.02 Regression_회귀의 기본 개념 (0) 2020.06.29 CS231n_Lecture3_Loss Function and Optimization (0) 2020.06.28