Tensorflow学习教程------参数保存和提取重利用

#coding:utf-8 import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data',one_hot=True) #每个批次的大小
batch_size = 100 n_batch = mnist.train._num_examples // batch_size def weight_variable(shape):
initial = tf.truncated_normal(shape,stddev=0.1) #生成一个截断的正态分布
return tf.Variable(initial) def bias_variable(shape):
initial = tf.constant(0.1,shape = shape)
return tf.Variable(initial) #卷基层
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')
#定义两个placeholder
x = tf.placeholder(tf.float32, [None,784])
y = tf.placeholder(tf.float32,[None,10]) #改变x的格式转为4D的向量[batch,in_height,in_width,in_channels]
x_image = tf.reshape(x, [-1,28,28,1]) #初始化第一个卷基层的权值和偏置
W_conv1 = weight_variable([5,5,1,32]) #5*5的采样窗口 32个卷积核从一个平面抽取特征 32个卷积核是自定义的
b_conv1 = bias_variable([32]) #每个卷积核一个偏置值 #把x_image和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
h_pool1 = max_pool_2x2(h_conv1) #进行max-pooling #初始化第二个卷基层的权值和偏置
W_conv2 = weight_variable([5,5,32,64]) # 5*5的采样窗口 64个卷积核从32个平面抽取特征 由于前一层操作得到了32个特征图
b_conv2 = bias_variable([64]) #每一个卷积核一个偏置值 #把h_pool1和权值向量进行卷积 再加上偏置值 然后应用于relu激活函数
h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2) #进行max-pooling #28x28的图片第一次卷积后还是28x28 第一次池化后变为14x14
#第二次卷积后 变为14x14 第二次池化后变为7x7
#通过上面操作后得到64张7x7的平面 #初始化第一个全连接层的权值
W_fc1 = weight_variable([7*7*64,1024])#上一层有7*7*64个神经元,全连接层有1024个神经元
b_fc1 = bias_variable([1024]) #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) #keep_prob用来表示神经元的输出概率
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob) #初始化第二个全连接层
W_fc2 = weight_variable([1024,10])
b_fc2 = bias_variable([10]) #计算输出
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2) #交叉熵代价函数
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction)) #使用AdamOptimizer进行优化
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#结果存放在一个布尔列表中
correct_prediction = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1)) #argmax返回一维张量中最大的值所在的位置
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(13):
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,keep_prob:0.7})
acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0})
print ("Iter "+ str(epoch) + ", Testing Accuracy= " + str(acc))
saver.save(sess,save_path='/home/bayes/logs/mnist_net.ckpt')

提取保存的参数进行准确率验证

#coding:utf-8 import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data',one_hot=True) #每个批次的大小
batch_size = 100 n_batch = mnist.train._num_examples // batch_size def weight_variable(shape):
initial = tf.truncated_normal(shape,stddev=0.1) #生成一个截断的正态分布
return tf.Variable(initial) def bias_variable(shape):
initial = tf.constant(0.1,shape = shape)
return tf.Variable(initial) #卷基层
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')
#定义两个placeholder
x = tf.placeholder(tf.float32, [None,784])
y = tf.placeholder(tf.float32,[None,10]) #改变x的格式转为4D的向量[batch,in_height,in_width,in_channels]
x_image = tf.reshape(x, [-1,28,28,1]) #初始化第一个卷基层的权值和偏置
W_conv1 = weight_variable([5,5,1,32]) #5*5的采样窗口 32个卷积核从一个平面抽取特征 32个卷积核是自定义的
b_conv1 = bias_variable([32]) #每个卷积核一个偏置值 #把x_image和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
h_pool1 = max_pool_2x2(h_conv1) #进行max-pooling #初始化第二个卷基层的权值和偏置
W_conv2 = weight_variable([5,5,32,64]) # 5*5的采样窗口 64个卷积核从32个平面抽取特征 由于前一层操作得到了32个特征图
b_conv2 = bias_variable([64]) #每一个卷积核一个偏置值 #把h_pool1和权值向量进行卷积 再加上偏置值 然后应用于relu激活函数
h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2) #进行max-pooling #28x28的图片第一次卷积后还是28x28 第一次池化后变为14x14
#第二次卷积后 变为14x14 第二次池化后变为7x7
#通过上面操作后得到64张7x7的平面 #初始化第一个全连接层的权值
W_fc1 = weight_variable([7*7*64,1024])#上一层有7*7*64个神经元,全连接层有1024个神经元
b_fc1 = bias_variable([1024]) #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) #keep_prob用来表示神经元的输出概率
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob) #初始化第二个全连接层
W_fc2 = weight_variable([1024,10])
b_fc2 = bias_variable([10]) #计算输出
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2) #交叉熵代价函数
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction)) #使用AdamOptimizer进行优化
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#结果存放在一个布尔列表中
correct_prediction = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1)) #argmax返回一维张量中最大的值所在的位置
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print (sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0}))
saver.restore(sess, '/home/bayes/logs/mnist_net.ckpt')
print (sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0}))

结果 初始化后没有经过训练的参数准确率低 训练后从模型中提取的参数准确率高
I tensorflow/core/common_runtime/gpu/gpu_device.cc:906] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_device.cc:916] 0: Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:03:00.0)
0.1117
0.9893
Tensorflow学习教程------参数保存和提取重利用的更多相关文章
- tensorflow学习之路----保存和提取数据
#保存数据注意他只能保存变量,不能保存神经网络的框架.#保存数据的作用:保存权重有利于下一次的训练,或者可以用这个数据进行识别#np.arange():arange函数用于创建等差数组,使用频率非常高 ...
- Tensorflow学习教程------过拟合
Tensorflow学习教程------过拟合 回归:过拟合情况 / 分类过拟合 防止过拟合的方法有三种: 1 增加数据集 2 添加正则项 3 Dropout,意思就是训练的时候隐层神经元每次随机 ...
- Tensorflow学习教程------代价函数
Tensorflow学习教程------代价函数 二次代价函数(quadratic cost): 其中,C表示代价函数,x表示样本,y表示实际值,a表示输出值,n表示样本的总数.为简单起见,使用一 ...
- Tensorflow学习教程------读取数据、建立网络、训练模型,小巧而完整的代码示例
紧接上篇Tensorflow学习教程------tfrecords数据格式生成与读取,本篇将数据读取.建立网络以及模型训练整理成一个小样例,完整代码如下. #coding:utf-8 import t ...
- TensorFlow学习笔记:保存和读取模型
TensorFlow 更新频率实在太快,从 1.0 版本正式发布后,很多 API 接口就发生了改变.今天用 TF 训练了一个 CNN 模型,结果在保存模型的时候居然遇到各种问题.Google 搜出来的 ...
- tensorflow 学习教程
tensorflow 学习手册 tensorflow 学习手册1:https://cloud.tencent.com/developer/section/1475687 tensorflow 学习手册 ...
- Tensorflow学习教程------模型参数和网络结构保存且载入,输入一张手写数字图片判断是几
首先是模型参数和网络结构的保存 #coding:utf-8 import tensorflow as tf from tensorflow.examples.tutorials.mnist impor ...
- Tensorflow学习教程------tfrecords数据格式生成与读取
首先是生成tfrecords格式的数据,具体代码如下: #coding:utf-8 import os import tensorflow as tf from PIL import Image cw ...
- Tensorflow学习教程------创建图启动图
Tensorflow作为目前最热门的机器学习框架之一,受到了工业界和学界的热门追捧.以下几章教程将记录本人学习tensorflow的一些过程. 在tensorflow这个框架里,可以讲是若数据类型,也 ...
随机推荐
- 从ofo到乐视,变卖资产好过冬靠谱吗?
今年年底,有很多人"被迫"离职.他们为了应对生活压力和找工作的不确定性,尝试在二手平台上卖出自己的奢侈品或心爱之物,以期度过潜在的难关.而对于很多企业来说,这个冬天也非常冷.依靠常 ...
- git 的那点东西,随心记
目前常用的项目版本管理,协同开发的工具有SVN和GIT,本次就记录一下GIT的基本使用. git下载地址:https://git-scm.com/downloads *根据自己的操作系统进行选择(这里 ...
- chromedriver版本问题
最新的chromedriver 66.0.3359.117 的对应chromedriver版本为2.38 http://npm.taobao.org/mirrors/chromedriver/ Web ...
- Redis详解(八)——企业级解决方案
Redis详解(八)--企业级解决方案 缓存预热 缓存预热就是系统上线后,提前将相关的缓存数据直接加载到缓存系统.避免在用户请求的时候,先查询数据库,然后再将数据缓存的问题!用户直接查询事先被预热的缓 ...
- javascript判断数组是否包含了指定的元素
jQuery写法: var arr = [ "xml", "html", "css", "js" ]; $.inArra ...
- openalyser6学习
1.安装nvm.nvm下载地址:https://github.com/coreybutler/nvm-windows/releases使用nvm-setup安装和下载nodejs:https://ww ...
- Golang的选择结构-if语句
Golang的选择结构-if语句 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.选择语句应用场景概述 选择结构也称为条件判断,生活中关于判断的场景也非常的多,比如: ()登录Q ...
- 我的Java语言学习日志1_"简单的银行管理系统实现"
设计步骤:注意:本篇代码,直接建两个类( Bank_Account.BankManage)在BankManage往里面填方法就行.是为了让和我一样自学朋友可以更快的接受.但是代码优化的空间还是很大的( ...
- 《新标准C++程序设计》3.6-3.7(C++学习笔记9)
一.成员对象和封闭类 (1)定义 一个类的成员变量如果是另一个类的对象,就称之为“成员对象”. 包含成员对象的类叫封闭类. (2)封闭类构造函数的初始化列表 在构造函数中添加初始化列表的写法: 类名: ...
- centos7下使用yum安装ifconfig工具
步骤1:搜索安装包 步骤2:使用yum安装 至此,ifconfig工具安装完毕,希望对你有帮助~