本文主要是介绍1.tensorflow线性回归示例:保存模型,载入模型,打印模型参数,修改模型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#coding:utf-8
'''
a liner regression by tenosrflow.
input dimension: 1, output dimension: 1.
显示每个epoch的loss
利用模型预测
保存模型
载入模型
打印模型中的参数
修改模型中的参数
'''
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file# data
x_train = np.linspace(-1, 1, 100)
y_train = 10 * x_train + np.random.randn(x_train.shape[0])
# plt.plot(x_train, y_train, "ro", label="data")
# plt.legend()
# plt.show()epochs = 30
display_step = 2
# input, output
x = tf.placeholder(dtype="float", name="input")
y = tf.placeholder(dtype="float", name="label")
# w, b
w = tf.Variable(initial_value=tf.random_normal([1]), name="weight")
b = tf.Variable(initial_value=tf.zeros([1]), name="bias")
# model
z = tf.multiply(x, w) + b
# loss functon
cost = tf.reduce_mean(tf.square(y - z))
# optimizer
optim = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)
saver = tf.train.Saver(max_to_keep=4) # save 4 model
init = tf.global_variables_initializer()
with tf.Session() as sess:sess.run(init)for epoch in range(epochs):for x_batch, y_batch in zip(x_train, y_train): # batch is all data theresess.run(optim, feed_dict={x:x_batch, y:y_batch})if epoch % display_step ==0:loss = sess.run(cost, feed_dict={x:x_train, y:y_train})print("epoch: %d, loss: %d" %(epoch, loss))# 保存训练过程中的模型saver.save(sess, "line_regression_model/regress.cpkt", global_step=epoch)print("train finished...")# 保存最终的模型saver.save(sess, "line_regression_model/regress.cpkt")print("final loss:", sess.run(cost, feed_dict={x:x_train, y:y_train}))print("weight:", sess.run(w))print("bias:", sess.run(b))# show train data and predict dataplt.plot(x_train, y_train, "ro", label="train")predict = sess.run(w) * x_train + sess.run(b)plt.plot(x_train, predict, "b", label="predict")plt.legend()plt.show()# 载入模型
print("*"*50)
saver = tf.train.Saver()
with tf.Session() as sess2:sess2.run(tf.global_variables_initializer())saver.restore(sess2, "line_regression_model/regress.cpkt")print(sess2.run(w))print(sess2.run(b))predict2 = sess2.run(z, feed_dict={x:0.5})print(predict2)# 打印出模型中的变量及参数
print("-"*50)
print("the params in model:")
print_tensors_in_checkpoint_file("line_regression_model/regress.cpkt", None, True)# 修改模型中的参数,并重新保存
print("-"*50)
# 以上得到了模型中参数名字为weight,bias, 下面对他们进行修改
w_change = tf.Variable(10, name="weight")
b_change = tf.Variable(0.001, name="bias")
# 把他们放到一个字典里并写在saver里
saver = tf.train.Saver({"weighs":w_change, "bias":b_change})
with tf.Session() as sess3:sess3.run(tf.global_variables_initializer())# 保存修改后的参数saver.save(sess3, "line_regression_model/regress.cpkt")
# 发现参数已经被修改
print_tensors_in_checkpoint_file("line_regression_model/regress.cpkt", None, True)
输出:
/usr/local/bin/python2.7 /Users/ming/Downloads/zhangming/tf_demo/liner_regression.py
2018-11-17 16:07:32.138907: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
epoch: 0, loss: 21
epoch: 2, loss: 2
epoch: 4, loss: 1
epoch: 6, loss: 1
epoch: 8, loss: 1
epoch: 10, loss: 1
epoch: 12, loss: 1
epoch: 14, loss: 1
epoch: 16, loss: 1
epoch: 18, loss: 1
epoch: 20, loss: 1
epoch: 22, loss: 1
epoch: 24, loss: 1
epoch: 26, loss: 1
epoch: 28, loss: 1
train finished...
('final loss:', 1.0535882)
('weight:', array([10.063329], dtype=float32))
('bias:', array([0.03052005], dtype=float32))
**************************************************
[10.063329]
[0.03052005]
[5.0621843]
--------------------------------------------------
the params in model:
tensor_name: bias
[0.03052005]
tensor_name: weight
[10.063329]
--------------------------------------------------
tensor_name: bias
0.001
tensor_name: weighs
10
这篇关于1.tensorflow线性回归示例:保存模型,载入模型,打印模型参数,修改模型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!