In [1]:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
In [2]:
number_of_points = 200
x_point = []
y_point = []
Initial a, b
In [3]:
a = 0.22
b = 0.78
Generate Data
In [4]:
for i in range(number_of_points):
x = np.random.normal(0.0, 0.5)
y = a*x + b + np.random.normal(0.0, 0.1)
x_point.append([x])
y_point.append([y])
pass
plt.plot(x_point, y_point, 'o', label='Input Data')
plt.legend()
plt.show()
Initial A, B Variable
In [5]:
A = tf.Variable(initial_value=tf.random_uniform([1], -1.0, 1.0))
B = tf.Variable(initial_value=tf.zeros([1]))
Define Model
In [8]:
y = A * x_point + B
cost_function = tf.reduce_mean(tf.square(y - y_point))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5)
train = optimizer.minimize(cost_function)
model = tf.global_variables_initializer()
Start Training
In [9]:
with tf.Session() as session:
session.run(model)
for step in range(21):
session.run(train)
if (step % 5 == 0):
cost_ = session.run(cost_function)
a_ = session.run(A)
b_ = session.run(B)
print 'cost: {}, a: {}, b: {}'.format(cost_, a_, b_)
plt.plot(x_point, y_point, 'o', label='Step = {}'.format(step))
plt.plot(x_point, a_ * x_point + b_)
plt.legend()
plt.show()
pass
pass
In [ ]: