tensorflow 训练保存模型

训练模型:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#mnist已经作为官方的例子,做好了数据下载,分割,转浮点等一系列工作,源码在tensorflow源码中都可以找到
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# 配置每个 GPU 上占用的内存的比例
# 没有GPU直接sess = tf.Session()
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

#每个批次的大小
batch_size = 20
#定义训练轮数据
train_epoch = 10
#定义每n轮输出一次
test_epoch_n = 1

#计算一共有多少批次
n_batch = mnist.train.num_examples // batch_size
print("batch_size="+str(batch_size)+"n_batch="+str(n_batch))

#占位符,定义了输入,输出
x = tf.placeholder(tf.float32,[None, 784]) 
y_ = tf.placeholder(tf.float32,[None, 10]) 
#权重和偏置,使用0初始化
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

#这里定义的网络结构
y = tf.matmul(x,W) + b

#损失函数是交叉熵
#cross_entropy = -tf.reduce_sum(y_*tf.log(y))
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_,logits=y))
#训练方法:
#train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
train_step = tf.train.AdamOptimizer(1e-2).minimize(cross_entropy)

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 

#初始化sess中所有变量
init = tf.global_variables_initializer() 
sess.run(init) 
#打印出需要tensor的名字
print(x)
print(y_)
print(accuracy)

MaxACC = 0#最好的ACC
saver = tf.train.Saver()  

#训练n个epoch
for epoch in range(train_epoch): 
    for batch in range(n_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size) 
        sess.run(train_step, feed_dict = {x: batch_xs, y_: batch_ys}) 
    if(0==(epoch%test_epoch_n)):#每若干次预测test一次
        #计算test集的准确率
        correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
        now_acc=sess.run(accuracy, feed_dict={x:mnist.test.images, y_: mnist.test.labels})
        print('epoch=',epoch,'ACC=',now_acc)
        if(now_acc>MaxACC):
            MaxACC = now_acc
            saver.save(sess, "Model/ModelSoftmax.ckpt")  
            print('Save model! Now ACC=',MaxACC)

#计算最终test集的准确率
print('Train OK! epoch=',epoch,'ACC=',sess.run(accuracy, feed_dict={x:mnist.test.images, y_: mnist.test.labels}))

#关闭sess
sess.close()

读取模型:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#mnist已经作为官方的例子,做好了数据下载,分割,转浮点等一系列工作,源码在tensorflow源码中都可以找到
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# 配置每个 GPU 上占用的内存的比例
# 没有GPU直接sess = tf.Session()
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

#每个批次的大小
batch_size = 20
#定义训练轮数据
train_epoch = 100
#定义每n轮输出一次
test_epoch_n = 1

#计算一共有多少批次
n_batch = mnist.train.num_examples // batch_size
print("batch_size="+str(batch_size)+"n_batch="+str(n_batch))

saver = tf.train.import_meta_graph("./Model/ModelSoftmax.ckpt.meta")
saver.restore(sess, "./Model/ModelSoftmax.ckpt") # 注意此处路径前添加"./"  
print('Load Model OK!')
print('ACC=',sess.run("Mean_1:0", feed_dict={"Placeholder:0":mnist.test.images,"Placeholder_1:0": mnist.test.labels}))

这里tensor的名字我是在训练的时候打印出来的,
那么剩下的问题是:如果我只有一个模型的文件,那么我怎么知道每个tesnor的名字,整个网络的结构呢?

猜你喜欢

转载自blog.csdn.net/masbbx123/article/details/80773057