TensorFlow-MNIST入门篇代码

来源:互联网 发布:mac改了用户名进不去 编辑:程序博客网 时间:2024/06/05 10:40

看了下TensorFlow的官方文档 里面关于MNIST的入门篇

在这里把代码整理了

input_data.py(urllib下面有红线 没关系)

# __author__ = 'youngkl'# -*- coding: utf-8 -*-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


mnist_demo.py

#-*- coding:utf-8 -*-import tensorflow.examples.tutorials.mnist.input_data as input_dataimport tensorflow as tfmnist=input_data.read_data_sets("MNIST_data/",one_hot=True)#one_hot编码 向量上只有一位是1其他都是0x=tf.placeholder(tf.float32,[None,784])#占位符 输入任意数量的图片 每一张图片展开成784维向量W=tf.Variable(tf.zeros([784,10]))b=tf.Variable(tf.zeros([10]))y=tf.nn.softmax(tf.matmul(x,W)+b)#通过softmax得到的预测值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)#使用梯度下降算法 学习率为0.01 最小化交叉熵init=tf.initialize_all_variables()sess=tf.Session()sess.run(init)for i in range(1000):    batch_xs,batch_ys=mnist.train.next_batch(100)    #随机抓取训练数据中的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))#找出tensor对象在某一维上其数据最大值所在的索引值 在此最大值1所在的索引位置就是类别标签accuracy=tf.reduce_mean(tf.cast(correct_prediction,"float"))print sess.run(accuracy,feed_dict={x:mnist.test.images,y_:mnist.test.labels})


输出:

Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.Extracting MNIST_data/train-images-idx3-ubyte.gzSuccessfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.Extracting MNIST_data/train-labels-idx1-ubyte.gzSuccessfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.Extracting MNIST_data/t10k-images-idx3-ubyte.gzSuccessfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.Extracting MNIST_data/t10k-labels-idx1-ubyte.gz0.9155


      

1 0
原创粉丝点击