公式サンプル では線形回帰を行った。
せっかくなので、もうちょっとだけ複雑にした関係式で、回帰(パラメータ推定)を行う
In [41]:
%matplotlib inline
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# http://www.tensorflow.org/get_started
x_data = np.float32(np.random.rand(1, 100)) # Random input
noise = np.random.normal(scale=0.02, size=(1, 100))
y_data = 0.4 * (x_data ** 5) + 0.1 + noise
plt.scatter(x_data[0], y_data[0])
plt.xlim(0, 1.0)
plt.ylim(0, 0.4)
Out[41]:
y = a x^5 + b の関係性の直線を引いた。
関数の形は既知、a・bのパラメーターは未知として、a・bのパラメータを推定する。(正解は a = 0.4, b = 0.1)
In [43]:
# Construct a linear model.
b = tf.Variable(tf.zeros([1]))
a = tf.Variable(tf.random_uniform([1, 1], -1.0, 1.0, seed=1))
y = tf.matmul(a, tf.pow(x_data, 5)) + 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.
result = [] # a, b, y
for step in range(0, 150):
sess.run(train)
a_, b_ = sess.run(a)[0, 0], sess.run(b)[0]
y_ = sess.run(y)
if step % 10 == 0:
print(a_, b_)
result.append((a_, b_, y_))
In [44]:
x = np.linspace(0, 1, num=200)
for i, (a_, b_, _) in enumerate(result):
y_ = a_ * np.power(x, 5) + b_
plt.figure()
plt.scatter(x_data[0], y_data[0])
plt.plot(x, y_, label='y = %.3f * x^5 + %.3f' % (a_, b_), c='r')
plt.title("iteration #%d" % (i * 10))
plt.legend()
plt.xlim(0, 1.0)
plt.ylim(0, 0.4)
初期値では全然フィッティングできていないが、最後のイテレーションでは曲線フィッティングができている!
In [ ]: