In [1]:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
%matplotlib inline
In [2]:
np.random.seed(101)
tf.set_random_seed(101)
In [3]:
x_data = np.linspace(0, 10, 10) + np.random.uniform(-1.5, 1.5, 10)
In [4]:
x_data
Out[4]:
In [5]:
y_label = np.linspace(0, 10, 10) + np.random.uniform(-1.5, 1.5, 10)
In [6]:
plt.plot(x_data,
y_label,
'*')
Out[6]:
Variables
In [7]:
np.random.rand(2)
Out[7]:
In [8]:
m = tf.Variable(0.39)
b = tf.Variable(0.2)
In [9]:
error = tf.reduce_mean(y_label - (m * x_data + b))
In [10]:
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.0005)
train = optimizer.minimize(error)
In [11]:
init = tf.global_variables_initializer()
In [12]:
saver = tf.train.Saver()
In [13]:
with tf.Session() as sess:
sess.run(init)
epochs = 300
for i in range(epochs):
sess.run(train)
# Fetch Back Results
final_slope , final_intercept = sess.run([m,b])
# Save the checkpoint
saver.save(sess,'new_models/my_second_model.ckpt')
In [14]:
x_test = np.linspace(-1, 11, 10)
y_pred_plot = final_slope * x_test + final_intercept
plt.plot(x_test, y_pred_plot,'r')
plt.plot(x_data, y_label,'*')
Out[14]:
In [15]:
with tf.Session() as sess:
# Restore the model
saver.restore(sess,'new_models/my_second_model.ckpt')
# Fetch Back Results
restored_slope, restored_intercept = sess.run([m,b])
In [16]:
print(restored_slope)
In [17]:
print(restored_intercept)
In [18]:
x_test = np.linspace(-1, 11, 10)
y_pred_plot = restored_slope * x_test + restored_intercept
plt.plot(x_test,y_pred_plot,'r')
plt.plot(x_data,y_label,'*')
Out[18]: