1、
import tensorflow as tf
import numpy as np
isTrain = True
train_steps = 100
checkpoint_steps = 50
checkpoint_dir = '/home/jdlu/jdluTensor/test/tmp/'
x = tf.placeholder(tf.float32, shape=[None, 1])
y = 4 * x + 4
w = tf.Variable(tf.random_normal([1], -1, 1))
b = tf.Variable(tf.zeros([1]))
y_predict = w * x + b
loss = tf.reduce_mean(tf.square(y - y_predict))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
isTrain = False
train_steps = 100
checkpoint_steps = 50
checkpoint_dir = ''
saver = tf.train.Saver() # defaults to saving all variables - in this case w and b
x_data = np.reshape(np.random.rand(10).astype(np.float32), (10, 1))
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
if isTrain:
for i in xrange(train_steps):
sess.run(train, feed_dict={x: x_data})
if (i + 1) % checkpoint_steps == 0:
saver.save(sess, checkpoint_dir + 'model.ckpt', global_step=i+1)
else:
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
else:
pass
print(sess.run(w))
print(sess.run(b))
训练的过程:
1、先设置isTrain=True,然后会保存模型,设置isTrain=False会将训练好的模型加载进来进行测试
2、train_steps:表示训练的次数,例子中使用100
3、checkpoint_steps:表示训练多少次保存一下checkpoints,例子中使用50
4、checkpoint_dir:表示checkpoints文件的保存路径,例子中使用当前路径
if isTrain:
for i in xrange(train_steps):
sess.run(train, feed_dict={x: x_data})
if (i + 1) % checkpoint_steps == 0:
saver.save(sess, checkpoint_dir + 'model.ckpt',global_step = i+1)
说明:每训练checkpoint_steps就保存一次模型,在训练的过程中,就可以多次保存模型。
测试的过程:
1、测试的过程就是加载训练模型好的模型
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
else:
pass
print(sess.run(w))
print(sess.run(b))
说明:
checkpoint的文件内容:
保存model的路径下的文件内容:
saver.save(sess, checkpoint_dir + 'model.ckpt',global_step = i+1)
==================================================================================================================