본문 바로가기
머신러닝과 딥러닝/실습

TensorFlow로 Multi-variable Linear Regression 실습

by Bentist 2020. 2. 11.
import tensorflow as tf
import matplotlib.pyplot as plt

# 선형 회귀를 위해서 텐서 플로우 1의 코드 실행을 위한 임포트
# 현재는 텐서 플로우 2로 선형 회귀를 훨씬 간단하게 구현할 수 있다.
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
# H(x1, x2, x3) = x1w1 + x2w2 + x3w3
#x1, x2, x3은 feature들

x1_data = [73, 93, 89, 96, 73] 
x2_data = [80, 88, 91, 98, 66]
x3_data = [75, 93, 90, 100, 70]
y_data = [152, 185, 180, 196, 142]

x1 = tf.placeholder(tf.float32)
x2 = tf.placeholder(tf.float32)
x3 = tf.placeholder(tf.float32)

Y = tf.placeholder(tf.float32)

w1 = tf.Variable(tf.random_normal([1]), name='weight1')
w2 = tf.Variable(tf.random_normal([1]), name='weight2')
w3 = tf.Variable(tf.random_normal([1]), name='weight3')
b = tf.Variable(tf.random_normal([1]), name='bias')

# Y = x1*w1 + x2*w2 + x3*w3 + b
hypothesis = x1*w1 + x2*w2 + x3*w3 + b

# cost function
cost = tf.reduce_mean(tf.square(hypothesis - Y))

# Minimize. Need a very small learning rate for this data set
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)
train = optimizer.minimize(cost)

sess = tf.Session()
sess.run(tf.global_variables_initializer())

for step in range(2001):
    cost_val, hy_val, _ = sess.run([cost, hypothesis, train],
                                  feed_dict={x1: x1_data, x2: x2_data, x3: x3_data, Y: y_data})
    if step % 100 == 0:
        print(step, "Cost:", cost_val, "\nPrediction:\n", hy_val)        

# Matrix 개념 활용, H(X) = XW

이제 앞서 배운 Matrix 개념을 사용하게 되면 더 간단하게 구현할 수 있다.

x_data = [[73, 80, 75],[93, 88, 93], 
          [85, 91, 90],[96, 98, 100],[73, 66, 70]]
y_data = [[152],[185],[180],[196],[142]]

X = tf.placeholder(tf.float32, shape=[None, 3])
Y = tf.placeholder(tf.float32, shape=[None, 1])

W = tf.Variable(tf.random_normal([3,1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')

hypothesis = tf.matmul(X, W) + b

cost = tf.reduce_mean(tf.square(hypothesis - Y))

# Minimize. Need a very small learning rate for this data set
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)
train = optimizer.minimize(cost)

# launch the graph in a session.
sess = tf.Session()
sess.run(tf.global_variables_initializer())

for step in range(2001):
    cost_val, hy_val, _ = sess.run([cost, hypothesis, train],
                                  feed_dict={X: x_data, Y: y_data})
    if step % 100 == 0:
        print(step, "Cost:", cost_val, "\nPrediction:\n", hy_val)   

shape = [None, 3]에서 None값은 x_data 샘플로 n개, 혹은 개수와 상관없이 여러개를 가질 것이라는 의미이다.

그리고 x의 feature는 3개이다.

y_data를 보면 x_data의 샘플 개수인 n개 데이터가 각각 하나의 출력값으로 예측되기 때문에 shape = [None, 1]이다. 

 

댓글