AI/모두를 위한 ML (SungKim)

[ML lab 04-2] TensorFlow로 파일에서 데이타 읽어오기

ferozsun 2021. 2. 17. 11:53

[Slicing examples]

b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# array([[1, 2, 3, 4],
#	 [5, 6, 7, 8],
#        [9, 10, 11, 12]])

b[:, 1]
# array([ 2,  6,  10])

b[-1]
# array([ 9, 10, 11, 12])

b[-1, :]
# array([ 9, 10, 11, 12])

b[-1, ...]
# array([ 9, 10, 11, 12])

b[0:2, :]
# array([[1, 2, 3, 4],
#	 [5, 6, 7, 8]])

[Loading data from file]

x_data와 y_data가 많아짐에 따라 소스코드에 전부 적는 것이 무리가 있다.

따라서 텍스트 파일(.csv)에 저장하고, 파일로부터 데이터를 읽어온다.

 

[data-01-test-score.csv]

73,80,75,152
93,88,93,185
89,91,90,180
96,98,100,196
73,66,70,142
53,46,55,101

[using numpy]

import numpy as np

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:\n", x_data.shape, "\n", x_data, "\n", len(x_data))
print("\ny_data:\n", y_data.shape, "\n", y_data)

 

np.loadtxt("파일경로", 파일에서 사용한 구분자, 데이터타입 지정)

 

[출력]


[numpy를 이용하는 방법]

import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

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

# Make sure the shpae and data are OK
#print("x_data:\n", x_data.shape, "\n", x_data, "\n", len(x_data))
#print("\ny_data:\n", y_data.shape, "\n", 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
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())

# Set up feed_dict variables inside the Loop
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]]}))

[출력]

. . .


[Queue Runner를 이용하는 방법]

파일이 너무 커서 메모리에 올리기도 어려운 경우 Queue Runner를 이용한다.

 

[step]

1. 읽을 파일들을 리스트에 넣어 큐를 만든다.

2. 파일들을 읽는 reader를 정의한다. (tf.TextLineReader() 이용)

3. 읽어온 value를 tf.decode_csv()를 통해 decode한다. (record_defaults 통해 type도 정할 수 있다.)

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

# 파일을 담은 queue를 만듦
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) # 10개씩 가져옴
# batch를 통해 값을 펌프해 옴

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

출력 결과는 numpy를 사용했을 때와 같다.