本文主要是介绍TensorFlow-MNIST入门篇代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
看了下TensorFlow的官方文档 里面关于MNIST的入门篇
在这里把代码整理了
input_data.py(urllib下面有红线 没关系)
# __author__ = 'youngkl'
# -*- coding: utf-8 -*-from __future__ import absolute_import
from __future__ import division
from __future__ import print_functionimport gzip
import os
import tempfileimport 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
mnist_demo.py
#-*- coding:utf-8 -*-import tensorflow.examples.tutorials.mnist.input_data as input_data
import 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.gz
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
0.9155
这篇关于TensorFlow-MNIST入门篇代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!