[ML] 3. Linear Regression cost함수 최소화

김성 교수의 '모두를 위한 머신러닝/딥러닝' 정리


Linear Regression cost함수 최소화


  • Linear Regression 목표:
    가설의 cost function을 최소화 하는 W,B값을 찾아나가는거
  • Gradient descent algorithm (경사를 따라 내려가는 알고리즘) :
    • minimize cost function 
    • it can be applied to more general function : cost(w1,w2)....여러개도 가능
    • How it works? 경사도를 따라가다가 가장 아랫점을 찾는다 생각하면 편함



Tensor

  • gradient의 경사측 코드


    이렇게 간단한 코드로도 구현 가능 + 추가적으로 optimizer.apply_gradients로
    gradient의 minimize의 부분을 수정 가능
  • 전체코드

    # Lab 3 Minimizing Cost
    import tensorflow as tf
    tf.set_random_seed(777)  # for reproducibility
    
    x_data = [1, 2, 3]
    y_data = [1, 2, 3]
    
    # Try to find values for W and b to compute y_data = W * x_data + b
    # We know that W should be 1 and b should be 0
    # But let's use TensorFlow to figure it out
    W = tf.Variable(tf.random_normal([1]), name='weight')
    
    X = tf.placeholder(tf.float32)
    Y = tf.placeholder(tf.float32)
    
    # Our hypothesis for linear model X * W
    hypothesis = X * W
    
    # cost/loss function
    cost = tf.reduce_mean(tf.square(hypothesis - Y))
    
    # Minimize: Gradient Descent using derivative: W -= learning_rate * derivative
    learning_rate = 0.1
    gradient = tf.reduce_mean((W * X - Y) * X)
    descent = W - learning_rate * gradient
    update = W.assign(descent)
    
    # Launch the graph in a session.
    sess = tf.Session()
    # Initializes global variables in the graph.
    sess.run(tf.global_variables_initializer())
    
    for step in range(21):
        sess.run(update, feed_dict={X: x_data, Y: y_data})
        print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}), sess.run(W))
    


다음 포스팅

  • 여러개의 입력(feature)의 Linear Regression

No comments:

Post a Comment