import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data

# 在变量的构建时,通过truncated_normal 函数初始化权重变量,shape 是一个二维的tensor,从截断的正太分布中输出随机值。
def weight_varible(shape):
initial=tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(initial) def bias_varible(shape):
initial=tf.constant(0.1,shape=shape)
return tf.Variable(initial) def conv2d(x,w):
# x 输入,是一个tensor,w 为filter,strides卷积时每一维的步长,padding 参数是string类型的值,为same,或valid,use_cudnn_on_gpu: bool类型,默认是true
return tf.nn.conv2d(x,w,strides=[1,1,1,1],padding='SAME')
def max_pool_2x2(x):
# x 为池化的输入,ksize 为窗口的大小,四维向量,一般为【1,height,width,1】, 因为不在channel上做池化,stride 和卷积类型,窗口在每一维上滑动的步长,【1,stride,stride,1】
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') # tensorflow 中已经写好了加载mnist 数据集的脚本,minist是一个轻量级的类文件,存储了Numpy格式的训练集,验证集。。同时提供了数据中mini-batch迭代的功能
mnist=input_data.read_data_sets('MNIST_data/',one_hot=True) # 输入数据参数
x=tf.placeholder(tf.float32,[None,784])
# 当某轴为-1 时,根据数组元素的个数自动计算此轴的长度
x_image=tf.reshape(x,[-1,28,28,1])
y=tf.placeholder(tf.float32,[None,10]) # 后台C++,通过session与后台连接, 在session中运行创建的图,
# 使用InteractiveSession 更方便,允许交互操作,如果不用InteractiveSession, 在启动一个回话和运行图之前,要创建整个流图
sess=tf.InteractiveSession() # 第一个卷积层
w_conv1=weight_varible([5,5,1,32])
b_conv1=bias_varible([32])
h_conv1=tf.nn.relu(conv2d(x_image,w_conv1)+b_conv1)
h_pool1=max_pool_2x2(h_conv1) # 第二个卷积层
w_conv2=weight_varible([5,5,32,64])
b_conv2=bias_varible([64])
h_conv2=tf.nn.relu(conv2d(h_pool1,w_conv2)+b_conv2)
h_pool2=max_pool_2x2(h_conv2) #全连接层
# 经过两次pool 之后大小变为7*7
w_fc1=weight_varible([7*7*64,1024])
b_fc1=bias_varible([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)
h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob) #output softmax w_fc2=weight_varible([1024,10])
b_fc2=bias_varible([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop,w_fc2)+b_fc2) # 定义loss 函数,和最优化函数
cross_entropy=-tf.reduce_sum(y*tf.log(y_conv))
train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # 定义eval
correct_prediction=tf.equal(tf.arg_max(y_conv,1),tf.arg_max(y,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))# cast 为类型转换函数,将类型转换为tf.float32 sess.run(tf.initialize_all_variables()) # 开始正式的训练
for i in range(20000):
batch=mnist.train.next_batch(50)
# mnist 类中提供了取batch的函数
if i%100==0: # train_accuracy=accuracy.eval()
print("step %d, training accuracy %g" %(i, sess.run(accuracy,feed_dict={x:batch[0],y:batch[1],keep_prob:1.0}))) sess.run(train_step,feed_dict={x:batch[0],y:batch[1],keep_prob:0.5})
#train_step.run() print("test accuracy %g" %(accuracy.eval(feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0})))

  

sess.run(accuracy,feed_dict={x:batch[0],y:batch[1],keep_prob:1.0})

accuracy.eval(feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0})

accuracy.eval 相当于 tf.get_default_session().run(t)

accuracy.eval()==sess.run(t)

而sess.run() 可以在同一步骤获取更多的张量的值,: sess.run(accuracy, train_step)

sess.run 和eval 每次都从头执行graph, 要缓存计算结果,需要分配tf.Variable

注意注意: 我们 需要关闭回话
sess.close()
如果想不显式的调用close, 可以用with 代码块
with tf.Session() as sess:
...

  如果需要存储参数:

saver=tf.train.Saver()
save_path=saver.save(sess,model_path)
load_path=saver.restore(sess,model_path)

  

												

tensorflow实现mnist的更多相关文章

  1. Android+TensorFlow+CNN+MNIST 手写数字识别实现

    Android+TensorFlow+CNN+MNIST 手写数字识别实现 SkySeraph 2018 Email:skyseraph00#163.com 更多精彩请直接访问SkySeraph个人站 ...

  2. Ubuntu16.04安装TensorFlow及Mnist训练

    版权声明:本文为博主原创文章,欢迎转载,并请注明出处.联系方式:460356155@qq.com TensorFlow是Google开发的开源的深度学习框架,也是当前使用最广泛的深度学习框架. 一.安 ...

  3. 一个简单的TensorFlow可视化MNIST数据集识别程序

    下面是TensorFlow可视化MNIST数据集识别程序,可视化内容是,TensorFlow计算图,表(loss, 直方图, 标准差(stddev)) # -*- coding: utf-8 -*- ...

  4. 基于tensorflow的MNIST手写数字识别(二)--入门篇

    http://www.jianshu.com/p/4195577585e6 基于tensorflow的MNIST手写字识别(一)--白话卷积神经网络模型 基于tensorflow的MNIST手写数字识 ...

  5. 使用Tensorflow操作MNIST数据

    MNIST是一个非常有名的手写体数字识别数据集,在很多资料中,这个数据集都会被用作深度学习的入门样例.而TensorFlow的封装让使用MNIST数据集变得更加方便.MNIST数据集是NIST数据集的 ...

  6. TensorFlow RNN MNIST字符识别演示快速了解TF RNN核心框架

    TensorFlow RNN MNIST字符识别演示快速了解TF RNN核心框架 http://blog.sina.com.cn/s/blog_4b0020f30102wv4l.html

  7. 2、TensorFlow训练MNIST

    装载自:http://www.tensorfly.cn/tfdoc/tutorials/mnist_beginners.html TensorFlow训练MNIST 这个教程的目标读者是对机器学习和T ...

  8. 深入浅出TensorFlow(二):TensorFlow解决MNIST问题入门

    2017年2月16日,Google正式对外发布Google TensorFlow 1.0版本,并保证本次的发布版本API接口完全满足生产环境稳定性要求.这是TensorFlow的一个重要里程碑,标志着 ...

  9. Tensorflow之MNIST的最佳实践思路总结

    Tensorflow之MNIST的最佳实践思路总结   在上两篇文章中已经总结出了深层神经网络常用方法和Tensorflow的最佳实践所需要的知识点,如果对这些基础不熟悉,可以返回去看一下.在< ...

  10. TensorFlow训练MNIST报错ResourceExhaustedError

    title: TensorFlow训练MNIST报错ResourceExhaustedError date: 2018-04-01 12:35:44 categories: deep learning ...

随机推荐

  1. python 字符串内置方法实例

    一.字符串方法总结: 1.查找: find(rfind).index(rindex).count 2.变换: capitalize.expandtabs.swapcase.title.lower.up ...

  2. HTML-封装原生Ajax

    function ajax(data){ //data{data:"",dataType:"xml/json",type:"get/post" ...

  3. BZOJ2141排队——树状数组套权值线段树(带修改的主席树)

    题目描述 排排坐,吃果果,生果甜嗦嗦,大家笑呵呵.你一个,我一个,大的分给你,小的留给我,吃完果果唱支歌,大家 乐和和.红星幼儿园的小朋友们排起了长长地队伍,准备吃果果.不过因为小朋友们的身高有所区别 ...

  4. BZOJ3626 LNOI2014LCA(树链剖分+主席树)

    开店简化版. #include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> ...

  5. 【Linux】memcache和memcached的自动安装

    赶时间所以写一个简单的一个脚本,没有优化,想优化的可以学习下shell,自己优化下. 且行且珍惜,源码包+脚本领取处 链接:https://pan.baidu.com/s/1wIFR1wY-luDKs ...

  6. AC自动机-HDU2222-模板题

    http://acm.hdu.edu.cn/showproblem.php?pid=2222 一个AC自动机的模板题.用的kuangbin的模板,静态建Trie树.可能遇到MLE的情况要转动态建树. ...

  7. ACM-ICPC国际大学生程序设计竞赛北京赛区(2017)网络赛 i题 Minimum(线段树)

    描述 You are given a list of integers a0, a1, …, a2^k-1. You need to support two types of queries: 1. ...

  8. Hdoj 基本输入输出8道(1089-1096)

    Hdoj 1089 #include<bits/stdc++.h> using namespace std; int main() { int a,b; while(cin>> ...

  9. [NOIP提高组2018day2t1]旅行

    题目描述 给定n个城市,m条双向道路的图, 不存在两条连接同一对城市的道路,也不存在一条连接一个城市和它本身的道路.并且, 从任意一个城市出发,通过这些道路都可以到达任意一个其他城市.小 Y 只能通过 ...

  10. C代码快速构建框架

    #include "stdio.h" typedef char int8_t; typedef short int16_t; typedef int int32_t; typede ...