训练代码:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('data_dir', '/tmp/data/', 'Directory for storing data') print(FLAGS.data_dir)
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True) input=tf.placeholder(tf.float32,[None,784],name='input')
label=tf.placeholder(tf.float32,[None,10],name='label')
keep_prob=tf.placeholder(tf.float32,name='keep_prob') image=tf.reshape(input,[-1,28,28,1]) conv1_W=tf.Variable(tf.truncated_normal([5,5,1,32],stddev=0.1))
conv1_b=tf.Variable(tf.constant(0.1,shape=[32]))
layer1=tf.nn.elu(tf.nn.conv2d(image,conv1_W,strides=[1,1,1,1],padding='SAME')+conv1_b)
layer2=tf.nn.max_pool(layer1,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') conv2_W=tf.Variable(tf.truncated_normal([5,5,32,64],stddev=0.1))
conv2_b=tf.Variable(tf.constant(0.1,shape=[64]))
layer3=tf.nn.elu(tf.nn.conv2d(layer2,conv2_W,strides=[1,1,1,1],padding='SAME')+conv2_b)
layer4=tf.nn.max_pool(layer3,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') layer5=tf.reshape(layer4,[-1,7*7*64]) fc1_W=tf.Variable(tf.truncated_normal([7*7*64,1024],stddev=0.1))
fc1_b=tf.Variable(tf.constant(0.1,shape=[1024]))
layer5=tf.reshape(layer4,[-1,7*7*64])
layer6=tf.nn.elu(tf.matmul(layer5,fc1_W)+fc1_b) layer7=tf.nn.dropout(layer6,keep_prob) fc2_W=tf.Variable(tf.truncated_normal([1024,10],stddev=0.1))
fc2_b=tf.Variable(tf.constant(0.1,shape=[10]))
output=tf.nn.softmax(tf.matmul(layer7,fc2_W)+fc2_b,name='output') cross_entropy=tf.reduce_mean(-tf.reduce_sum(label*tf.log(output),reduction_indices=[1])) train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_predition=tf.equal(tf.argmax(output,1),tf.arg_max(label,1))
accuracy=tf.reduce_mean(tf.cast(correct_predition,tf.float32),name='accuracy') sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
batch = mnist.train.next_batch(50)
for i in range(20000):
batch = mnist.train.next_batch(50)
train_step.run(feed_dict={input: batch[0], label: batch[1], keep_prob: 0.5})
if i%100==0:
train_accuracy = accuracy.eval(feed_dict={input:batch[0], label:batch[1], keep_prob: 1.0})
print("%d:training accuracy %g"%(i,train_accuracy)) saver = tf.train.Saver()
save_path = saver.save(sess,"E:/dnn/model")

测试代码:

from __future__ import division
import numpy as np
import tensorflow as tf
from PIL import Image img = Image.open('E:/dnn/test.bmp').convert('L')
if img.size[0] != 28 or img.size[1] != 28:
img = img.resize((28, 28))
arr = []
for i in range(28):
for j in range(28):
pixel = 1.0 - float(img.getpixel((j, i)))/255.0
arr.append(pixel)
image = np.array(arr).reshape((1, 28, 28, 1)) saver = tf.train.import_meta_graph('E:/dnn/model.meta')
graph = tf.get_default_graph()
input=graph.get_tensor_by_name('input:0')
label=graph.get_tensor_by_name('label:0')
output=graph.get_tensor_by_name('output:0')
keep_prob=graph.get_tensor_by_name('keep_prob:0')
accuracy=graph.get_tensor_by_name('accuracy:0') with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('E:/dnn'))
test = sess.run(output, feed_dict={input: image.reshape(-1,784), label: np.full(10,1e-10).reshape(-1,10), keep_prob: 1.0})
print(test)
ans=0
for i in range(10):
if (test[0][i]>test[0][ans]):
ans=i
print(ans)

测试结果:

TensorFlow-mnist的更多相关文章

  1. TensorFlow MNIST(手写识别 softmax)实例运行

    TensorFlow MNIST(手写识别 softmax)实例运行 首先要有编译环境,并且已经正确的编译安装,关于环境配置参考:http://www.cnblogs.com/dyufei/p/802 ...

  2. 学习笔记TF056:TensorFlow MNIST,数据集、分类、可视化

    MNIST(Mixed National Institute of Standards and Technology)http://yann.lecun.com/exdb/mnist/ ,入门级计算机 ...

  3. TensorFlow MNIST 问题解决

    TensorFlow MNIST 问题解决 一.数据集下载错误 错误:IOError: [Errno socket error] [Errno 101] Network is unreachable ...

  4. Mac tensorflow mnist实例

    Mac tensorflow mnist实例 前期主要需要安装好tensorflow的环境,Mac 如果只涉及到CPU的版本,推荐使用pip3,傻瓜式安装,一行命令!代码使用python3. 在此附上 ...

  5. tensorflow MNIST Convolutional Neural Network

    tensorflow MNIST Convolutional Neural Network MNIST CNN 包含的几个部分: Weight Initialization Convolution a ...

  6. tensorflow MNIST新手教程

    官方教程代码如下: import gzip import os import tempfile import numpy from six.moves import urllib from six.m ...

  7. TensorFlow MNIST初级学习

    MNIST MNIST 是一个入门级计算机视觉数据集,包含了很多手写数字图片,如图所示: 数据集中包含了图片和对应的标注,在 TensorFlow 中提供了这个数据集,我们可以用如下方法进行导入: f ...

  8. 学习笔记TF057:TensorFlow MNIST,卷积神经网络、循环神经网络、无监督学习

    MNIST 卷积神经网络.https://github.com/nlintz/TensorFlow-Tutorials/blob/master/05_convolutional_net.py .Ten ...

  9. AI tensorflow MNIST

    MNIST 数据 train-images-idx3-ubyte.gz:训练集图片 train-labels-idx1-ubyte.gz:训练集图片类别 t10k-images-idx3-ubyte. ...

  10. tensorflow——MNIST机器学习入门

    将这里的代码在项目中执行下载并安装数据集. 执行下面代码,训练.并评估模型: # _*_coding:utf-8_*_ import inputdata mnist = inputdata.read_ ...

随机推荐

  1. 关于jQuery.form中formSerialize()等函数的适用对象

    几个月前写一个页面,要用到Ajax提交,于是写了几行jQuery: …… var formData = $("form")[0].formSerialize(); …… 然后死活调 ...

  2. S-HR快速查看shr日志

    http://localhost:6888/shr/appData.do?method=getApplicationLog&logFile=apusic.log.0&instance= ...

  3. 【剑指Offer】51、构建乘积数组

      题目描述:   给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1].   其中B中的元素B[i]=A[0] * A[1]... * A[i-1] * A[i+1] ...

  4. js-2018-11-09 关于Array中的srot()方法和compare()方法

    Array中的srot()方法 sort()方法是用来重排序的方法.在默认情况下,sort()方法按升序排列数组项----即最小的值位于最前面,最大的值排在最后面. 我们看看官方是怎么说的: arra ...

  5. 01 c++常见面试题总结

    https://www.cnblogs.com/yjd_hycf_space/p/7495640.html   C++常见的面试题 http://c.tedu.cn/workplace/217749. ...

  6. HDU1087 - Super Jumping! Jumping! Jumping!【动态规划】

    zh成功的在他人的帮助下获得了与小姐姐约会的机会,同时也不用担心被非"川大"的女票发现了,可是如何选择和哪些小姐姐约会呢?zh希望自己可以循序渐进,同时希望挑战自己的极限,我们假定 ...

  7. 【学习笔记】有向无环图上的DP

    手动博客搬家: 本文发表于20180716 10:49:04, 原地址https://blog.csdn.net/suncongbo/article/details/81061378 首先,感谢以下几 ...

  8. SGU - 296 - Sasha vs. Kate

    上题目: 296. Sasha vs. Kate Time limit per test: 1 second(s)Memory limit: 65536 kilobytes input: standa ...

  9. springMVC @ModelAttribute功能

    @ModelAttribute功能:将数据模型回写到页面 如: public String validate(@Valid @ModelAttribute("user") User ...

  10. redhat超级用户密码破解

    1. 开机在出现grub画面,按e键 2. 用上下键选中第二项(类似于kernel /boot/vmlinuz-2.4.18-14 ro root=LABEL=/) 然后按e键编辑 3. 空格sing ...