# 多项式回归（polynomial regression）转换为线性回归（linear regression）

import numpy as np
from sklearn.linear_model import LinearRegression

from sklearn.preprocessing import PolynomialFeatures
import matplotlib.pyplot as plt
# seed
rng = np.random.RandomState(123)
# construct samples. give a x, generate y with noise
def genY(x):
a0, a1, a2, a3, e = 0.1, -0.02, 0.03, -0.04, 0.05
yr = a0 + a1*x + a2*(x**2) + a3*(x**3) + e
y = yr + 0.03*rng.rand(1)
return y
# plot
plt.figure()
plt.title('polynomial regression(sklearn)')
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)

x_tup = np.linspace(-1, 1, 30)
y = [genY(a) for a in x_tup]
print y
x = x_tup.reshape(-1,1)
y = np.array(y).reshape(-1,1)
plt.plot(x, y, 'k.')

qf = PolynomialFeatures(degree = 3)
qModel = LinearRegression()
qModel.fit(qf.fit_transform(x), y)
print '----'
print qf.get_params()

xp = np.linspace(-1, 2, 100)
yp = qModel.predict(qf.transform(xp.reshape(-1, 1)))

plt.plot(xp, yp, 'r-')
plt.show()

#-*- coding:utf-8 -*-
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

rng = np.random.RandomState(123)

def genY(x):
a0, a1, a2, a3, e = 0.1, -0.02, 0.03, -0.04, 0.05
yr = a0 + a1*x + a2*(x**2) + a3*(x**3) + e
y = yr + 0.03*rng.rand(1)
return y

plt.figure()
plt.title('polynomial regression(tensorflow)')
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)

x = np.linspace(-1, 1, 30)
y = [genY(a) for a in x]
x = x.reshape(-1,1)
y = np.array(y).reshape(-1,1)
plt.plot(x, y, 'k.')

X = tf.placeholder('float')
Y = tf.placeholder('float')
W = tf.Variable([0.] * 4)
print W

def Model(x, w):
terms = []
for i in range(0, 4):
term = tf.multiply(w[i], tf.pow(x, i))
terms.append(term)
rs = tf.add_n(terms)
return rs
YModel = Model(X, W)
Cost = tf.reduce_sum(tf.square(Y - YModel))
LearnRate = 0.01
train_op = tf.train.GradientDescentOptimizer(LearnRate).minimize(Cost)

with tf.Session() as sess:
Init = tf.global_variables_initializer()
sess.run(Init)
for i in range(0, 100):
for (_x, _y) in zip(x, y):
sess.run(train_op, feed_dict = {X: _x, Y: _y})
print sess.run(W)

xp = np.linspace(-1, 2, 100)
yp = 0
for i in range(0, 4):
yp += sess.run(W)[i] * np.power(xp, i)

plt.plot(xp, yp, 'g-')
plt.show()