multi _variable 선형회귀_코드 분석

2020. 8. 7. 10:42딥러닝

lab-04-2-multi_variable_matmul_linear_regression.py
0.00MB


import tensorflow as tf
tf.set_random_seed(777)  # for reproducibility

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


matrix(행렬)을 이용해서 보다 쉽게 주어진 데이터들을 쓸 수 있다.

 

 

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')

tf.placeholder을 이용해서 텐서를 만들어준다. 이때 행렬을 이용했으므로 shape가 중요한데 none은 인스턴스의 개수를 의미한다. (none을 사용한것은 instance의 개수를 정하지 않고 맘대로 쓰기 위함)

숫자(3)이 의미하는것은 variable의 개수가 3개임을 의미한다. 즉 multil_variable이다.

 

정해지지 않은 웨이트와 바이어스의 변수 설정은 tf.Variable을 이용한다. (이때 주의 할 점은 tf.Variable을 사용 했으면sess.run(tf.global_variables_initializer())을 코드에 넣어줘야한다. 이것을 넣어줘야 변수가 텐서플로우 그래프 안에서 텐서가 만들어진다.)

 

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

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

# Minimize
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)
train = optimizer.minimize(cost)

hypothesis(가설)을 만들어준다. 이떄에 곱해지는 X와 W는 행렬이다.

tf.square는 제곱을 의미한다.

tf.reduce_mean은 최소값을 의미한다. , 즉 이 두 메소드를 통해서 cost를 정의 해주었다

 

학습을 위해 optimizer와 train을 준비한다.

 

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

학습을 시작해보자

range는 총 갯수를 의미한다. for문을 이용해서 반복시켜 준다.

 

cost_var, hy_val로 다시 정의 해준 이유는 그래프를 실행 한 후에 나오 나온값을 쓰기 위해서이다.

'딥러닝' 카테고리의 다른 글

Classification  (0) 2020.08.10
선형 회귀 -간단 정리  (0) 2020.08.07
텐서플로우 변수 placd holder  (0) 2020.08.07
기본적으로 알아야 할 Tensorflow(텐서플로)의 기본  (0) 2020.08.06
Linear regression(선형 회귀)  (0) 2020.08.05