实现第一个例子 来自google的数字识别

来源:互联网 发布:淘宝司法拍卖平台 编辑:程序博客网 时间:2024/05/17 01:21


1、先安装tensorflow

     参考:http://blog.csdn.net/moonshine99/article/details/78075714

     linux pip安装tensorflow很方便,推荐



2 下载代码: https://github.com/HungryGoogle/LeeTensorFlow

3.1 参考mnist,已经将下载好的数据放进来了

3.2 参考mnist2,将下面两个py文件放在同一个目录(我用的是pycharm),运行,可自动下载数据,运行

-----------------------------------------------------------------

run_this.py
-----------------------------------------------------------------
import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets("MNIST_data", one_hot=True)#读取mnist文件#设定参数x = tf.placeholder(tf.float32, [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])#定义costcross_entropy = -tf.reduce_sum(y_*tf.log(y))#设定训练算法train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)#初始化变量init = tf.global_variables_initializer()#启动模型sess = tf.Session()sess.run(init)#施行训练for i 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}))


-----------------------------------------------------------------

run_this.py
-----------------------------------------------------------------

"""Functions for downloading and reading MNIST data."""

from __future__ import absolute_importfrom __future__ import divisionfrom __future__ import print_functionimport gzipimport osimport tempfileimport numpyfrom six.moves import urllibfrom six.moves import xrange  # pylint: disable=redefined-builtinimport tensorflow as tffrom tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets

代码: https://github.com/HungryGoogle/LeeTensorFlow

原创粉丝点击