Neural Networks in XOR problem


본 장에서는 Neural network을 약 20년간 암흑기에 빠지게한 
XOR문제에 대해서 다뤄 보겠다.

우선 직관적으로 Hiddlen Layer를 통해서 XOR 문제를 해결 하는 방법을 알아보고
두 번째로 Backpropagation Algorithm을 이용해서 기계적으로 학습을 통해서 Weight 값을 알아내는 방법을 알아본다.
마지막으로 TensorFlow를 통해서 이를 각각 구현해 보도록 한다.

XOR using NN

아래와 같은 문제가 있다고 하자.

아래와 같은 weight들로 구성 되어져 있다고 가정 하자. 

이것을 각각 계산하면 아래와 같다.

좀 더 정리하면 아래와 같은 모습이 된다.

생각해 볼것은 여기서 주어진 wegiht들 이외에 XOR 문제를 풀수 있는 새로운 W와 b를 찾을 수 있을까?

그리고 Vectorazation을 이용해서 좀 더 간소화 시킬 수 도 있다.

이것을 TensorFlow로 구현 하면 아래와 같다.

# Our hypothesis
K = tf.sigmoid(tf.matmul(X, W1) + b1)
hypothesis = tf.sigmoid(tf.matmul(K, W2) + b2)

Backpropagation

MIT AI Lab의 창시자 Marvin Minsky가 말했던

No one on earth had found a viable way to train MLPs good enough to learn such simple functions.

Forwarding 방식으로는 Derivation을 계산하기가 너무 어렵다.
따라서 제안된 방식이 Backpropagation이다.

기본적으로 Back propagation은 미분학의 chain rule을 사용하는 방식이다.
여기서 chain rule이란 아래의 미분 공식을 말한다.
함수 $f(g(x))$의 미분값은 아래의 방식으로 계산 할 수 있다.
$$\frac{\partial f}{\partial x}=\frac{\partial f}{\partial g}\frac{\partial g}{\partial x}$$

이제 아래와 같은 간단한 함수를 생각해 보자.
$$f=Wx+b, g=Wx, f=g+b$$
그리고 이것을 chain rule을 통해서 모두 계산 할 수 있게 된다. 즉 결과 f에 미치는 각각의 term들의 영향을 계산할 수 있는 것이다.

  • forward (w=-2, x=5, b=3)
  • backward

이제 각각의 계산하면
w = -2
x = 5
b = 3
g = -10
f = -7

그리고 계산의 편의를 위해서 각각의 partial derivative를 모두 계산해 보자.

$$\frac{\partial g}{\partial w}=x$$
$$\frac{\partial g}{\partial x}=w$$
$$\frac{\partial f}{\partial g}=1$$
$$\frac{\partial f}{\partial b}=1$$

이제 편미분 값을 이용해서 f에 미치는 영향을 각각 계산하면 아래와 같다.

위 값을 해석해보면 결국 1이라는 것은 1:1 영향 관계를 나타내고
5는 5배 만큼 영향을 미친다는 것이다.
즉 b=3에서 b=4로 증가시킬 경우 f의 값은 -6이 된다. 즉 1만큼 차이가 생긴다.
반대로 w를 -3으로 변경 시키면 f는 -12되므로 -5만큼 값이 증가하게 된다. 5배의 영향을 미치는 것을 알 수 있다.

이러한 방법을 이용해서 아무리 복잡해서 모두 계산 할 수 있다.

Neural network implementation

How can we learn W1, W2, B1, B2 from training data ?

구현 방법에 대해서 알아 보겠다.
지난번 logistic regression code에서 약간만 더 수정하면 된다.

아래의 코드는 아래의 그림을 표현한 것이다.

W1 = tf.Variable(tf.random_uniform([2, 2], -1.0, 1.0))
W2 = tf.Variable(tf.random_uniform([2, 1], -1.0, 1.0))

b1 = tf.Variable(tf.zeros([2]), name="Bias1")
b2 = tf.Variable(tf.zeros([1]), name="Bias1")


# Our hypothesis
L2 = tf.sigmoid(tf.matmul(X, W1) + b1)
hypothesis = tf.sigmoid(tf.matmul(L2, W2) + b2)

위와 같이 구현하면 쉽게 두개의 layer가 존재하는 neural network을 구성한 것이 된다.

전체소스코드는 아래와 같다.
기본적으로 변경된 것은 아래와 같다.

1) hypothesis를 위와 같이 변경 했다.

2) 입력 데이터 형테를 변경 했다.
변경전 
[[ 0, 0, 1, 1],
[ 0, 1, 0, 1]]
변경후
[[0, 0],
[0, 1],
[1, 0],
[1, 1]]

3) Learning rate과 interation을 조정했다. converge하는데 시간이 너무 오래 걸린다.

import tensorflow as tf
import numpy as np

xy = np.loadtxt('train.txt', unpack=True)

#x_data = xy[0:-1]
x_data = np.transpose(xy[0:-1])
#y_data = xy[-1]
y_data = np.reshape(xy[-1], (4, 1))

X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)

W1 = tf.Variable(tf.random_uniform([2, 2], -1.0, 1.0))
W2 = tf.Variable(tf.random_uniform([2, 1], -1.0, 1.0))

b1 = tf.Variable(tf.zeros([2]), name="Bias1")
b2 = tf.Variable(tf.zeros([1]), name="Bias1")


# Our hypothesis
L2 = tf.sigmoid(tf.matmul(X, W1) + b1)
hypothesis = tf.sigmoid(tf.matmul(L2, W2) + b2)

# Cost function
cost = -tf.reduce_mean(Y*tf.log(hypothesis) + (1-Y)*tf.log(1-hypothesis))

# Minimize
a = tf.Variable(0.1) # Learning rate, alpha
optimizer = tf.train.GradientDescentOptimizer(a)
train = optimizer.minimize(cost)

# Before starting, initialize the variables. We will `run` this first.
init = tf.initialize_all_variables()

# Launch the graph,
with tf.Session() as sess:
    sess.run(init)

    # Fit the line.
    for step in xrange(10000):
        sess.run(train, feed_dict={X:x_data, Y:y_data})
        if step % 200 == 0:
            print step, sess.run(cost, feed_dict={X:x_data, Y:y_data}), sess.run(W1), sess.run(W2)

    # Test model
    correct_prediction = tf.equal(tf.floor(hypothesis+0.5), Y)
    # Calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print sess.run([hypothesis, tf.floor(hypothesis+0.5), correct_prediction, accuracy], feed_dict={X:x_data, Y:y_data})
    print "Accuracy:", accuracy.eval({X:x_data, Y:y_data})

재치환 오류 계산 코드 설명

# Test model
correct_prediction = tf.equal(tf.floor(hypothesis+0.5), Y)
# Calculate accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print sess.run([hypothesis, tf.floor(hypothesis+0.5), correct_prediction, accuracy], feed_dict={X:x_data, Y:y_data})
print "Accuracy:", accuracy.eval({X:x_data, Y:y_data})

tf.floor(hypothesis+0.5)는 0~1 사이의 값을 나오게 한다.
그리고 Y의 실제 값과 비교를 한다.
이러한 기능을 하는 함수 correct_prediction를 디자인 한것이다.

accuracy는 평균을 구하는 것이다.

[hypothesis, tf.floor(hypothesis+0.5), correct_prediction, accuracy], 
feed_dict={X:x_data_testing, Y:y_data_testing}

print "Accuracy:", accuracy.eval({X:x_data_testing, Y:y_data_testing})

실행결과

9800 0.0402879 [[-6.13605404 -4.11170053]
 [-6.11376047 -4.1088109 ]] [[-8.83549595]
 [ 8.12334061]]
[array([[ 0.02604489],
       [ 0.96690428],
       [ 0.96695912],
       [ 0.05478531]], dtype=float32), array([[ 0.],
       [ 1.],
       [ 1.],
       [ 0.]], dtype=float32), array([[ True],
       [ True],
       [ True],
       [ True]], dtype=bool), 1.0]
Accuracy: 1.0

cost가 0.04로 0에 근접하는 것을 알 수 있다.


'AI > TensorFlow, PyTorch, Keras, Scikit' 카테고리의 다른 글

Naive Bayes vs Neural network  (2) 2016.04.25
Softmax Function  (0) 2016.04.19
Logistic Regression  (0) 2016.04.17
Linear regression with TensorFlow  (0) 2016.04.17
TensorFlow 개발환경 ( Eclipse + PyDev, Pycharm, Jupyter)  (0) 2015.11.17

Logistic Regression


Logistic Regression의 기본 개념

Linear regression 방식은 0.5를 기점으로 1과 0을 만들기가 어렵다.
즉 학습 데이터에 너무 기울기가 민감하다는 점이다.

그래서 나온것이 logistic 함수이다.

Logistic Hypothesis
$$H(X) = \frac{1}{1+e^{-W^{T}X}} $$

Cost function을 
위의 Hoypothesis를 바로 이용해서 구하게 되면
구불 구불한 graph가 형셩되어 local minimum에 도달하는 문제가 발생 한다.

New cost function for logistic

그래서 새로 나온 cost 함수는 아래와 같다.

갑자기 log를 하는 이유는 exponential이 결국 cost 함수를 구불구불 하게 만들기 때문에 이러한 특성을 제거해 주기 위해서
log를 취하게 된다.

Logistic은 0~1 사이의 값이므로
g(z) = -log(z)를 생각해보면 결국 z가 1이면 0인 그래프가 생성된다.

cost함수의 정의는 결국 예측값이랑 실제값이랑 같으면 cost가 0이고
틀리면 패널티를 주는 것이 철학이다.

위함수 대로 cost를 계산해보면
H(x) = 1 -> cost(1) = 0 
H(x) = 0 -> cost(0) = infinite

반대로 y=0일때를 계산해 보면
H(x) = 0, cost = 0
H(x) = 1, cost = infinite

결국 우리가 목표로하는 cost 함수가 잘 만들어진것을 알 수 있다.
그리고 아래의 그래프를 보면 bowl 모양으로 local minimum이 없는 gradient decesent하기 좋은 graph shape인 것을 알 수 있다.
이러한 것을 convexity가 아주 좋다고 한다.

이것을 If조건 없이 간소화하면 아래와 같은 수식이 된다.
$$ C(H(x),y) = -y\log{(H(x))}+(1-y)\log{(1-H(x))}$$

Minimum cost, Gradient decent algorithm

이제 간소화된 hypothesis를 이용해서 cost function을 아래와 같이 생성한다.
$$ cost(W) = -\frac{1}{m}\sum{y\log{(H(x))}+(1-y)\log{(1-H(x))}}$$

그리고 이것을 partial derivative해서 gradient descent algorithm을 수행 한다.
derivative를 하는 것은 복잡하므로 그냥 그렇게 한다고만 생각하자.
컴퓨터가 자동으로 계산해 줄 것이다.

$$ W:=W-\alpha\frac{\partial}{\partial W}cost(W)$$

Logistic regression의 Cost function을 최적화 하는 코드는 아래와 같다.
아래의 GradientDescentOPtimizer함수가 tensorflow에 구현되어 있으니 이것을 그냥 사용하면 된다.

# Cost function
cost = -tf.reduce_mean(Y*tf.log(hypothesis) + (1-Y)*tf.log(1-hypothesis))

# Minimize
a = tf.Variable(0.1) # Learning rate, alpha
optimizer = tf.train.GradientDescentOptimizer(a)
train = optimizer.minimize(cost)

Logistic Regression Basic Implementation

간단한 Logistic Regression을 이용한 코드는 아래와 같다.

Training Data

#x0 x1 x2 y
1 2 1 0
1 3 2 0
1 3 4 0
1 5 5 1
1 7 5 1
1 2 5 1

Code

import tensorflow as tf
import numpy as np

xy = np.loadtxt('logisticTrain.txt', unpack=True, dtype='float32')

x_data = xy[0:-1]
y_data = xy[-1]

X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)

W = tf.Variable(tf.random_uniform([1,len(x_data)],-1.0, 1.0))

# Our hypothesis
h = tf.matmul(W, X)
hypothesis = tf.div(1., 1+tf.exp(-h))

# Cost function
cost = -tf.reduce_mean(Y*tf.log(hypothesis) + (1-Y)*tf.log(1-hypothesis))

# Minimize
a = tf.Variable(0.1) # Learning rate, alpha
optimizer = tf.train.GradientDescentOptimizer(a)
train = optimizer.minimize(cost)

# Before starting, initialize the variables. We will `run` this first.
init = tf.initialize_all_variables()

# Launch the graph.
with tf.Session() as sess:
    sess.run(init)

    # Fit the line.
    for step in xrange(2000):
        sess.run(train, feed_dict={X:x_data, Y:y_data})
        if step % 200 == 0:
            print step, sess.run(cost, feed_dict={X:x_data, Y:y_data}), sess.run(W)

    # Test model: re-substitution error
    correct_prediction = tf.equal(tf.floor(hypothesis+0.5), Y)
    # Calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print sess.run([hypothesis, tf.floor(hypothesis+0.5), correct_prediction, accuracy], feed_dict={X:x_data, Y:y_data})
    print "Accuracy:", accuracy.eval({X:x_data, Y:y_data})

    print '----------------------------------------'
    # study hour attendance
    # unseen data, but we don't know exact answer
    print sess.run(hypothesis, feed_dict={X:[[1], [2], [2]]}) > 0.5
    print sess.run(hypothesis, feed_dict={X:[[1], [5], [5]]}) > 0.5

    print sess.run(hypothesis, feed_dict={X:[[1, 1], [4, 3], [3, 5]]}) > 0.5

Result

1200 0.217096 [[-6.07444096  0.19686432  1.39010859]]
1400 0.205831 [[-6.5395813   0.2086037   1.48329437]]
1600 0.196362 [[-6.96585989  0.21742623  1.57006204]]
1800 0.188185 [[-7.36184502  0.22416407  1.65168989]]
[array([[ 0.00389449,  0.02695587,  0.46784386,  0.88681448,  0.92534608,
         0.79747105]], dtype=float32), array([[ 0.,  0.,  0.,  1.,  1.,  1.]], dtype=float32), array([[ True,  True,  True,  True,  True,  True]], dtype=bool), 1.0]
Accuracy: 1.0
----------------------------------------
[[False]]
[[ True]]
[[False  True]]

재치환 오류의 경우 0로 정확도가 1이 나온다.
그리고 2,2 5,5에 대해서는 False와 True가 나온다.
이것은 test data set을 임의로 만든 것이기 때문에 딱히 의미는 없다.
대략 생성된 모델로 저렇게 예측한 다는것을 보여주기 위함이다.

XOR with Logistic Regression

train.txt 데이터는 아래와 같다.
아무 편집기로나 하나 만들어 주면 된다.

import tensorflow as tf
import numpy as np

xy = np.loadtxt('train.txt', unpack=True)

x_data = xy[0:-1]
y_data = xy[-1]

X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)

W = tf.Variable(tf.random_uniform([1,len(x_data)],-1.0, 1.0))

# Our hypothesis
h = tf.matmul(W, X)
hypothesis = tf.div(1., 1+tf.exp(-h))

# Cost function
cost = -tf.reduce_mean(Y*tf.log(hypothesis) + (1-Y)*tf.log(1-hypothesis))

# Minimize
a = tf.Variable(0.01) # Learning rate, alpha
optimizer = tf.train.GradientDescentOptimizer(a)
train = optimizer.minimize(cost)

# Before starting, initialize the variables. We will `run` this first.
init = tf.initialize_all_variables()

# Launch the graph,
with tf.Session() as sess:
    sess.run(init)

    # Fit the line.
    for step in xrange(1000):
        sess.run(train, feed_dict={X:x_data, Y:y_data})
        if step % 200 == 0:
            print step, sess.run(cost, feed_dict={X:x_data, Y:y_data}), sess.run(W)

    # Test model
    correct_prediction = tf.equal(tf.floor(hypothesis+0.5), Y)
    # Calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print sess.run([hypothesis, tf.floor(hypothesis+0.5), correct_prediction, accuracy], feed_dict={X:x_data, Y:y_data})
    print "Accuracy:", accuracy.eval({X:x_data, Y:y_data})

1) 200번 마다 print를 통해서 값을 출력하게 된다.
step, cost, W(wegiht) 이 세개의 값이다.

2) test model에서
hypothesis는 0~1사이의 값을 가진다. 
이것에 floor를 취하게 되면, element wise the largest value가 리턴 되어 지므로 0.5를 기준으로 0~1이 잘 반환 된다.
이것과 실제 Y값을 비교함으로써 accuracy를 측정 하게 된다.
마지막으로는 최종적으로 평균을 구하게 된다.

결과

/root/tensorflow/bin/python /root/PycharmProjects/TensorFlowTest/XORwithLogisticRegression.py
I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 8
I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 8
0 0.74015 [[ 0.71727103 -0.98306912]]
200 0.729532 [[ 0.66214472 -0.84831709]]
400 0.721451 [[ 0.60500312 -0.73486906]]
600 0.715226 [[ 0.54846114 -0.63875955]]
800 0.710393 [[ 0.49420556 -0.55683309]]
[array([[ 0.5       ,  0.38061982,  0.60909009,  0.48914438]], dtype=float32), array([[ 1.,  0.,  1.,  0.]], dtype=float32), array([[False, False,  True,  True]], dtype=bool), 0.5]
Accuracy: 0.5

Process finished with exit code 0

위와 같이 Logistic Regression 방법으로는 0.5의 정확도 밖에 얻을 수 없는것을 알 수 있다.

제대로 동작 하지 않는다.


Linear regression with TensorFlow

Placeholder

foo(a,b){ .. }

실행하는 시점에서 아래와 같이 값을 결정하게 할 수 있다.

a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)

# Define some operations
add = tf.add(a, b)
mul = tf.mul(a, b)

with tf.Session() as sess:
    print "Addition with variables: %i" % sess.run(add, feed_dict={a:2, b:3})
    print "Multiplication with variables: %d" % sess.run(mul, feed_dict={a:2, b:3})
Addition with variables: 5
Multiplication with variables: 6

Linear regression

H(x) = Wx +b

$$cost(H(x)) = \frac{1}{m} \sum_{i=1}^{m}{(H(x^{(i)})-y^{(i)})^2}$$

Variable로 지정해야 tensorflow가 update를 할 수 있게 된다.

import tensorflow as tf

x_data = [1,2,3]
y_data = [1,2,3]

# Try to find values for W and b taht compute y_data = W * x_data + b
# (We know that W should be 1 and b 0, but Tensorflow will figure that out for us.)

W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.random_uniform([1], -1.0, 1.0))

# Our hypothesis
hypothesis = W * x_data + b

# Simplified cost function
cost = tf.reduce_mean(tf.square(hypothesis-y_data))

# Minimize
a = tf.Variable(0.1) # Learning rate, alpha
optimizer = tf.train.GradientDescentOptimizer(a)
train = optimizer.minimize(cost)

# Before starting, initialize the variables.
# We are going to run this first.
init = tf.initialize_all_variables()

# Launch the graph
sess = tf.Session()
sess.run(init)

# Fit the line.
for step in xrange(2001):
    sess.run(train)
    if step % 100 == 0 :
        print step, sess.run(cost), sess.run(W), sess.run(b)

result

0 0.0695987 [ 1.0891968] [ 0.07517025]
100 1.00123e-06 [ 0.99883789] [ 0.00264173]
200 7.70968e-09 [ 0.99989802] [ 0.0002318]
300 5.84587e-11 [ 0.99999106] [  2.03111595e-05]
400 4.73695e-13 [ 0.99999917] [  1.74629804e-06]
500 4.73695e-15 [ 0.99999994] [  1.88630892e-07]
600 0.0 [ 1.] [  5.35269820e-08]
700 0.0 [ 1.] [  5.35269820e-08]
800 0.0 [ 1.] [  5.35269820e-08]
900 0.0 [ 1.] [  5.35269820e-08]
1000 0.0 [ 1.] [  5.35269820e-08]
1100 0.0 [ 1.] [  5.35269820e-08]
1200 0.0 [ 1.] [  5.35269820e-08]
1300 0.0 [ 1.] [  5.35269820e-08]
1400 0.0 [ 1.] [  5.35269820e-08]
1500 0.0 [ 1.] [  5.35269820e-08]
1600 0.0 [ 1.] [  5.35269820e-08]
1700 0.0 [ 1.] [  5.35269820e-08]
1800 0.0 [ 1.] [  5.35269820e-08]
1900 0.0 [ 1.] [  5.35269820e-08]
2000 0.0 [ 1.] [  5.35269820e-08]

with placeholder.
reuse가 가능하다.

import tensorflow as tf

x_data = [1,2,3]
y_data = [1,2,3]

# Try to find values for W and b taht compute y_data = W * x_data + b
# (We know that W should be 1 and b 0, but Tensorflow will figure that out for us.)

W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.random_uniform([1], -1.0, 1.0))

# with placeholder
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)


# Our hypothesis
hypothesis = W * X + b

# Simplified cost function
cost = tf.reduce_mean(tf.square(hypothesis-Y))

# Minimize
a = tf.Variable(0.1) # Learning rate, alpha
optimizer = tf.train.GradientDescentOptimizer(a)
train = optimizer.minimize(cost)

# Before starting, initialize the variables.
# We are going to run this first.
init = tf.initialize_all_variables()

# Launch the graph
sess = tf.Session()
sess.run(init)

# Fit the line.
for step in xrange(2001):
    sess.run(train, feed_dict={X:x_data, Y:y_data})
    if step % 100 == 0 :
        print step, sess.run(cost,feed_dict={X:x_data, Y:y_data}), sess.run(W), sess.run(b)

result

0 0.0671113 [ 1.31180656] [-0.57569945]
100 0.000394039 [ 1.02305508] [-0.05240955]
200 3.03385e-06 [ 1.00202298] [-0.00459877]
300 2.33703e-08 [ 1.0001775] [-0.00040349]
400 1.7819e-10 [ 1.00001562] [ -3.54349249e-05]
500 1.51227e-12 [ 1.00000143] [ -3.18881439e-06]
600 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
700 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
800 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
900 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
1000 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
1100 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
1200 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
1300 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
1400 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
1500 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
1600 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
1700 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
1800 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
1900 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]
2000 3.78956e-14 [ 1.00000036] [ -6.25814607e-07]

이렇게 한번 model을 생성 했다면,
생성된 hypothesis를 이용해서 특정 X에 대한 모델을 출력할 수 있게 된다.

# learns best fit is W: [1], b: [0]

# Learns best fit is W: [1], b[0]
print sess.run(hypothesis, feed_dict={X:5})
print sess.run(hypothesis, feed_dict={X:2.5})

결과

[ 5.00000143]
[ 2.50000024]


TensorFlow 개발환경 ( Eclipse + PyDev, Pycharm, Jupyter)



TensorFlow 설치법과 PyDev 설치법은 이전에 다뤘다.

원할한 개발을 위해서 PyDev에 TensorFlow를 연결하는것을 다룬다.


우선 필자는 TensorFlow를 Virtualenv에다가 설치 했다. VirtualEnv를 설치하는 이유는 아래와 같다.

Here's the short version: pip lets you install packages (Python libraries). Usually, you do not want to install packages globally, for the entire system, because they may conflict with each other. Instead, you want each Python project you create to have its own isolated ecosystem. Virtualenv provides this isolation. Virtualenvwrapper makes virtualenv nicer to use.


Even if you're not worried about conflicts, virtualenv can help you make sure your demo still works years from now (especially important if you care about reproducible research). The fact is that libraries aren't always perfectly backward-compatible or bug-free. You may upgrade a package and find that it breaks your project. The more time passes since you last ran a piece of code, the more likely it is to be broken. Using a virtualenv to freeze the dependencies is a safeguard against this problem.



PyDev의 VirtualEnv 설정 연결


PyDev와 TensorFlow 그리고 virtualenv가 모두 설치되었어야 한다.


Eclipse 메뉴에서

Preferences -> PyDev > Interpreters > Python 메뉴에서

New를 눌러서 Browse를 통해서 설정한 virtualenvs를 등록해준다.

<venv-name>/bin/python


등록할때 모든 종속 라이브러릴 같이 등록해준다. 팝업이 나오면 다 선택된 상태로 등록하면 된다.






프로젝트 생성 및 "Hellow Tensor"실행


아래와 같이 프로젝트를 생성 할 때 interpreter를 생성한 virtualenv용 python 환경으로 잘 선택해 줘야 한다.



그다음 Hello tensorflow 코드를 실행하면 정상적으로 실행 되는것을 알 수 있다.

'''
Created on Nov 17, 2015

@author: root
'''
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print sess.run(hello)

a = tf.constant(10)
b = tf.constant(32)
print sess.run(a+b)





IntelliJ 기반의 Pycharm


설치방법: 이전포스트


실행 모습



아래와 같이 Tensorflow가 있는 virtualenv를 interpreter로 설정을 해주어야 한다.





웹기반 Jupyter로 실행하기


설치방법: 이전포스트




'AI > TensorFlow, PyTorch, Keras, Scikit' 카테고리의 다른 글

Softmax Function  (0) 2016.04.19
Neural Networks in XOR problem  (0) 2016.04.18
Logistic Regression  (0) 2016.04.17
Linear regression with TensorFlow  (0) 2016.04.17
TensorFlow 설치 및 예제 실행 (uBuntu)  (2) 2015.11.17

TensorFlow 설치 및 예제 실행 (uBuntu)


2015.11.9일에 공개된 오픈프로젝트 TensorFlow는 Google에서 공개한 DeepLearning을 위한 2세대 system이다.

TensorFlow의 내용은 이전 Post를 참조 한다.

이 시스템의 설치와 실행을 다룬다.



Python VirtualEnv에 기반한 설치 방법


필자가 사용하는 Desktop PC의 환경은 아래와 같다.


설치환경

uBuntu 14.04 64bit (LTS)

VMware based

python 2.7 (설치법 참조)


필자는 VirtualEnv-based Installation을 수행한다(VirtualEnv 설치).

VirtualEnv 환경을 python 자체가 지원하므로 고립된 수행 환경을 생성할 수 있는 이점이 있다. 문제 발생시에도 모든 사람이 같은 상황이므로 해결방법을 그대로 적용할 수 있는 장점이 있다.

#Next, set up a new virtualenv environment. To set it up in the directory ~/tensorflow, run:
$ virtualenv --system-site-packages ~/tensorflow
$ cd ~/tensorflow

tensorflow는 이제 가상환경이 저장되는 디렉터리가 된다.

--system-site-packages 옵션의 의미는 가상환경에게 global site-package의 접근 권한을 허용 하는 것이다.

아래의 경로에 해당 가상환경에만 적용되는 site-package들이 저장되어 있다.

~/tensorflow/lib/python2.7/site-packages

아래의 경로에는 해당 가상환경에서 사용 할 수 있는 python의 종류이다.

~/tensorflow/lib/


virtualenv를 활성화 시킨다.

$ source (설치경로)/bin/activate  # If using bash
source ./tensorflow/bin/activate #나의 경우 

비활성화는 deactivate라고 치면된다.


만약 csh 쉘을 쓴다면 아래의 명령어이다.

$ source bin/activate.csh  # If using csh

최종적으로 아래처럼 프롬프트 창의 이름 앞에 (tensorflow)가 들어가는 것을 볼 수 있다.

(tensorflow)root@jemin-virtual-machine:

실행된 virtualenv의 환경에서 TensorFlow를 설치한다.

설치 종류는 CPU-only version과 GPU-enabled version이 있으므로 자신이 원하는것을 선택하자.

필자는 일단 CUDA sdk를 설치하지 않았으므로 CPU-only를 설치했다.

# For CPU-only version
$ pip install https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl

# For GPU-enabled version (only install this version if you have the CUDA sdk installed)
$ pip install https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl

이렇게까지 하면 tensorFlow는 설치가 된것이다.

이제 간단한 예제를 실행해보자.


Hello, TensorFlow

Hello, TensorFlow
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> hello = tf.constant("Hello, TensorFlow!")
>>> sess = tf.Session()
I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 8
I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 8
>>> print sess.run(hello)
Hello, TensorFlow!
>>> a = tf.constant(10)
>>> b = tf.constant(32)
>>> print sess.run(a+b)
42
(tensorflow)root@jemin-virtual-machine:~/tensorflow# 
위와 같이 실행되면, 정상적으로 설치가 된것이다.


삼차원 데이터를 100개 생성하고 그것에 딱 맞는 초평면을 생성하는 예제이다.
# Make 100 phony data points in NumPy.
x_data = np.float32(np.random.rand(2, 100)) # Random input
y_data = np.dot([0.100, 0.200], x_data) + 0.300

# Construct a linear model.
b = tf.Variable(tf.zeros([1]))
W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0))
y = tf.matmul(W, x_data) + b

# Minimize the squared errors.
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)

# For initializing the variables.
init = tf.initialize_all_variables()

# Launch the graph
sess = tf.Session()
sess.run(init)

# Fit the plane.
for step in xrange(0, 201):
    sess.run(train)
    if step % 20 == 0:
        print step, sess.run(W), sess.run(b)

# Learns best fit is W: [[0.100  0.200]], b: [0.300]
I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 8
I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 8
Hello, TensorFlow!
42
0 [[ 0.3138563   0.52770293]] [-0.0221094]
20 [[ 0.17014106  0.30057704]] [ 0.20599112]
40 [[ 0.12187628  0.23032692]] [ 0.27126268]
60 [[ 0.10676718  0.20918694]] [ 0.29121917]
80 [[ 0.10208294  0.2027912 ]] [ 0.29731771]
100 [[ 0.10063919  0.20084961]] [ 0.29918078]
120 [[ 0.10019579  0.20025893]] [ 0.29974979]
140 [[ 0.1000599   0.20007896]] [ 0.2999236]
160 [[ 0.10001831  0.2000241 ]] [ 0.29997668]
180 [[ 0.1000056   0.20000736]] [ 0.29999286]
200 [[ 0.1000017   0.20000222]] [ 0.29999784]

위와 같이 점차 반복수행 하면서, best fit인 0.1, 0.2, 0.3에 근접하는 것을 알 수 있다.



신경망 모델링 실행

이제 TensorFlow를 이용해서 이제 DeepLearning 예제를 실행해 보자.

실행할 예제는 신경망 모델링에 관한것이다.


일단 gitHub에서 TensorFlow 소스코드를 복제(clone)해와야 한다.

tensorflow)root@jemin-virtual-machine: git clone https://github.com/tensorflow/tensorflow.git

정상적으로 다운이 완료 되면, 예제를 실행 해보자.

이 예제는 "LeNet -5 - like convolutional MNIST model"이라고 한다.

(tensorflow)$ cd tensorflow/models/image/mnist
(tensorflow)$ python convolutional.py



실행결과

Initialized!
Epoch 0.00
Minibatch loss: 12.054, learning rate: 0.010000
Minibatch error: 90.6%
Validation error: 84.6%
Epoch 0.12
Minibatch loss: 3.285, learning rate: 0.010000
Minibatch error: 6.2%
Validation error: 7.0%
Epoch 0.23
Minibatch loss: 3.473, learning rate: 0.010000
Minibatch error: 10.9%
Validation error: 3.7%
Epoch 0.35
Minibatch loss: 3.221, learning rate: 0.010000
Minibatch error: 4.7%
Validation error: 3.2%
Epoch 0.47
Minibatch loss: 3.193, learning rate: 0.010000
Minibatch error: 4.7%
Validation error: 2.7%
Epoch 0.58
Minibatch loss: 3.301, learning rate: 0.010000
Minibatch error: 9.4%
Validation error: 2.5%
Epoch 0.70
Minibatch loss: 3.203, learning rate: 0.010000
Minibatch error: 6.2%
Validation error: 2.8%
Epoch 0.81
Minibatch loss: 3.022, learning rate: 0.010000
Minibatch error: 4.7%
Validation error: 2.6%
Epoch 0.93
Minibatch loss: 3.131, learning rate: 0.010000
Minibatch error: 6.2%
Validation error: 2.1%
Epoch 1.05
Minibatch loss: 2.954, learning rate: 0.009500
Minibatch error: 3.1%
Validation error: 1.6%
Epoch 1.16
Minibatch loss: 2.854, learning rate: 0.009500
Minibatch error: 0.0%
Validation error: 1.8%
Epoch 1.28
Minibatch loss: 2.825, learning rate: 0.009500
Minibatch error: 1.6%
Validation error: 1.4%
Epoch 1.40
Minibatch loss: 2.938, learning rate: 0.009500
Minibatch error: 7.8%
Validation error: 1.5%
Epoch 1.51
Minibatch loss: 2.767, learning rate: 0.009500
Minibatch error: 0.0%
Validation error: 1.9%
Epoch 1.63
Minibatch loss: 2.771, learning rate: 0.009500
Minibatch error: 3.1%
Validation error: 1.4%
Epoch 1.75
Minibatch loss: 2.844, learning rate: 0.009500
Minibatch error: 4.7%
Validation error: 1.2%
Epoch 1.86
Minibatch loss: 2.694, learning rate: 0.009500
Minibatch error: 0.0%
Validation error: 1.3%
Epoch 1.98
Minibatch loss: 2.650, learning rate: 0.009500
Minibatch error: 0.0%
Validation error: 1.5%
Epoch 2.09
Minibatch loss: 2.667, learning rate: 0.009025
Minibatch error: 1.6%
Validation error: 1.4%
Epoch 2.21
Minibatch loss: 2.658, learning rate: 0.009025
Minibatch error: 1.6%
Validation error: 1.2%
Epoch 2.33
Minibatch loss: 2.640, learning rate: 0.009025
Minibatch error: 3.1%
Validation error: 1.2%
Epoch 2.44
Minibatch loss: 2.579, learning rate: 0.009025
Minibatch error: 1.6%
Validation error: 1.1%
Epoch 2.56
Minibatch loss: 2.568, learning rate: 0.009025
Minibatch error: 0.0%
Validation error: 1.2%
Epoch 2.68
Minibatch loss: 2.554, learning rate: 0.009025
Minibatch error: 1.6%
Validation error: 1.1%
Epoch 2.79
Minibatch loss: 2.503, learning rate: 0.009025
Minibatch error: 0.0%
Validation error: 1.2%
Epoch 2.91
Minibatch loss: 2.487, learning rate: 0.009025
Minibatch error: 0.0%
Validation error: 1.2%
Epoch 3.03
Minibatch loss: 2.463, learning rate: 0.008574
Minibatch error: 1.6%
Validation error: 1.2%
Epoch 3.14
Minibatch loss: 2.458, learning rate: 0.008574
Minibatch error: 1.6%
Validation error: 1.1%
Epoch 3.26
Minibatch loss: 2.410, learning rate: 0.008574
Minibatch error: 0.0%
Validation error: 1.4%
Epoch 3.37
Minibatch loss: 2.496, learning rate: 0.008574
Minibatch error: 3.1%
Validation error: 1.3%
Epoch 3.49
Minibatch loss: 2.399, learning rate: 0.008574
Minibatch error: 1.6%
Validation error: 1.1%
Epoch 3.61
Minibatch loss: 2.377, learning rate: 0.008574
Minibatch error: 0.0%
Validation error: 1.1%
Epoch 3.72
Minibatch loss: 2.333, learning rate: 0.008574
Minibatch error: 0.0%
Validation error: 1.1%
Epoch 3.84
Minibatch loss: 2.312, learning rate: 0.008574
Minibatch error: 0.0%
Validation error: 1.2%
Epoch 3.96
Minibatch loss: 2.300, learning rate: 0.008574
Minibatch error: 1.6%
Validation error: 1.1%
Epoch 4.07
Minibatch loss: 2.276, learning rate: 0.008145
Minibatch error: 0.0%
Validation error: 1.1%
Epoch 4.19
Minibatch loss: 2.250, learning rate: 0.008145
Minibatch error: 0.0%
Validation error: 1.0%
Epoch 4.31
Minibatch loss: 2.233, learning rate: 0.008145
Minibatch error: 0.0%
Validation error: 1.0%
Epoch 4.42
Minibatch loss: 2.217, learning rate: 0.008145
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 4.54
Minibatch loss: 2.324, learning rate: 0.008145
Minibatch error: 3.1%
Validation error: 1.0%
Epoch 4.65
Minibatch loss: 2.212, learning rate: 0.008145
Minibatch error: 0.0%
Validation error: 1.0%
Epoch 4.77
Minibatch loss: 2.174, learning rate: 0.008145
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 4.89
Minibatch loss: 2.211, learning rate: 0.008145
Minibatch error: 1.6%
Validation error: 1.0%
Epoch 5.00
Minibatch loss: 2.193, learning rate: 0.007738
Minibatch error: 1.6%
Validation error: 1.0%
Epoch 5.12
Minibatch loss: 2.148, learning rate: 0.007738
Minibatch error: 3.1%
Validation error: 1.0%
Epoch 5.24
Minibatch loss: 2.153, learning rate: 0.007738
Minibatch error: 3.1%
Validation error: 1.0%
Epoch 5.35
Minibatch loss: 2.111, learning rate: 0.007738
Minibatch error: 1.6%
Validation error: 0.9%
Epoch 5.47
Minibatch loss: 2.084, learning rate: 0.007738
Minibatch error: 1.6%
Validation error: 0.8%
Epoch 5.59
Minibatch loss: 2.054, learning rate: 0.007738
Minibatch error: 0.0%
Validation error: 1.0%
Epoch 5.70
Minibatch loss: 2.043, learning rate: 0.007738
Minibatch error: 0.0%
Validation error: 1.0%
Epoch 5.82
Minibatch loss: 2.134, learning rate: 0.007738
Minibatch error: 3.1%
Validation error: 1.0%
Epoch 5.93
Minibatch loss: 2.006, learning rate: 0.007738
Minibatch error: 0.0%
Validation error: 1.0%
Epoch 6.05
Minibatch loss: 2.048, learning rate: 0.007351
Minibatch error: 3.1%
Validation error: 0.9%
Epoch 6.17
Minibatch loss: 1.988, learning rate: 0.007351
Minibatch error: 0.0%
Validation error: 1.1%
Epoch 6.28
Minibatch loss: 1.957, learning rate: 0.007351
Minibatch error: 0.0%
Validation error: 0.8%
Epoch 6.40
Minibatch loss: 1.971, learning rate: 0.007351
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 6.52
Minibatch loss: 1.927, learning rate: 0.007351
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 6.63
Minibatch loss: 1.912, learning rate: 0.007351
Minibatch error: 0.0%
Validation error: 1.0%
Epoch 6.75
Minibatch loss: 1.901, learning rate: 0.007351
Minibatch error: 0.0%
Validation error: 0.8%
Epoch 6.87
Minibatch loss: 1.886, learning rate: 0.007351
Minibatch error: 0.0%
Validation error: 0.8%
Epoch 6.98
Minibatch loss: 1.894, learning rate: 0.007351
Minibatch error: 1.6%
Validation error: 1.0%
Epoch 7.10
Minibatch loss: 1.859, learning rate: 0.006983
Minibatch error: 0.0%
Validation error: 0.8%
Epoch 7.21
Minibatch loss: 1.844, learning rate: 0.006983
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 7.33
Minibatch loss: 1.836, learning rate: 0.006983
Minibatch error: 0.0%
Validation error: 1.0%
Epoch 7.45
Minibatch loss: 1.887, learning rate: 0.006983
Minibatch error: 3.1%
Validation error: 0.9%
Epoch 7.56
Minibatch loss: 1.808, learning rate: 0.006983
Minibatch error: 0.0%
Validation error: 0.8%
Epoch 7.68
Minibatch loss: 1.822, learning rate: 0.006983
Minibatch error: 1.6%
Validation error: 0.9%
Epoch 7.80
Minibatch loss: 1.782, learning rate: 0.006983
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 7.91
Minibatch loss: 1.772, learning rate: 0.006983
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 8.03
Minibatch loss: 1.761, learning rate: 0.006634
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 8.15
Minibatch loss: 1.773, learning rate: 0.006634
Minibatch error: 1.6%
Validation error: 0.9%
Epoch 8.26
Minibatch loss: 1.742, learning rate: 0.006634
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 8.38
Minibatch loss: 1.744, learning rate: 0.006634
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 8.49
Minibatch loss: 1.719, learning rate: 0.006634
Minibatch error: 0.0%
Validation error: 0.8%
Epoch 8.61
Minibatch loss: 1.700, learning rate: 0.006634
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 8.73
Minibatch loss: 1.700, learning rate: 0.006634
Minibatch error: 0.0%
Validation error: 0.8%
Epoch 8.84
Minibatch loss: 1.801, learning rate: 0.006634
Minibatch error: 1.6%
Validation error: 0.8%
Epoch 8.96
Minibatch loss: 1.666, learning rate: 0.006634
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 9.08
Minibatch loss: 1.666, learning rate: 0.006302
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 9.19
Minibatch loss: 1.649, learning rate: 0.006302
Minibatch error: 0.0%
Validation error: 0.8%
Epoch 9.31
Minibatch loss: 1.676, learning rate: 0.006302
Minibatch error: 1.6%
Validation error: 0.8%
Epoch 9.43
Minibatch loss: 1.626, learning rate: 0.006302
Minibatch error: 0.0%
Validation error: 0.8%
Epoch 9.54
Minibatch loss: 1.621, learning rate: 0.006302
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 9.66
Minibatch loss: 1.606, learning rate: 0.006302
Minibatch error: 0.0%
Validation error: 0.8%
Epoch 9.77
Minibatch loss: 1.596, learning rate: 0.006302
Minibatch error: 0.0%
Validation error: 0.9%
Epoch 9.89
Minibatch loss: 1.602, learning rate: 0.006302
Minibatch error: 0.0%
Validation error: 0.9%
Test error: 0.8%

실행 시간은 아래와 같다.

- MNIST -

real 26m26.382s

user 77m58.714s

sys 19m21.539s


가상화 환경에서 CPU만 가지고 처리해서 오래걸린것 같다.

그래도 i7 4세대 프로세서, ram 24gb, ssd pro 256gb에서 실행한것인데, 대략 Android 5.0 컴파일 시간의 반 정도의 시간이 걸린것 같다.








+ Recent posts