본문 바로가기
machine learning

[TENSORFLOW] Polynomial Model

by 유주원 2017. 4. 8.

2017/04/10 - [machine learning] - [TENSORFLOW] Linear regression Classification


이전의 Linear regression에서 1차항에 대한 regression을 고민했다면, 이번에는 항이 여러 개인 다차항에 대한 regression을 고민해보자.

위의 식과 같이 여러 개의 항으로 구성되어 있는 model을 Polynomial Model이라고 부른다.

import tensorflow as tf

import numpy as np

import matplotlib.pyplot as plt

%matplotlib inline


num_coeffs = 6

training_epochs = 400

learning_rate = 0.01


def model(X, w):

terms = []

for i in range(num_coeffs):

term = tf.mul(w[i], tf.pow(X, i))

terms.append(term)

return tf.add_n(terms)


def gettrY():

trY = 0

trY_coeffs = [1, 2, 3, 4, 5, 6]

for i in range(num_coeffs):

trY += trY_coeffs[i] * np.power(trX, i)

trY += np.random.randn(*trX.shape) * 1.5

return trY


def gettrX():

return np.linspace(-1, 1, 101)


trX = gettrX()

trY = gettrY()

X = tf.placeholder("float")

Y = tf.placeholder("float")

w = tf.Variable[0.] * num_coeffs, name="parameters")

y_model = model(X, w)

cost = (tf.pow(Y-y_model, 2))

train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)


sess = tf.Session()

init = tf.global_variables_initializer()

sess.run(init)

for epoch in range(training_epochs):

for (x,y) in zip(trX, trY):

sess.run(train_op, feed_dict={X:x, Y:y})


w_val = sess.run(w)

sess.close()

plt.scatter(trX, trY)

trY2 = 0


for i in range(num_coeffs):

trY2 += w_val[i] * np.power(trX, i)

plt.plot(trX, trY2, 'r')

plt.show()



이전에 살펴본 linear regression 코드와 상당히 유사하기 때문에 차이점 위주로 살펴보자면, 우선 num_coeffs라는 변수가 추가가 되었다. 이전에는 1차항이기 때문에 따로 명시를 안했지만, 지금은 6차항의 방정식 계수를 찾아야하기 때문에 num_coeffs라는 변수를 추가해주었다.

model함수도 약간 복잡해졌는데 결국에는 위에서 언급한 f(x)를 구하기 위한 코드임을 우선 인지하면 이해가 쉽다.

tf.mul을 통해 각각 6개의 w값에 x의 제곱근을 곱한다.

w와 x를 각각 곱한 결과를 더해주기 위해 tf.add_n함수를 이용한다.

 모델 생성이 완료되었으면 이제 train_data trX와 정답 trY를 생성하자.

gettrX 함수를 호출해서 -1과 1 사이의 균등한 숫자 101개를 뽑고, gettrY를 통해 해당 X 값에 대한 정답 리스트를 추출한다.

gettrY를 보면, 정답 w인 [1,2,3,4,5,6]을 각각의 trX에 대한 제곱승으로 곱한 다음 더해주고, 더한 결과에 대해 noise를 더해준 값을 최종적으로 생성한다.

for i in range(num_coeffs):

trY += trY_coeffs[i] * np.power(trX, i)

trY += np.random.randn(*trX.shape) * 1.5

나머지 진행은 이전 포스팅에서 설명한 linear regression 코드와 동일하기 때문에 생략하도록 하겠다.

마지막으로 찾아낸 w_val 값을 print 해보면 아래와 같이 나타나는데, 정답 계수 [1,2,3,4,5,6]에 랜덤으로 noise를 씌웠기 때문에 해당 noise가 반영된 결과의 계수 값이 나타나게 된다.  

[ 1.125, 0.58269811, 4.37246943, 6.83307457, 2.77599858, 4.65937662]

해당 결과 계수가 regression을 잘 하는지 확인해 보기 위해 plot으로 그림을 그려보자.