본문 바로가기
IT 기록/머신러닝

[머신러닝]04-3.TensorFlow로 파일에서 데이터 읽어 오기

by Lazy Quant 2018. 7. 24.
반응형

※본 포스팅은 직접 강의하는 내용이 아닌, 김성훈 교수님의 머신러닝 강의를 정리하기 위한 포스팅입니다.

김성훈 교수님의 강의는 모두를 위한 머신러닝/딥러닝(http://hunkim.github.io/ml)에서 들을 수 있습니다.


 지난 강의에서 여러 개의 입력 값이 있을 때 Linear Regression을 Tensorflow로 구현하는 방법을 공부했다. 입력 데이터가 많아지니, 소스 코드에 직접 써서 학습하기가 어렵다. 1,000개, 10,000개가 넘어가면 사실상 불가능해진다. 그래서 데이터를 텍스트로 정리를 한다. 보통 csv 파일을 많이 사용한다.


참고) CSV(comma-separated values)는 몇 가지 필드를 쉼표(,)로 구분한 텍스트 데이터 및 텍스트 파일이다. 확장자는 .csv 


4-3.Numpy를 이용한 데이터 로드

이런 데이터 파일을 읽어오는 여러 방법이 있지만, 가장 간편한 방법은 numpy loadtxt를 사용하는 것

# Lab 4 Multi-variable linear regression
import tensorflow as tf
import numpy as np
tf.set_random_seed(777)  # for reproducibility

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

# Make sure the shape and data are OK
print(x_data.shape, x_data, len(x_data))
print(y_data.shape, y_data)

# placeholders for a tensor that will be always fed.
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
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)

# Launch the graph in a session.
sess = tf.Session()
# Initializes global variables in the graph.
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)

# Ask my score
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]]}))

참고) Numpy : Numpy는 C언어로 구현된 파이썬 라이브러리로써, 고성능의 수치계산을 위해 제작되었다. Numerical Python의 줄임말이기도 한 Numpy는 벡터 및 행렬 연산에 있어서 매우 편리한 기능을 제공한.

참고) np.loadtxt : 텍스트 파일로부터 배열 로딩

np.loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0)

  • fname: 파일명
  • dtype: 데이터 타입
  • comments: comment 시작 부호
  • delimiter: 구분자
  • skiprows: 제외 라인 수(header 제거용)


참고) 파이썬의 slicing

xy[:, 0:-1] : 전체 n행을 다 가져오고, 마지막 열을 제외한 모든 열을 가져온다

xy[:, [-1]] : 전체 n행을 다 가져오고, 마지막 열 가져온다.




4-4.Numpy를 이용한 데이터 로드

 파일이 너무 커서 메모리에 한 번에 올리기도 힘들 때가 있다. 텐서플로우에는 Queue Runnuers라는 것이 구축되어 있다. 여러 개의 파일에서 데이터를 읽어와서 Filename Queue에 쌓아놓고, reader가 읽어서 Example Queue에 쌓는다. Example Queue에서 배치로 가져와서 사용한다. 메모리 관리에 유용
# Lab 4 Multi-variable linear regression
# https://www.tensorflow.org/programmers_guide/reading_data

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

filename_queue = tf.train.string_input_producer(
    ['data-01-test-score.csv'], shuffle=False, name='filename_queue')

reader = tf.TextLineReader()
key, value = reader.read(filename_queue)

# Default values, in case of empty columns. Also specifies the type of the
# decoded result.
record_defaults = [[0.], [0.], [0.], [0.]]
xy = tf.decode_csv(value, record_defaults=record_defaults)

# collect batches of csv in
train_x_batch, train_y_batch = \
    tf.train.batch([xy[0:-1], xy[-1:]], batch_size=10)

# placeholders for a tensor that will be always fed.
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
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)

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

# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)

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

coord.request_stop()
coord.join(threads)

# Ask my score
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]]}))


반응형

댓글