1 保存和恢复模型
1.1保存模型
tf.train.Saver()函数可以建立一个saver对象,然后在session中调用save即可将模型保存起来。
# 导入tensorflow类库
import tensorflow as tfv1 = tf.Variable(tf.constant([[5.0, 6.0], [7.0, 7.0]], shape=[2, 2]), name="m1")
v2 = tf.Variable(tf.constant([[4.0, 6.0], [7.0, 8.0]], shape=[2, 2]), name="m2")
result = v1 + v2
saver = tf.train.Saver()
init_op = tf.global_variables_initializer()
with tf.Session() as sess:sess.run(init_op)saver.restore(sess, "model/model.ckpt")print(sess.run(result))
会产生四个文件:
1.2 载入模型
saver.restore()
通过tf.train.import_meta_graph直接加载计算图,获得模型的输出结果。
import tensorflow as tf# 通过tf.train.import_meta_graph,直接加载持久化的图
saver = tf.train.import_meta_graph("model/model.ckpt.meta")
with tf.Session()as sess:# saver.restore在当前会话中还原模型saver.restore(sess, 'model/model.ckpt')print("m1", sess.run(tf.get_default_graph().get_tensor_by_name('m1:0')))print("m2", sess.run(tf.get_default_graph().get_tensor_by_name('m2:0')))print(sess.run(tf.get_default_graph().get_tensor_by_name('add:0')))
2 使用模型预测
使用模型预测步骤:
import tensorflow.compat.v1 as tf# 加载计算图,不加载参数
saver = tf.train.import_meta_graph('predict/predict_model.ckpt.meta')
with tf.Session()as sess:# 加载x节点input_x = sess.graph.get_tensor_by_name('x:0')# 加载y节点input_y = sess.graph.get_tensor_by_name('y:0')# 获得矩阵相乘操作mul_result = sess.graph.get_tensor_by_name('mul_result:0')# 向节点喂入数据,获得输出结果result = sess.run(mul_result, feed_dict={input_x: [[2, 3, 4], [2, 3, 4]], input_y: [[1, 2, 3], [3, 5, 5]]})print("矩阵乘法结果:", result)
3 构建二维线性拟合模型
步骤:
3.1准备数据
随机产生数据:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt#准备数据
train_x=np.linspace(-1,1,100)
train_y=2*train_x + np.random.randn(*train_x.shape)*0.5
plt.plot(train_x,train_y,'ro',label="原始数据集")
plt.show()
3.2 搭建模型
###搭建模型
x=tf.placeholder(dtype=tf.float32)
y=tf.placeholder(dtype=tf.float32)
w=tf.Variable(tf.random_normal([1]),name='weight')
b=tf.Variable(tf.zeros([1]),name='bias')
z=tf.multiply(x,w)+b
3.3 反向传播
###反向传播
cost=tf.reduce_mean(tf.square(y-z))#均方误差
learning_rate=0.05
optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)#优化器采用随机梯度下降算法
3.4 迭代训练模型
###迭代训练模型
training_epochs=100
display_step=10
saver=tf.train.Saver()
with tf.Session() as sess:sess.run(tf.global_variables_initializer())for epoch in range(training_epochs): #向模型中输入数据for (x_data,y_data) in zip(train_x,train_y):sess.run(optimizer,feed_dict={x:x_data,y:y_data})if epoch % display_step ==0:loss=sess.run(cost,feed_dict={x:x_data,y:y_data})print('Epoch:',epoch+1,'cost:',loss)saver.save(sess,save_path="linear/linear.ckpt")#保存模型
3.5 模型预测
###模型预测
with tf.Session() as sess:saver.restore(sess,"linear/linear.ckpt")print("模型的预测值为:",sess.run(z,feed_dict={x:0.6}))
模型的预测值为: [1.2711029]