import tensorflow as tf
v1 = tf.Variable(tf.random_normal([1,2]), name="v1")
v2 = tf.Variable(tf.random_normal([2,3]), name="v2")
init_op = tf.global_variables_initializer()
saver = tf.train.Saver() #重要
with tf.Session() as sess:
sess.run(init_op)
print ("V1:",sess.run(v1))
print ("V2:",sess.run(v2))
saver_path = saver.save(sess, "save/model.ckpt")
#保存运行数据到 项目文件夹下的save文件夹,取名为model.ckpt
print ("Model saved in file: ", saver_path)
程序1(保存数据)
程序2(读取数据)
import tensorflow as tf
v1 = tf.Variable(tf.random_normal([1,2]), name="v1")
v2 = tf.Variable(tf.random_normal([2,3]), name="v2")
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, "save/model.ckpt")
#从存储的文件里读取数据
print ("V1:",sess.run(v1))
print ("V2:",sess.run(v2))
print ("Model restored")
会发现,第二个程序中新定义的变量并没有起作用。因为从保存的文件里读取数据了。
程序(3):在上次卷积神经网络的程序里加下面的代码,改变do_train,分别完成训练和测试。提前在项目文件夹新建save文件夹,在save下新建nets 文件夹。要不然会报错,差评!!!
ValueError: Parent directory of save2/nets/model.ckpt doesn't exist, can't save.
# SAVER
save_step = 1 # 每隔一次迭代进行一次保存,可以修改
saver = tf.train.Saver(max_to_keep=3) #最大保存三次运行数据,可以修改
do_train = 0
if do_train == 1: # 进行训练
for epoch in range(training_epochs):
#…………
#迭代训练的代码
#…………
if epoch % save_step == 0: #保存数据
saver.save(sess, "save/nets/cnn_mnist_basic.ckpt-" + str(epoch))
if do_train == 0: # 把训练得到的数据拿出来测试
epoch = training_epochs - 1
saver.restore(sess, "save/nets/cnn_mnist_basic.ckpt-" + str(epoch))
test_acc = sess.run(accr, feed_dict={x: testimg, y: testlabel, keepratio: 1.})
print(" TEST ACCURACY: %.3f" % (test_acc))
结果如下:用CPU跑的,小米平板,一直在呼呼的响,有点怕怕~~害怕它爆了(哭脸)
2018-12-11 21:36:13.018800: W tensorflow/core/framework/allocator.cc:122] Allocation of 2007040000 exceeds 10% of system memory.(这一条是红色的,出现了5次,吓死宝宝了)
TEST ACCURACY: 0.905