출처 : 모두를위한 머신러닝 (http://hunkim.github.io/ml/)
Tensor Flow 에서 사용할 Data preprocessing 에 관하여 이론과 예제를 통해 설명한다.¶
Data Preprocessing (Normalization)¶
예를들어 2차원의 data 의 column 값들이 비슷한 경우, 다음과 같은 모양을 갖으며 minimum point를 찾을 수 있다.
그러나 만약 column 끼리의 값이 많이 차이나는 데이터일 경우 다음과 같이 한쪽으로만 치우친 그래프가 생성되고, 한쪽 축으로의 편차가 더 적기때문에 그 방향으로 움직이다가 튀는 경우가 발생한다.
따라서 차이가 큰 데이터들의 값을 비슷하게 맞춰주는 작업이 필요하다. 예를들면 다음과같은 작업들이 있다.
예제¶
아래 예제의 데이터에서 세번째 column 의 값이 유독 크다는것을 알 수 있다. 이런 상황에서의 data 를 Normalization 을 이용해 preprocessing 하는 방법을 알아본다.
In [3]:
import tensorflow as tf
import numpy as np
tf.set_random_seed(777) # for reproducibility
xy = np.array([[828.659973, 833.450012, 908100, 828.349976, 831.659973],
[823.02002, 828.070007, 1828100, 821.655029, 828.070007],
[819.929993, 824.400024, 1438100, 818.97998, 824.159973],
[816, 820.958984, 1008100, 815.48999, 819.23999],
[819.359985, 823, 1188100, 818.469971, 818.97998],
[819, 823, 1198100, 816, 820.450012],
[811.700012, 815.25, 1098100, 809.780029, 813.669983],
[809.51001, 816.659973, 1398100, 804.539978, 809.559998]])
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
# placeholders for a tensor that will be always fed.
X = tf.placeholder(tf.float32, shape=[None, 4])
Y = tf.placeholder(tf.float32, shape=[None, 1])
W = tf.Variable(tf.random_normal([4, 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(101):
cost_val, hy_val, _ = sess.run(
[cost, hypothesis, train], feed_dict={X: x_data, Y: y_data})
if step < 10 or step > 95:
print(step, "Cost: ", cost_val, "\nPrediction:\n", hy_val)
그 결과 Cost 값이 nan 으로 이상하게 학습된다.
Data Normalization using 'min-max scale'¶
min-max scale 방법을 이용하여 데이터를 normalization 시킨다. 그 결과, 원본 데이터와 다르게 데이터 간의 값 차이가 크지 않다.
In [4]:
import tensorflow as tf
import numpy as np
tf.set_random_seed(777) # for reproducibility
def MinMaxScaler(data):
numerator = data - np.min(data, 0)
denominator = np.max(data, 0) - np.min(data, 0)
# noise term prevents the zero division
return numerator / (denominator + 1e-7)
xy = np.array([[828.659973, 833.450012, 908100, 828.349976, 831.659973],
[823.02002, 828.070007, 1828100, 821.655029, 828.070007],
[819.929993, 824.400024, 1438100, 818.97998, 824.159973],
[816, 820.958984, 1008100, 815.48999, 819.23999],
[819.359985, 823, 1188100, 818.469971, 818.97998],
[819, 823, 1198100, 816, 820.450012],
[811.700012, 815.25, 1098100, 809.780029, 813.669983],
[809.51001, 816.659973, 1398100, 804.539978, 809.559998]])
xy = MinMaxScaler(xy)
print(xy)
In [6]:
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
# placeholders for a tensor that will be always fed.
X = tf.placeholder(tf.float32, shape=[None, 4])
Y = tf.placeholder(tf.float32, shape=[None, 1])
W = tf.Variable(tf.random_normal([4, 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(101):
cost_val, hy_val, _ = sess.run(
[cost, hypothesis, train], feed_dict={X: x_data, Y: y_data})
if step < 10 or step > 95:
print(step, "Cost: ", cost_val, "\nPrediction:\n", hy_val)
'Dev > 딥러닝' 카테고리의 다른 글
07-3. Tensor flow 에서 epoch 과 batch 설명 및 예제 (0) | 2018.08.23 |
---|---|
07-1. Tensor Flow 에서 Learning rate 이란 (0) | 2018.08.22 |
06-2. Tensorflow 에서 One hot 인코딩을 이용한 classification (0) | 2018.08.22 |
06-1. Tensor Flow 로 3종류 이상 Classfication (Soft max Classifier) (0) | 2018.08.20 |
05. Tensor Flow 로 Classification 예제 (binary) (0) | 2018.08.17 |
댓글