学习进度笔记
学习进度笔记13
TensorFlow编程基础——实现线性回归
# 载入必要库
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 设置必要参数
## 设置学习率
learning_rate = 0.01
## 设置迭代轮数
training_epochs = 1000
## 每50轮展示当前模型的参数值和损失
display_step = 50
## 每500轮保存一次模型
save_step = 500
# 设定原始数据
## 训练集
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])
# 定义张量占位符
X = tf.placeholder("float", name="X")
Y = tf.placeholder("float", name="Y")
# 定义权重和偏置
with tf.variable_scope("liner_regression"):
# 设置模型的权重和偏置
W = tf.get_variable(initializer=np.random.randn(), name="weight") # 生成权重
b = tf.get_variable(initializer=np.random.randn(), name="bias") # 生成偏置
# 构建线性回归模型(前向传播)
mul = tf.multiply(X, W, name="mul")
pred = tf.add(mul, b, name="pred")
# 建立会话运行程序
with tf.Session() as sess:
# 初始化变量
init_op = tf.global_variables_initializer()
sess.run(init_op)
# 将汇总结果写入文件
file_writer = tf.summary.FileWriter("./temp/summary/linear", graph=sess.graph)
# 拟合训练数据
for epoch in range(training_epochs):
for (x, y) in zip(train_X, train_Y):
# 带入数据
_, summary = sess.run([train_op, merged], feed_dict={X: x, Y: y})
# 保存模型
if (epoch + 1) % save_step == 0:
save_path = saver.save(sess, ckpt_path, global_step=epoch)
print("Model saved in file: %s" % save_path)
# 展示每步训练的日志
if (epoch + 1) % display_step == 0:
# Display loss and value
c = sess.run(loss, feed_dict={X: train_X, Y: train_Y})
print("Epoch:", '%04d' % (epoch+1), "loss=", "{:.9f}".format(c), "W=", W.eval(), "b=", b.eval())
file_writer.add_summary(summary, global_step=epoch)
print("Optimization Finished!")
# 保存最终模型
save_path = saver.save(sess, ckpt_path, global_step=epoch)
print("Final model saved in %s" % save_path)
# 计算最终损失函数
training_loss = sess.run(loss, feed_dict={X: train_X, Y: train_Y})
print("Training loss=", training_loss, "W=", sess.run(W), "b=", sess.run(b), '\n')
# 画图
plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
plt.legend()
plt.show()