티스토리 뷰


This is an example of regression of the sin function with MLP

(Multi-layer perceptron)


요즘 주변에서는 많이 사용하는 neural network 통해서 

regression을 할 수는 없을까라는 잡생각이 들어서 간단하게 만들어 봤습니다. 


주어진 범위만 벗어나면 맞지도 않는 것을 왜하지 라고 하시는 답을 아시는 분도 계시겠지만, 

심심풀이로 간단하게 정리하고 만든 내용 공유 차원에서 적어 나가겠습니다.



아래 처럼 최종 출력단을 SUM 으로 하여서 알고 있는 답과 비교하면서 학습을 진행하도록 만들었습니다.

cost function 으로는 least square method 방식으로 $\sum_{k=1}^N (predict - correct)^2$ 로 정하였고,

activation function 을 relu 로 하여서 training 을 시도해봤습니다.



$sin(x)$ 함수

 $sin(x)$ neural network regression - relu

처음 하고난 결과는 두둥,,, 뭔가 어설프고 이상한게 보이시죠.

여기에서 제가 한가지 깜빡 했던, 아니 오해했던 내용이 있었네요, 


neural network 에서 sigmoid, tanh 함수들은 무조건 사용하지 말고, relu 를 쓰라고 머릿속에 암기되어 있어

regression 문제까지 relu 를 써버렸네요,.


regression 의 특성상 부드럽게 중간 중간을 채워주는 무엇인가가 필요한데,

relu 함수는 그렇게 부드러운 아이는 아니란걸 깜빡했습니다.


 regression vs classification



다시 relu 함수를 tanh 나 sigmoid 로 변경해서 training 을 시도했습니다. 

역시 예상이 맞았습니다. 부드러운 activation 함수로 바꾸고 나니, 한결 모양이 깔끔해졌습니다.


 $sin(x)$ neural network regression - tanh

모델로 함수를 쓰지않고, neural network 쓰다보니 역시 학습하지 않은 범위를 넘어가 버리면

값들이 산으로 가버렸네요


supervised learning




아래는 제가 간략하게 구현한 코드 입니다.




# python version 3.6.2
# tensorflow version 1.3.0

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt


def make_model(X,layer_shape,**kwargs):

	atv_enum = {'tanh':tf.nn.tanh,'relu':tf.nn.relu,'sigmoid':tf.nn.sigmoid}
	atv_fun = active_type[atv_enum[type]] if 'atv_type' in kwargs else atv_enum['tanh']

	layer = tf.multiply(X,1)
	for idx,size in enumerate(layer_shape[:-1]):
		W = tf.Variable(tf.random_normal([size,layer_shape[idx+1]]))
		b = tf.Variable(tf.random_normal([layer_shape[idx+1]]))
		layer = tf.add(tf.matmul(layer,W),b)

		if(idx != len(layer_shape)-2):
			layer = atv_fun(layer)

	return layer


if __name__ == '__main__':
	x_data = np.linspace(-2*np.pi,2*np.pi, 100).reshape(-1,1)
	y_data = np.sin(x_data)

		
	X = tf.placeholder(tf.float32,name='X')
	Y = tf.placeholder(tf.float32,name='Y')

	# activation function 으로 tanh 사용하였습니다.
	# neural network 구성은 1,5,5,1 로 구성하였습니다.
	model = make_model(X,[1,5,5,1])

	# leat square method 로 cost 함수 정의하였습니다.
	cost = tf.reduce_mean(tf.square(model - Y))
	train_op  = tf.train.AdamOptimizer(learning_rate=0.02).minimize(cost)

	init = tf.global_variables_initializer()
	with tf.Session() as sess:
		sess.run(init)

		for step in range(20000):
			error,_ = sess.run([cost,train_op],feed_dict={X:x_data,Y:y_data})
			if(step % 100 == 0):
				print(step,error)

		# 테스트 데이터를 -4 pi ~ 4 pi 로 구간을 넓혔습니다.
		tx_data = np.linspace(-4*np.pi,4*np.pi, 100).reshape(-1,1)
		predict = sess.run(model,feed_dict={X:tx_data})
		plt.plot(tx_data.flatten(),predict.flatten(),'ro')

		
	plt.plot(x_data.flatten(),y_data.flatten())
	plt.show()


'프로그래밍 > tensorflow' 카테고리의 다른 글

Tensorflow Serving vs Flask REST API  (0) 2021.12.28
[ slim ] model-inception  (0) 2017.10.09
[ intro ] google cloud platform  (0) 2017.09.25
[ CNN ] inception-v3 (tf slim )  (0) 2017.09.13
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함