Tensorflow模型保存和模型使用

1 模型保存

TensorFlow提供了一个非常方便的api,tf.train.Saver()来保存和还原一个机器学习模型。程序会生成并保存四个文件:

  1. checkpoint 文本文件,记录了模型文件的路径信息列表
  2. mnist-10000.data-00000-of-00001网络权重信息
  3.  mnist-10000.index  .data和.index这两个文件是二进制文件,保存了模型中的变量参数(权重)信息
  4. mnist-10000.meta 二进制文件,保存了模型的计算图结构信息(模型的网络结构)protobuf

看下保存LeNet模型的例子:

#coding=utf-8

import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "2"

isTrain = True
#导入数据,创建一个session对象 ,之后的运算都会跑在这个session里
mnist = input_data.read_data_sets("MNIST/",one_hot=True)
sess = tf.InteractiveSession()

#定义一个函数,用于初始化所有的权值 W,这里我们给权重添加了一个截断的正态分布噪声 标准差为0.1
def weight_variable(shape):
    initial = tf.truncated_normal(shape,stddev=0.1)
    return tf.Variable(initial)

#定义一个函数,用于初始化所有的偏置项 b,这里给偏置加了一个正值0.1来避免死亡节点
def bias_variable(shape):
    inital = tf.constant(0.1,shape=shape)
    return tf.Variable(inital)

#定义一个函数,用于构建卷积层,这里strides都是1 代表不遗漏的划过图像的每一个点
def conv2d(x,w):
    return tf.nn.conv2d(x,w,strides=[1,1,1,1],padding='SAME')

#定义一个函数,用于构建池化层
def max_pool_2x2(x):
    return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')


#placceholder 基本都是用于占位符 后面用到先定义
x = tf.placeholder(tf.float32,[None,784],name="x")
y_ = tf.placeholder(tf.float32,[None,10],name="y_")
x_image = tf.reshape(x,[-1,28,28,1])                                #将数据reshape成适合的维度来进行后续的计算

#第一个卷积层的定义
W_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1) + b_conv1)                #激活函数为relu
h_pool1 = max_pool_2x2(h_conv1)                                        #2x2 的max pooling

#第二个卷积层的定义
W_conv2 = weight_variable([5,5,32,64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

#第一个全连接层的定义
W_fc1 = weight_variable([7*7*64,1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1) + b_fc1)

#将第一个全连接层 进行dropout 随机丢掉一些神经元不参与运算
keep_prob = tf.placeholder(tf.float32,name="keep_prob")
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)

#第二个全连接层 分为十类数据 softmax后输出概率最大的数字
W_fc2 = weight_variable([1024,10])
b_fc2 = bias_variable([10])
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2,name="y_conv")


# 创建saver的时候可以指明要存储的tensor,如果不指明,就会全部存下来
#saves a model every 2 hours and maximum 4 latest models are saved.
saver = tf.train.Saver(max_to_keep=4)

#保存模型的路劲
ckpt_file_path = "./models/mnist"
path = os.path.dirname(os.path.abspath(ckpt_file_path))
if os.path.isdir(path) is False:
    os.makedirs(path)


cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv),reduction_indices=[1]))        #交叉熵
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)                                #这里用Adam优化器 优化 也可以使用随机梯度下降

#cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv),reduction_indices=[1])   #交叉熵
#train_step = tf.train.GradientDescentOptimizer(0.5*1e-4).minimize(cross_entropy)

correct_predition = tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_predition,tf.float32))                                #准确率

tf.initialize_all_variables().run()                                                                #使用全局参数初始化器 并调用run方法 来进行参数初始化

for i in range(20000):
    batch = mnist.train.next_batch(50)
    if i%100 == 0:
        train_accuracy = accuracy.eval(feed_dict={x:batch[0],y_:batch[1],keep_prob:1.0})        #每一百次验证一下准确率
        print "step %d,training accuracy %g"%(i,train_accuracy)
    if i%1000 == 0:
        tf.train.Saver().save(sess, ckpt_file_path,write_meta_graph=True)

    train_step.run(feed_dict={x:batch[0],y_:batch[1],keep_prob:0.5})                            #batch[0]   [1] 分别指数据维度 和标记维度 将数据传入定义好的优化器进行训练

print "test accuracy %g"%accuracy.eval(feed_dict={x:mnist.test.images,y_:mnist.test.labels,keep_prob:0.5})    #开始测试数据
train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})  

2 使用模型

使用训练好的LeNet模型例子:

#coding:utf8
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
#导入数据,创建一个session对象 ,之后的运算都会跑在这个session里
mnist = input_data.read_data_sets("MNIST/",one_hot=True)
sess = tf.Session()

#加载模型
saver = tf.train.import_meta_graph('./models/mnist.meta')
saver.restore(sess, tf.train.latest_checkpoint('./models'))


graph = tf.get_default_graph()
x_ = graph.get_tensor_by_name("x:0")
keep_prob_ = graph.get_tensor_by_name("keep_prob:0")

# Now, access the op that you want to run.
y_ = graph.get_tensor_by_name("y_conv:0")



for i in range(20):
    batch = mnist.train.next_batch(1)
    #预测
    y_conv =  sess.run(y_,feed_dict={x_: batch[0],keep_prob_:0.5})  #
    correct_predition = tf.equal(tf.argmax(y_conv, 1), tf.argmax(batch[1], 1))
    print correct_predition.eval(session=sess)

 

  • 7
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值