[ML] 2. Linear Regression의 Hypothesis 와 cost 설명

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


Linear Regression


  • Regression 을 학습한다는것은 :
    가설을 세울 필요가있다 => (Linear) Hypothesis
    H(x) = Wx + b
    가설   가중치  어떤값 이렇게 가설을 세운다




  • Which hypothesis is better ? :
    가장 기본적으로는 실제 데이터와 가설이 나타내는 데이터들과의 거리를 비교하는게 있음 이걸 Cost function
    -값이 있을수 있으니 (H(x) -y)^2를 취해줌 그래서 이 cost를 최소화 하는 W와 b를 찾으면 된다.



Tensor

  • 기본코드 "Linear"

    # Lab 2 Linear Regression
    import tensorflow as tf
    tf.set_random_seed(777)  # for reproducibility
    
    # X and Y data
    x_train = [1, 2, 3]
    y_train = [1, 2, 3]
    
    # Try to find values for W and b to compute y_data = x_data * W + b
    # We know that W should be 1 and b should be 0
    # 텐서플로우가 바꿀꺼라는말이다 
    W = tf.Variable(tf.random_normal([1]), name='weight')
    b = tf.Variable(tf.random_normal([1]), name='bias')
    
    # Our hypothesis XW+b
    hypothesis = x_train * W + b
    
    # cost/loss function
    cost = tf.reduce_mean(tf.square(hypothesis - y_train))
    # Minimize 함수 호출  
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
    train = optimizer.minimize(cost)
    # Launch the graph in a session.
    sess = tf.Session()
    # 변수만들면 초기화해야함
    sess.run(tf.global_variables_initializer())
    
    # Fit the line
    for step in range(2001):
        sess.run(train)
        if step % 20 == 0:
            print(step, sess.run(cost), sess.run(W), sess.run(b))
    

  • place holder사용 해서 구현

    # X and Y data
    X = tf.placeholder(tf.float32)
    Y = tf.placeholder(tf.float32)
    ...
    for step in range(2001):
     cost_val, W_val, b_val, _ = \
            sess.run([cost, W, b, train],
                     feed_dict={X: [1, 2, 3], Y: [1, 2, 3]})
        if step % 20 == 0:
            print(step, cost_val, W_val, b_val)
    


다음 포스팅

  • Linear Regression cost함수 최소화

No comments:

Post a Comment