728x90
728x170

1. 파일에서 학습할 데이터를 가져옵니다.

2017/10/25 - [TensorFlow&Python] - (TensorFlow) 파일에서 (학습할)데이터 읽어오기

import numpy as np
import tensorflow as tf

xy = np.loadtxt('testData.csv',delimiter=',',dtype=np.float32)
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]

print(x_data.shape, x_data, len(x_data))
print(y_data.shape, y_data, len(y_data))

 

2. Node 를 구성합니다. (학습할 데이터의 구성을 정의합니다.)

// n 개의 3가지 숫자값을 가지는 구성의 x
X = tf.placeholder(tf.float32, shape=[None, 3])
// 1 개의 결과 숫자값을 가지는 구성의 y
Y = tf.placeholder(tf.float32, shape=[None, 1])

// 3개가 들어가서 1개의 결과로 나온다.
W = tf.Variable(tf.random_normal([3, 1]), name='weight')
// 1개의 출력값을 갖는다.
b = tf.Variable(tf.random_normal([1]), name='bias')

 

3. 학습을 어떻게 할것인지 정의합니다.

// 가설을 세우고
hypothesis = tf.matmul(X, W) + b
// 비용을 계산
cost = tf.reduce_mean(tf.square(hypothesis - Y))

// optimizer를 생성하여 비용(cost) 이 적은 방향으로 학습시키도록 정의
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)
train = optimizer.minimize(cost)

 

4. 학습합니다.

// session 을 가져와 변수 초기화
sess = tf.Session()
sess.run(tf.global_variables_initializer())

// 2001 번 루프 돌면서 학습을 시킵니다.
// feed_dict 에 학습된 결과가 저장됩니다.
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)

 

5. 학습한결과로 예측해봅니다.

// 학습한 내용을 가지고 결과를 예측해봅니다. (100,70,101) 인 경우 결과를 예측합니다.
print("Your score will be ", sess.run(
    hypothesis, feed_dict={X: [[100, 70, 101]]}))

Your score will be [[ 170.03196716]]

// [60, 70, 110], [90, 100, 80] 에대한 결과를 예측해 봅니다. 2가지 조건을 넣었으므로 두가지 예측 결과가 나타납니다.
print("Other scores will be ", sess.run(hypothesis,
                                        feed_dict={X: [[60, 70, 110], [90, 100, 80]]}))

Other scores will be  [[ 149.67153931]
 [ 188.85415649]]

 

 

 

 

전체코드
import numpy as np
import tensorflow as tf

xy = np.loadtxt('testData.csv',delimiter=',',dtype=np.float32)
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]] 

print(x_data.shape, x_data, len(x_data))
print(y_data.shape, y_data, len(y_data))

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

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={X: x_data, Y: y_data})
    if step % 10 == 0:
        print(step, "Cost: ", cost_val, "\nPrediction:\n", hy_val)

print("Your score will be ", sess.run(hypothesis, feed_dict={X: [[100, 70, 101]]}))

print("Other scores will be ", sess.run(hypothesis,feed_dict={X: [[60, 70, 110], [90, 100, 80]]}))

 

 

 

728x90
그리드형
Posted by kjun
,