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

首先要有编译环境,并且已经正确的编译安装,关于环境配置参考:http://www.cnblogs.com/dyufei/p/8027517.html

一、MNIST 运行

1)首先下载训练数据

http://yann.lecun.com/exdb/mnist/ 将四个包都下载下来,在下面代码的运行目录下创建MNIST_data目录,将四个包放进去

train-images-idx3-ubyte.gz: training set images (9912422 bytes)

train-labels-idx1-ubyte.gz: training set labels (28881 bytes)

t10k-images-idx3-ubyte.gz: test set images (1648877 bytes)

t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes)

当然也可以不下载,前提是运行TensorFlow的服务器可以正常访问下载目录,如果出问题参照 【问题1)】解决)

2) MNIST 代码

A: 比较旧的版本(官方教程里面的)

https://tensorflow.google.cn/get_started/mnist/beginners

中文:http://www.tensorfly.cn/tfdoc/tutorials/mnist_beginners.html

完整代码如下:mnist.py

import input_data
import tensorflow as tf
FLAGS = None
mnist = input_data.read_data_sets('MNIST_data', one_hot=True) x = tf.placeholder("float",[None,784])
w = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x,w) + b)
y_ = tf.placeholder("float",[None,10])
cross_entroy = -tf.reduce_sum(y_ * tf.log(y)) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entroy) init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init) for _ in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step,feed_dict ={x:batch_xs,y_:batch_ys}) correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float")) print sess.run(accuracy, feed_dict={x:mnist.test.images, y_:mnist.test.labels})

input_data.py

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function import gzip
import os
import tempfile import numpy
from six.moves import urllib
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets

运行

python mnist.py

2) 新版本mnist_softmax.py

input_data.py 文件内容相同,mnist_softmax.py文件不同

mnist_softmax.py 文件目录:

tensorflow\tensorflow\examples\tutorials\mnist\mnist_softmax.py

完整代码:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function import argparse
import sys
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf FLAGS = None def main(_):
# Import data
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True) # Create the model
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b # Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10]) # The raw formulation of cross-entropy,
#
# tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),
# reduction_indices=[1]))
#
# can be numerically unstable.
#
# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw
# outputs of 'y', and then average across the batch.
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
# Train
for _ in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Test trained model
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images,
y_: mnist.test.labels})) if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
help='Directory for storing input data')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

数据路径不同,将训练数据copy过去:

cp MNIST_data/*.gz /tmp/tensorflow/mnist/input_data/

运行:

python mnist_softmax.py

最新文章

  1. yield生成器及字符串的格式化
  2. Sphinx安装配置应用
  3. Linux下解压超过4G的zip文件
  4. 【强烈推荐】如何给TortoiseGit 配置密钥?
  5. [资料分享]Python视频教程(基础篇、进阶篇、项目篇)
  6. TCP/IP 协议:链路层概述
  7. Android中动画
  8. [译]Stairway to Integration Services Level 10 - 高级事件活动
  9. 微信小程序之----加载中提示框loading
  10. "双非"应届生校招如何获得大厂青睐?(内附技术岗超全求职攻略)
  11. mobile angualar ui的简单使用
  12. 网络操作系统 第九章 DHCP服务器管理与配置
  13. 【Android】GestureDetector类及其用法
  14. 使用VSTS的Git进行版本控制(六)——拉取请求
  15. luogu1965 转圈游戏 (快速幂)
  16. Mac-控制台更新svn版本
  17. 【BZOJ 2822】2822: [AHOI2012]树屋阶梯(卡特兰数+高精度)
  18. window 如何枚举设备并禁用该设备和启用该设备?如何注册设备热拔插消息通知?
  19. appium+python自动化41-切换webview时候报chromedriver版本问题
  20. Kali Linux使用Aircrack破解wifi密码(wpa/wpa2)

热门文章

  1. linux C 文件操作之fgets()
  2. addEventListener 的事件函数的传递【转载】
  3. NFS服务安装及配置
  4. vue初级学习--环境搭建
  5. webpack学习笔记啊(幕课)
  6. div内长串数字或字母不断行处理
  7. [转载] Redis系统性介绍
  8. tsung压力测试——tcp测试tsung.xml配置模版说明
  9. spring学习笔记(一) Spring概述
  10. 从.git文件夹探析git实现原理