import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
def moving_average(a,w=10):
if(len(a)<w):
return a[:]
return [val if idx <w else sum(a[idx-w:idx])/w for idx,val in enumerate(a)]
X_train=np.linspace(-1,1,100)
Y_train=2*X_train+np.random.randn(*X_train.shape)*0.3
X=tf.placeholder('float')
Y=tf.placeholder('float')
W=tf.Variable(tf.random_normal([1]),name='weight')
b=tf.Variable(tf.zeros([1]),name='bias')
z=tf.multiply(X,W)+b
loss=tf.reduce_mean(tf.square(Y-z))
learn_rate=0.01
optimizer=tf.train.GradientDescentOptimizer(learn_rate).minimize(loss)
init=tf.global_variables_initializer()
training_epochs=20
display_step=2
with tf.Session() as sess:
sess.run(init)
plot_data={'batch_size':[],'loss_value':[]}
for epoch in range(training_epochs):
for x,y in zip(X_train,Y_train):
sess.run(optimizer,feed_dict={X:x,Y:y})
if epoch % display_step == 0:
loss_value = sess.run(loss, feed_dict={X:x, Y:y})
print('Epoch:', epoch + 1, 'Loss=', loss_value, 'w=',sess.run(W),'b=',sess.run(b))
if not (loss == 'NA'):
plot_data['batch_size'].append(epoch)
plot_data['loss_value'].append(loss_value)
print('Finished!')
plt.plot(X_train, Y_train, 'ro', label='Origin data')
plt.plot(X_train, sess.run(W) * X_train + sess.run(b),label='FittedLine')
plt.legend()
plt.show()
plot_data['avgloss']=moving_average(plot_data['loss_value'])
plt.figure(1)
plt.subplot(211)
plt.plot(plot_data['batch_size'],plot_data['avgloss'],'b',linewidth=1.5)
plt.xlabel('Minbatch number')
plt.ylabel('Loss')
plt.title('Minibatch run vs Training loss')
plt.show()