반응형

알 수 없는 n차 다항 함수에 근사하는 샘플데이터를 학습시켜보자.

단순한 linear regression으로는 다차항 함수의 학습이 되지 않는다.

feature 값을 x^2, x^3, .. 이런식으로 변환하여 feture들을 늘려서 학습시킨다면 가능할수도 있지만, 몇 차로 해야될지도 알 수 없고 전처리를 해야되서 예측이 어렵다.

이것을 해결하기 위해서는 deep and wide한 네트웍을 구성하여 학습을 시킨다.

단, 주의해야될 점은 바로 activation function이다. 항등함수로만 하면 아무리 네트웍을 구성해도 학습이 되지 않는다.

네트웍을 affine  계층으로만 하게되면 weighted sum을 다시 weighted sum을 하게 되므로 다중 레이어를 둔 의미가 상실되게 된다. 즉, xw+b를 다시 (xw+b)w+b가 되서 아무리 반복해도 x*w+b꼴로 표현이 가능하다. 즉, 단층레이어와 동일할 뿐이다.

activation function은 다양한 정보 표현이 가능하도록 비선형 함수들을 사용해야 한다. sigmoid, tanh, relu 등.

그리고 마지막 계층 또한 중요하다. 1/0을 판단하는 binary classification이라면 sigmoid로 하고, multinomial classfication이라면 softmax를 사용하며, 실수범위의 예측이라면???  출력값의 범위가 표현될 수 있는 function을 만든다.  학습이 잘 되냐 실패하냐거 거의 여기에 달린 것 같다.

ex) sigmoid or tanh or identity 의 값에 * 도메인크기 + bias , 

(identity는 항등함수를 말함. 즉, weighted sum 인풋이 그대로 출력되는 함수) 

몇 번 테스트해보니 sigmoid나 tanh가 적당하다. 


단, 이렇게 학습하여 예측하는 것에는 한계가 있다.

학습한 데이터의 도메인에 해당되는 범위내에서는 예측가능하나, 학습되지 않은 구간에서는 맞지 않게 된다.


# -*- coding: utf-8 -*-


'''

Created on Sat May 13 10:54:59 2017


@author: Junhee

'''


#

# complex algbra predict learning? is it possible???

# continous valued target bounded range (-1000,1000)

# not using polynomial modified input!. because I don't know

# what polynomial degree is correct. 

#



import numpy as np

import tensorflow as tf

import matplotlib.pyplot as plt

import time



bDrawFigure = True

# train yes or no

bTrain = 1

#learning_rate = 0.1

#learning_rate = 0.0001

learning_rate = 0.00001

#learning_rate = 0.1

trainset_cnt = 200

epoch_cnt = 4000

#epoch_cnt = 40000





# unknown algbra function

def problem(x):

#    y = x**2

    y = x**2-30*x

    return y

# can u imagine? i dont know.

xrange = np.linspace(0, 100, 200)

y_correct = problem(xrange)


# draw graph?

if bDrawFigure:

    plt.figure()

    plt.plot(xrange, y_correct)


output_space = 40000     # tanh ; -1~1 X output_space ; output range! ; -2000~2000


                    # x domain ; -1000~1000

trainx = np.random.rand(trainset_cnt)*100-0   # training set must be shuffle!!!

trainx = trainx.reshape([-1,1])

trainy_cor = problem(trainx)

trainy_cor = trainy_cor.reshape([-1,1])



X = tf.placeholder(tf.float32, shape=[None,1])

Y = tf.placeholder(tf.float32, shape=[None,1])


# make network NN

W1 = tf.Variable(tf.random_normal([1,512]))

b1 = tf.Variable(tf.zeros([512]))

L1 = tf.nn.sigmoid(tf.matmul(X, W1)+b1)

#L1 = tf.nn.tanh(tf.matmul(X, W1)+b1) 


W2 = tf.Variable(tf.random_normal([512,1024]))

b2 = tf.Variable(tf.zeros([1024]))

L2 = tf.nn.sigmoid( tf.matmul(L1, W2)+b2) 


W3 = tf.Variable(tf.random_normal([1024,1024]))

b3 = tf.Variable(tf.zeros([1024]))

L3 = tf.nn.sigmoid( tf.matmul(L2, W3)+b3) 


W4 = tf.Variable(tf.random_normal([1024,1024]))

b4 = tf.Variable(tf.zeros([1024]))

L4 = tf.nn.sigmoid( tf.matmul(L3, W4)+b4) 


W5 = tf.Variable(tf.random_normal([1024,1]))

b5 = tf.Variable(tf.zeros([1]))

#Llast = tf.nn.tanh( tf.matmul(L4, W5)+b5) *output_space


#good

Llast = (tf.nn.sigmoid( tf.matmul(L4, W5)+b5)) *output_space - 500


#Llast = (tf.matmul(L4, W5)+b5) *output_space


# bad... 

#Llast = (tf.matmul(L4, W5)+b5)


cost = tf.reduce_mean( tf.square(Llast-Y) )


train = tf.train.AdamOptimizer(learning_rate).minimize(cost)


sess = tf.Session()

sess.run( tf.global_variables_initializer())


param_list = {'W1':W1,'b1':b1,

              'W2':W2,'b2':b2,

              'W3':W3,'b3':b3,

              'W4':W4,'b4':b4,              

              'W5':W5,'b5':b5,

              }

saver = tf.train.Saver(param_list)

#saver.restore(sess, './unknown_predict_poly.ptl')    # continue train


print( "bTrain=", bTrain, " trainset_cnt=", trainset_cnt, " epoch=cnt", epoch_cnt)

# train

oldtime = time.time()

if bTrain:

    for i in range(epoch_cnt) :

        _, _cost = sess.run( [train, cost], feed_dict={X:trainx, Y:trainy_cor})

        if i%100==(100-1):

            newtime = time.time()

            term = newtime-oldtime

            print( "train=",i," cost=",_cost, " remaintime=", ((epoch_cnt-i)/100+1)*term)

            oldtime=newtime

    saver.save(sess, './unknown_predict_poly.ptl')


##########################################################

# test

saver.restore(sess, './unknown_predict_poly.ptl')

    

#draw compare

if bDrawFigure:

#    xrange = np.linspace(-1000, 1000, 2000)

    xrange = np.linspace(1, 200, 200)

    xrange = xrange.reshape(-1, 1)

    _llast2 = sess.run( Llast, feed_dict = { X:xrange } )

    xrange = xrange.reshape(-1)

    testyrange = _llast2.reshape(-1)

    plt.plot(xrange, testyrange, c='r')    

    

plt.show()



출력결과

bTrain= 1  trainset_cnt= 200  epoch=cnt 4000

train= 99  cost= 4.10605e+07  remaintime= 408.33133206844326

train= 199  cost= 6.47534e+06  remaintime= 374.9750850892067

train= 299  cost= 3.22122e+06  remaintime= 390.8726796555519

...

train= 3399  cost= 12447.5  remaintime= 73.77905233621597

train= 3499  cost= 12130.0  remaintime= 62.91447646141052

train= 3599  cost= 11828.8  remaintime= 51.30402812004089

train= 3699  cost= 11539.5  remaintime= 43.085111978054044

train= 3799  cost= 11257.4  remaintime= 33.96168860197067

train= 3899  cost= 10978.7  remaintime= 21.201974751949308

train= 3999  cost= 10699.7  remaintime= 11.279016330242158

INFO:tensorflow:Restoring parameters from ./unknown_predict_poly.ptl

초반에 cost가 어마어마하다. 학습이 잘 된다면 위와 같이 점점 줄어들 것이다.


임의의 다차항 함수의 샘플을 생성하여 학습한다.

y=x^2-30x 라는 함수를 배워본다. 단, 전체 실수범위에 대해서 학습은 불가능하다.

샘플의 범위는 유한하기 때문. x의 범위를 0~100까지를 학습해 본다.

학습데이터의 모습은 아래와 같다.

이를 학습하여 200까지 예측해 보면, 100~200 범위는 배우지 않았기 때문에 오차가 커진다.

그러나 학습한 범위인 0~100까지는 거의 정확하다!

최종 학습 결과.

위 그림에서 0~100 구간은 파란선과 빨간선의 거의 일치한다.


추신)

샘플에 noise를 가해주고 학습하는게 좋을 것 같다.

학습시에는 batch로 샘플데이터를 random select하게 해야 학습이 더 잘 될 것 같다. 

다른 복잡한 곡선도 테스트해 보자.


반응형


보간법. interpolate 


몇 개의 샘플 포인트들로 추정하여 인접한 점들 사이를 다항식 함수로 완만한 곡선으로 이어준 것을 스플라인 곡선이라고 한다.

보간법은 이러한 미싱 포인트(추정)들을 계산/추정하는 방법이다.

간단하게는 linear 방식(1차)이 있고, 2차, 3차, 4차 곡선등으로 확장하면서 보다 다양하게 추정할 수 있다.



위 그림은 파란색 점의 샘플 좌표들만을 가지고, 스플라인 곡선을 만들어 그린 추정 그래프이다.

python에서 scipy 라이브러리의 interpolate를 사용하여 구현하였다.

아래 코드에서 splrep에 별다른 옵션이 없으면 3차 스플라인 곡선으로 추정하게 된다. (k=1(선형보간), k=2, k=3(default), k=4 이런식으로 옵션을 준다. )

[python code]


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 25 2017
@author: crazyj
"""

# interpolation test

import numpy as np
import scipy.interpolate as ip
from scipy.interpolate import splrep, splev
import matplotlib.pyplot as plt

# 0~10까지 15개로 나누어 점을 찍음.
x0 = np.linspace(0, 10, 15)
print('x0=', x0)
# cosine 값을 계산
y0 = np.cos(x0)

# x, y (샘플)값을 주고 추정하는 스플라인 곡선을 만든다.
spl = splrep(x0, y0)
# 0~10까지 50구간에 대한 모든 점들을 위 스플라인 곡선으로 추정한 y값을 구한다.
x1 = np.linspace(0, 10, 50)
y1 = splev(x1, spl)

# 그린다.
plt.figure(figsize=(16, 5))
plt.subplot(121)
plt.plot(x0, y0, 'o')
plt.plot(x1, y1, 'r')
plt.grid()

# 이번에는 sine 곡선으로 추정해 본다.
plt.subplot(122)
y2=np.sin(x0)
spl2=splrep(x0, y2)
y3=splev(x1, spl2)
plt.plot(x0, y2, 'o')
plt.plot(x1, y3, 'b')
plt.grid()
plt.show()



'Python' 카테고리의 다른 글

Python 강좌4 정규식 regular expression  (0) 2018.03.19
Python 강좌3 자료형. 수/문자열  (1) 2018.03.16
Python 강좌2 if/for/while/function  (0) 2018.03.15
Python 강좌1. 산술연산, range  (0) 2018.03.14
Linear regression  (0) 2018.03.13
반응형


+ Tensorflow로 XOR  학습을 구현하기


XOR 학습을 수동으로 계산하지 않고, tensorflow의 api를 사용하면 심플해진다.

복잡한 네트웍도 쉽게 구현이 가능하다.


노드의 개수 및 레이어를 2-4-1 로 구성.

입력층에 노드 2개(feature 개수. x1, x2)

은닉층에는 4개 

출력층은 1개의 노드. (Y)

back-propagation을 위한 골치 아픈 작업(미분)들을 할 필요없이 api 하나로 학습 가능! activation function도 원하는대로 쉽게 변경하고, 학습 알고리즘은 쉽게 바꿀 수 있다.


#!/usr/bin/env python3

# -*- coding: utf-8 -*-

"""

Created on Tue May 23 14:56:53 2017


@author: crazyj

"""



import numpy as np

import tensorflow as tf


# trainint set

X_train = np.array( [[0,0], [0,1], [1,0], [1,1]])

T_train = np.array( [[0], [1], [1], [0]] )



# placeholder

X = tf.placeholder(tf.float32, [None, 2])

T = tf.placeholder(tf.float32, [None, 1])


# variable

W1 = tf.Variable(tf.truncated_normal([2,4]))

b1 = tf.Variable(tf.zeros([4]))

W2 = tf.Variable(tf.truncated_normal([4,1]))

b2 = tf.Variable(tf.zeros([1]), dtype=tf.float32)


# model

A1 = tf.matmul(X, W1)+b1

Z1 = tf.sigmoid(A1)

A2 = tf.matmul(Z1, W2)+b2

Z2 = tf.sigmoid(A2)


learn_rate = 0.1

Cost = tf.reduce_mean(tf.reduce_sum(tf.square(Z2-T), 1))

train = tf.train.GradientDescentOptimizer(learn_rate).minimize(Cost)


predict = Z2


sess = tf.Session()

sess.run(tf.global_variables_initializer())

for i in range(5000):

    _train, _Cost = sess.run([train, Cost], feed_dict={X:X_train, T:T_train})

    print( "cost=", _Cost)

    

_predict = sess.run([predict], feed_dict={X:X_train})

print("predict=", _predict)

print("result=", np.array(np.array(_predict)>=0.5, np.int))




결과

cost= 0.021748

cost= 0.0217359

cost= 0.0217239

predict= [array([[ 0.10571096],

       [ 0.86153752],

       [ 0.84178925],

       [ 0.17739831]], dtype=float32)]

result= [[[0]

  [1]

  [1]

  [0]]]


+ 코드 설명

# trainint set

X_train = np.array( [[0,0], [0,1], [1,0], [1,1]])

T_train = np.array( [[0], [1], [1], [0]] )

훈련 데이터는 당연히 xor의 입력 조합에 따른 결과를 훈련시킨다. (0,0) -> 0 , (0,1) -> 1 , (1,0) -> 1 , (1,1)->1


# placeholder

X = tf.placeholder(tf.float32, [None, 2])

T = tf.placeholder(tf.float32, [None, 1])

플레이스 홀더는 텐서플로우내에서 돌아갈 입출력 변수들이라고 보면 된다. 노드에서 변수가 되는 것을 X 입력층은 (?,2) 매트릭스 크기(로우는 임의의 개수, 컬럼은 2개(x1,x2)), 출력층 T는 (n,1) 매트릭스 형태로 선언한다.


# variable

W1 = tf.Variable(tf.truncated_normal([2,4]))

b1 = tf.Variable(tf.zeros([4]))

W2 = tf.Variable(tf.truncated_normal([4,1]))

b2 = tf.Variable(tf.zeros([1]), dtype=tf.float32)

텐서 플로우 변수들을 정의한다. 이것은 그래프에 구성될 노드들의 변수의 형태를 정의한다.

네트웍을 2-4-1로 구성할 것이므로 여기에 따른 weight를 담을 변수와 bias 변수의 형태는 다음과 같다.

2개 노드는 placeholder로 X이고, 2-4연결되는 W(웨이트)는 2행(입력노드개수) 4열(출력노드개수) 매트릭스이다. bias는 4개(출력노드개수)이다.

4-1로 연결되는 파트의 W는 4x1 이렇게 b는 1개 이렇게 구성한다. 초기값들은 랜덤하게 채워준다. bias는 0으로 초기화해준다.


# model

A1 = tf.matmul(X, W1)+b1

Z1 = tf.sigmoid(A1)

A2 = tf.matmul(Z1, W2)+b2

Z2 = tf.sigmoid(A2)

이제 빠진 히든 노드들과 출력층 노드들을 구성한다.

2-4-1네트웍에서 2개는 X, 4개는 A1으로 정하고,

A1 = X x W1 + b1 으로 정의한다.

Z1=은 A1에 활성화함수 sigmoid를 적용한다.


A2=Z1 x W2 + b2로 정의한다. 앞 노드의 출력 결과에 weighted sum이다.

Z2 = A2에 sigmoid를 적용한 것으로 최종 output이다.


learn_rate = 0.1

Cost = tf.reduce_mean(tf.reduce_sum(tf.square(Z2-T), 1))

train = tf.train.GradientDescentOptimizer(learn_rate).minimize(Cost)

predict = Z2

이제 학습방식을 정한다.
cost function은 오차 제곱법을 쓰고, 학습방식은 gradient descent를 사용하여 훈련 그래프를 만든다.
예측값은 최종 노드 출력인 Z2가 된다.


sess = tf.Session()

sess.run(tf.global_variables_initializer())

for i in range(5000):

    _train, _Cost = sess.run([train, Cost], feed_dict={X:X_train, T:T_train})

    print( "cost=", _Cost)

텐서플로우로 학습을 돌린다. 세션을 만들고, 초기화하여 5000번 학습한다. 그래프의 꼭지인 train을 집어 넣고, feed_dict로 플레이스 홀더 X, T에 훈련 데이터를 넣는다.  학습1회마다 cost값을 출력해 본다. 


_predict = sess.run([predict], feed_dict={X:X_train})
학습 완료후, 학습이 잘 되었는지  입력값 X_train을 넣고 출력값을 생성한다.

print("result=", np.array(np.array(_predict)>=0.5, np.int))

최종 결과로 시그모이드 함수에서 0.5이상이면 1로 미만이면 0으로 출력하여 binary 분류를 한다.





+ Recent posts