Lec-02 2 Simple Linear Regression

박준영·2025년 11월 10일

딥러닝 공부

목록 보기
3/23

Simple Linear Regression LAB

=> 단순 선형 회귀를 TensorFlow 코드로 어떻게 구현/실행하는지.

remind

  • Hypothesis => H(x)=Wx+bH(x) = Wx + b
  • Cost Function => cost(W)=1mi=1m(H(Wxi)yi)2\text{cost}(W)=\frac{1}{m}\sum_{i=1}^{m}\big(H(Wx_i)-y_i\big)^2
  • Learning (학습) : 이 cost가 가장 작게 되는 W와 b를 구하는 것.

가설과 비용 코드

  • H(x)=Wx+bH(x) = Wx + b
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(W)=1mi=1m(H(Wxi)yi)2\text{cost}(W)=\frac{1}{m}\sum_{i=1}^{m}\big(H(Wx_i)-y_i\big)^2
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
# 에러 제곱의 평균으로 cost를 구하고 있다.
# tf.reduce_mean() : 평균
# tf.square() : 제곱

가장 유명한 Minimize Cost 함수

  • Gradient descent (경사하강법) => 함수의 미분 경사를 내려가면서 W와 b를 구한다.
# learning_rate initialize
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))
# GradientTape은 with와 함께 쓰인다.
# with 구문 안에 있는 변수(여기서는 W, b)들의 변화를 tape에다가 저장한다.
# 그리고 밑에서 tape의 gradient 메소드를 호출해서 경사도 값(= 미분값)을 구한다.

# gradient 메서드는 cost에 대한 변수들에 대한 개별 미분값(= 기울기 값)을 구해서 튜플로 반환한다.
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)
# learning_rate : 이 기울기 값(W_grad, b_grad)을 얼마만큼 반영할 것인지를 결정한다.

with ~ assign_sub 까지가 한 걸음이며, 이걸 반복하여 학습한다.

W = tf.Variable(2.9)
b = tf.Variable(0.5)

for i in range(100):
    # 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("Step: {:5}\tW: {:10.4f}\tb: {:10.4f}\tcost: {:10.6f}".format(
            i, W.numpy(), b.numpy(), cost.numpy()))

전체 코드

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

print("\n")
for i in range(100) :
    # 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("Step: {:5}\tW: {:10.4f}\tb: {:10.4f}\tcost: {:10.6f}".format(i, W.numpy(), b.numpy(), cost.numpy()))

출처: 모두를 위한 딥러닝 강좌 2
https://www.youtube.com/watch?v=7eldOrjQVi0&list=PLQ28Nx3M4Jrguyuwg4xe9d9t2XE639e5C

0개의 댓글