tensorflow 学习笔记(2)-basic_example
- linear_regression
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
train_epochs = 1000 # the step of epoch
diaplay_step = 50
learn_rate = 0.01 # the learning rate of GradientDescentOptimizer
# the data set of training
train_x=np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1])
train_y=np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3])
# tf graph input
X = tf.placeholder("float")
Y = tf.placeholder("float")
n_sample = train_x.shape[0]
# set model weights
W = tf.Variable(np.random.randn(), name = "weight")
b = tf.Variable(np.random.randn(), name = "bias")
# construct a linear model
pred = tf.add(tf.multiply(X, W), b)
# MSE
cost = tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * n_sample)
optimizer=tf.train.GradientDescentOptimizer(learn_rate).minimize(cost)
init = tf.global_variables_initializer()# Initializing the variables
with tf.Session() as sess:
sess.run(init)
for epoch in range(train_epochs):
for (x, y) in zip(train_x, train_y):
sess.run(optimizer, feed_dict = {X: x, Y: y})
if (epoch + 1) % 50 == 0:
c = sess.run(cost, feed_dict = {X: train_x, Y: train_y})
print("Epoch: ", epoch + 1, "cost = ", c , "W = ", sess.run(W), "b = ", sess.run(b))
print("Optimization Finished!")
train_cost = sess.run(cost, feed_dict = {X: train_x, Y: train_y})
print("Training cost = ", train_cost, "W = ", sess.run(W), "b = ", sess.run(b),'\n')
# Graphic display
plt.plot(train_x, train_y, 'ro', label = "Original data")
plt.plot(train_x, train_x * sess.run(W) + sess.run(b), label = "Fitted line")
plt.legend()
plt.show()
# Testing example,
test_x = numpy.asarray([6.83, 4.668, 8.9, 7.91, 5.7, 8.7, 3.1, 2.1])
test_y = numpy.asarray([1.84, 2.273, 3.2, 2.831, 2.92, 3.24, 1.35, 1.03])
print("Testing... (Mean square loss Comparison)")
test_cost = sess.run(tf.reduce_sum(tf.pow(pred - Y, 2))/(2 * test_x.shape[0]), feed_dict = {X:test_x,Y:test_y})
print("Testing cost: ", test_cost)
print("Absolute mean square loss difference: ",abs( test_cost - train_cost))
# Graphic display
plt.plot(test_x, test_y, "bo", label = "Testing data")
plt.plot(test_x, test_x * sess.run(W) + sess.run(b),label = "Fitted line")
plt.legend()
plt.show()