1. #coding:utf-8
  2.  
  3. import tensorflow as tf
  4. from tensorflow.examples.tutorials.mnist import input_data
  5.  
  6. mnist = input_data.read_data_sets('MNIST_data',one_hot=True)
  7.  
  8. #每个批次的大小
  9. batch_size = 100
  10.  
  11. n_batch = mnist.train._num_examples // batch_size
  12.  
  13. def weight_variable(shape):
  14. initial = tf.truncated_normal(shape,stddev=0.1) #生成一个截断的正态分布
  15. return tf.Variable(initial)
  16.  
  17. def bias_variable(shape):
  18. initial = tf.constant(0.1,shape = shape)
  19. return tf.Variable(initial)
  20.  
  21. #卷基层
  22. def conv2d(x,W):
  23. return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
  24. #池化层
  25. def max_pool_2x2(x):
  26. return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
  27. #定义两个placeholder
  28. x = tf.placeholder(tf.float32, [None,784])
  29. y = tf.placeholder(tf.float32,[None,10])
  30.  
  31. #改变x的格式转为4D的向量[batch,in_height,in_width,in_channels]
  32. x_image = tf.reshape(x, [-1,28,28,1])
  33.  
  34. #初始化第一个卷基层的权值和偏置
  35. W_conv1 = weight_variable([5,5,1,32]) #5*5的采样窗口 32个卷积核从一个平面抽取特征 32个卷积核是自定义的
  36. b_conv1 = bias_variable([32]) #每个卷积核一个偏置值
  37.  
  38. #把x_image和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
  39. h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
  40. h_pool1 = max_pool_2x2(h_conv1) #进行max-pooling
  41.  
  42. #初始化第二个卷基层的权值和偏置
  43. W_conv2 = weight_variable([5,5,32,64]) # 5*5的采样窗口 64个卷积核从32个平面抽取特征 由于前一层操作得到了32个特征图
  44. b_conv2 = bias_variable([64]) #每一个卷积核一个偏置值
  45.  
  46. #把h_pool1和权值向量进行卷积 再加上偏置值 然后应用于relu激活函数
  47. h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2)
  48. h_pool2 = max_pool_2x2(h_conv2) #进行max-pooling
  49.  
  50. #28x28的图片第一次卷积后还是28x28 第一次池化后变为14x14
  51. #第二次卷积后 变为14x14 第二次池化后变为7x7
  52. #通过上面操作后得到64张7x7的平面
  53.  
  54. #初始化第一个全连接层的权值
  55. W_fc1 = weight_variable([7*7*64,1024])#上一层有7*7*64个神经元,全连接层有1024个神经元
  56. b_fc1 = bias_variable([1024]) #1024个节点
  57.  
  58. #把第二个池化层的输出扁平化为一维
  59. h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])
  60. #求第一个全连接层的输出
  61. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)
  62.  
  63. #keep_prob用来表示神经元的输出概率
  64. keep_prob = tf.placeholder(tf.float32)
  65. h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
  66.  
  67. #初始化第二个全连接层
  68. W_fc2 = weight_variable([1024,10])
  69. b_fc2 = bias_variable([10])
  70.  
  71. #计算输出
  72. prediction = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2)
  73.  
  74. #交叉熵代价函数
  75. cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
  76.  
  77. #使用AdamOptimizer进行优化
  78. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
  79. #结果存放在一个布尔列表中
  80. correct_prediction = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1)) #argmax返回一维张量中最大的值所在的位置
  81. #求准确率
  82. accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
  83.  
  84. saver = tf.train.Saver()
  85. with tf.Session() as sess:
  86. sess.run(tf.global_variables_initializer())
  87. for epoch in range(13):
  88. for batch in range(n_batch):
  89. batch_xs,batch_ys = mnist.train.next_batch(batch_size)
  90. sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys,keep_prob:0.7})
  91. acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0})
  92. print ("Iter "+ str(epoch) + ", Testing Accuracy= " + str(acc))
  93. saver.save(sess,save_path='/home/bayes/logs/mnist_net.ckpt')

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

  1. #coding:utf-8
  2.  
  3. import tensorflow as tf
  4. from tensorflow.examples.tutorials.mnist import input_data
  5.  
  6. mnist = input_data.read_data_sets('MNIST_data',one_hot=True)
  7.  
  8. #每个批次的大小
  9. batch_size = 100
  10.  
  11. n_batch = mnist.train._num_examples // batch_size
  12.  
  13. def weight_variable(shape):
  14. initial = tf.truncated_normal(shape,stddev=0.1) #生成一个截断的正态分布
  15. return tf.Variable(initial)
  16.  
  17. def bias_variable(shape):
  18. initial = tf.constant(0.1,shape = shape)
  19. return tf.Variable(initial)
  20.  
  21. #卷基层
  22. def conv2d(x,W):
  23. return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
  24. #池化层
  25. def max_pool_2x2(x):
  26. return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
  27. #定义两个placeholder
  28. x = tf.placeholder(tf.float32, [None,784])
  29. y = tf.placeholder(tf.float32,[None,10])
  30.  
  31. #改变x的格式转为4D的向量[batch,in_height,in_width,in_channels]
  32. x_image = tf.reshape(x, [-1,28,28,1])
  33.  
  34. #初始化第一个卷基层的权值和偏置
  35. W_conv1 = weight_variable([5,5,1,32]) #5*5的采样窗口 32个卷积核从一个平面抽取特征 32个卷积核是自定义的
  36. b_conv1 = bias_variable([32]) #每个卷积核一个偏置值
  37.  
  38. #把x_image和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
  39. h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
  40. h_pool1 = max_pool_2x2(h_conv1) #进行max-pooling
  41.  
  42. #初始化第二个卷基层的权值和偏置
  43. W_conv2 = weight_variable([5,5,32,64]) # 5*5的采样窗口 64个卷积核从32个平面抽取特征 由于前一层操作得到了32个特征图
  44. b_conv2 = bias_variable([64]) #每一个卷积核一个偏置值
  45.  
  46. #把h_pool1和权值向量进行卷积 再加上偏置值 然后应用于relu激活函数
  47. h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2)
  48. h_pool2 = max_pool_2x2(h_conv2) #进行max-pooling
  49.  
  50. #28x28的图片第一次卷积后还是28x28 第一次池化后变为14x14
  51. #第二次卷积后 变为14x14 第二次池化后变为7x7
  52. #通过上面操作后得到64张7x7的平面
  53.  
  54. #初始化第一个全连接层的权值
  55. W_fc1 = weight_variable([7*7*64,1024])#上一层有7*7*64个神经元,全连接层有1024个神经元
  56. b_fc1 = bias_variable([1024]) #1024个节点
  57.  
  58. #把第二个池化层的输出扁平化为一维
  59. h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])
  60. #求第一个全连接层的输出
  61. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)
  62.  
  63. #keep_prob用来表示神经元的输出概率
  64. keep_prob = tf.placeholder(tf.float32)
  65. h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
  66.  
  67. #初始化第二个全连接层
  68. W_fc2 = weight_variable([1024,10])
  69. b_fc2 = bias_variable([10])
  70.  
  71. #计算输出
  72. prediction = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2)
  73.  
  74. #交叉熵代价函数
  75. cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
  76.  
  77. #使用AdamOptimizer进行优化
  78. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
  79. #结果存放在一个布尔列表中
  80. correct_prediction = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1)) #argmax返回一维张量中最大的值所在的位置
  81. #求准确率
  82. accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
  83.  
  84. saver = tf.train.Saver()
  85. with tf.Session() as sess:
  86. sess.run(tf.global_variables_initializer())
  87. print (sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0}))
  88. saver.restore(sess, '/home/bayes/logs/mnist_net.ckpt')
  89. print (sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0}))

结果  初始化后没有经过训练的参数准确率低  训练后从模型中提取的参数准确率高

  1. I tensorflow/core/common_runtime/gpu/gpu_device.cc:906] DMA: 0
  2. I tensorflow/core/common_runtime/gpu/gpu_device.cc:916] 0: Y
  3. 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)
  4. 0.1117
  5. 0.9893

Tensorflow学习教程------参数保存和提取重利用的更多相关文章

  1. tensorflow学习之路----保存和提取数据

    #保存数据注意他只能保存变量,不能保存神经网络的框架.#保存数据的作用:保存权重有利于下一次的训练,或者可以用这个数据进行识别#np.arange():arange函数用于创建等差数组,使用频率非常高 ...

  2. Tensorflow学习教程------过拟合

    Tensorflow学习教程------过拟合   回归:过拟合情况 / 分类过拟合 防止过拟合的方法有三种: 1 增加数据集 2 添加正则项 3 Dropout,意思就是训练的时候隐层神经元每次随机 ...

  3. Tensorflow学习教程------代价函数

    Tensorflow学习教程------代价函数   二次代价函数(quadratic cost): 其中,C表示代价函数,x表示样本,y表示实际值,a表示输出值,n表示样本的总数.为简单起见,使用一 ...

  4. Tensorflow学习教程------读取数据、建立网络、训练模型,小巧而完整的代码示例

    紧接上篇Tensorflow学习教程------tfrecords数据格式生成与读取,本篇将数据读取.建立网络以及模型训练整理成一个小样例,完整代码如下. #coding:utf-8 import t ...

  5. TensorFlow学习笔记:保存和读取模型

    TensorFlow 更新频率实在太快,从 1.0 版本正式发布后,很多 API 接口就发生了改变.今天用 TF 训练了一个 CNN 模型,结果在保存模型的时候居然遇到各种问题.Google 搜出来的 ...

  6. tensorflow 学习教程

    tensorflow 学习手册 tensorflow 学习手册1:https://cloud.tencent.com/developer/section/1475687 tensorflow 学习手册 ...

  7. Tensorflow学习教程------模型参数和网络结构保存且载入,输入一张手写数字图片判断是几

    首先是模型参数和网络结构的保存 #coding:utf-8 import tensorflow as tf from tensorflow.examples.tutorials.mnist impor ...

  8. Tensorflow学习教程------tfrecords数据格式生成与读取

    首先是生成tfrecords格式的数据,具体代码如下: #coding:utf-8 import os import tensorflow as tf from PIL import Image cw ...

  9. Tensorflow学习教程------创建图启动图

    Tensorflow作为目前最热门的机器学习框架之一,受到了工业界和学界的热门追捧.以下几章教程将记录本人学习tensorflow的一些过程. 在tensorflow这个框架里,可以讲是若数据类型,也 ...

随机推荐

  1. 2-10 就业课(2.0)-oozie:10、伪分布式环境转换为HA集群环境

    hadoop 的基础环境增强 HA模式 HA是为了保证我们的业务 系统 7 *24 的连续的高可用提出来的一种解决办法,现在hadoop当中的主节点,namenode以及resourceManager ...

  2. Springboot注解使用总结

    使用Spring boot已经有段时间了,但是对很多注解的使用经常会遇到模糊甚至不解的地方,这次有时间便总结一下. 注解(Annotation)概念 注解是Java5开始对元数据的支持,注解与注释是有 ...

  3. Concurrent包下用过哪些类?

    1.executor接口,使用executor接口的子接口ExecutorService用来创建线程池2.Lock接口下的ReentrantLock类,实现同步,比如三个线程循环打印ABCABCABC ...

  4. NPOI读取excel 空行

    if (sheet.GetRow(i) != null) 每行判断一下,避免出错.真是蛋疼.

  5. PG、GP与MySQL的特点和区别

    参考 PostgreSQL数据库 介绍:PostgreSQL是一种运行在Unix和Linux操作系统(在NT平台借助Cygnus也可以运行)平台上的免费的开放源码的关系数据库.最早是由美国加州大学伯克 ...

  6. Golang的单目(一元)运算符-地址操作符和接收操作符

    Golang的单目(一元)运算符-地址操作符和接收操作符 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Golang的单目(一元)运算符概述 常见的地址操作符: &: ...

  7. django 实现 内网访问 和 用花生壳进行内网穿透

    1.在setting.py中找到  ALLOWED_HOSTS = [] 改为 ALLOWED_HOSTS = ['*',]2.启动服务时使用如下命令行 python .\manage.py runs ...

  8. Babel(1)认识Babel

    阅读文档 Babel中文网 关于 Babel 你必须知道的 如何写好.babelrc?Babel的presets和plugins配置解析 不容错过的 Babel 7 知识汇总 一口(很长的)气了解 b ...

  9. Vue.js(23)之 keepAlive和activated

    阅读: vue中前进刷新.后退缓存用户浏览数据和浏览位置的实践 keep-alive 组件级缓存 keep-alive <keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而 ...

  10. HDU 4819 二维线段树

    13年长春现场赛的G题,赤裸裸的二维线段树,单点更新,区间查询 不过我是第一次写二维的,一开始写T了,原因是我没有好好利用行段,说白一点,还是相当于枚举行,然后对列进行线段树,那要你写二维线段树干嘛 ...