DeepLearning_Lab02 - 8BitsCoding/RobotMentor GitHub Wiki


Example

기본적 import

# Lab 2 Linear Regression
import tensorflow as tf
tf.set_random_seed(777)  # for reproducibility

tf.set_random_seed(777) # for reproducibility는 아직 뭔지 모름 일단 무시

# X and Y data
x_train = [1, 2, 3]
y_train = [1, 2, 3]

간단한 x, y값을 주어지고

주어진 x, y데이터에 따른 W, b(Weight, bias)를 찾아보자.

이미지

# 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
# But let TensorFlow figure it out
W = tf.Variable(tf.random_normal([1]), name="weight")
b = tf.Variable(tf.random_normal([1]), name="bias")

tf.Variable에서 말하는 variable은 tensorflow가 사용하는 variable을 의미 tensorflow가 값을 바꿔가며 사용할 값임. (tranninable varible이라고도 한다.)

W = tf.Variable(tf.random_normal([1]), name="weight") 해석 :

W라는 tensor를 Variable(tensorflow가 변경가능한 값)으로 두고 random_normal를 넣는데 shape은 [1]이다

# Our hypothesis XW+b
hypothesis = x_train * W + b

가설은 위와같이 정의 할 수 있고

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

함수는 위와 같이 정의 할 수 있다.

이미지

tf.reduce_mean는 평균을 만들어주는 것을 의미

# optimizer
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)

GradientDescentOptimizer를 통하여 cost(lost)를 minimize한다.

minimize는 어떻게 하는데?? -> 지금은 tensorflow가 해주는 매직이라 생각

# Launch the graph in a session.
with tf.Session() as sess:
    # Initializes global variables in the graph.
    sess.run(tf.global_variables_initializer())

세션을 생성 후 with tf.Session() as sess:

W, b라는 tensorflow의 variable을 사용하기 위해선 sess.run(tf.global_variables_initializer())를 호출해 주어야한다.

    # Fit the line
    for step in range(2001):
        _, cost_val, W_val, b_val = sess.run([train, cost, W, b])

        # 2001번 도는데 20번에 한 번씩 출력해줘
        if step % 20 == 0:
            print(step, cost_val, W_val, b_val)

해보자!

이미지

파이참에서 Ctrl+Shift+F10