(三)Tensorflow神经网络之模型载入及迁移学习

模型参照:Tensorflow神经网络模型持久化

1 载入模型获取模型变量

  • 源码Demo
import tensorflow as tf
import os
# 保存模型
def saveModel():
	MODEL_SAVE_PATH = './models'
	MODEL_NAME = 'model.ckpt'
	v1 = tf.Variable(tf.constant(2.0, shape=[1]), name='v1')
	v2 = tf.Variable(tf.constant(2.0, shape=[1]), name='v2')
	result = v1 + v2
	# 添加模型图变量
	tf.add_to_collection('result', result)
	saver = tf.train.Saver()
	with tf.Session() as sess:
		init_op = tf.global_variables_initializer()
		sess.run(init_op)
		saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME))
# 
def loadModel():
	with tf.Session() as sess:
		# 加载模型的图
		saver = tf.train.import_meta_graph("models/model.ckpt.meta")
		# 加载保存的模型
		saver.restore(sess, tf.train.latest_checkpoint('models/'))
		# 获取新增模型变量
		res = tf.get_collection('result')[0]
		print("Load model to get variable v1: {}".format(sess.run('v1:0')))
		print("Load model to get variable v2: {}".format(sess.run('v2:0')))
		print("Load model to get varaible result: {}".format(sess.run(res)))
# 保存模型
saveModel()
# 载入模型
loadModel()
  • 结果
Load model to get variable v1: [2.]
Load model to get variable v2: [2.]
Load model to get varaible result: [4.]

2 载入蛇精网络模型

import tensorflow as tf 
import numpy as np 
import matplotlib.pyplot as plt

x_data = np.linspace(-1, 1, 250, dtype=np.float32)[:, np.newaxis] 
noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5*x_data + noise

def loadModel():
	with tf.Session() as sess:
		# 载入模型,获取模型图graph及变量值
		saver = tf.train.import_meta_graph('models/model.ckpt-299.meta')
		# 载入模型变量
		saver.restore(sess, tf.train.latest_checkpoint('models/'))

3 迁移学习

# 获取新增变量
pre = tf.get_collection('prediction')[0]
# 获取输入变量
graph = tf.get_default_graph()
x = graph.get_operation_by_name('x').outputs[0]
y = graph.get_operation_by_name('y').outputs[0]
predictionModel = sess.run(pre, feed_dict={x: x_data, y: y_data})
plt.ion()
plt.title("Load Model for Transfer Training")
plt.scatter(x_data, y_data, s=2, c='b', label='Real')
plt.plot(x_data, predictionModel, 'r', label='Predict')
plt.legend(loc='upper right')
plt.xlabel("x/cm")
plt.ylabel('Prediction&Reality/cm')
plt.show()
plt.savefig('images/loadModelPredict.png', format='png')

完整代码:GitHub

4 学习结果

(三)Tensorflow神经网络之模型载入及迁移学习_第1张图片

图3.1 学习结果

4 总结

  • 载入模型并获取模型结构及参数;
  • 建立输出新增变量并获取该变量;
  • 建立输入变量并获取;
  • 计算;

[参考文献]
[1]https://blog.csdn.net/liweibin1994/article/details/78307382


你可能感兴趣的:(Ai-image,Tensorflow)