MNIST——softmax回归

来源:互联网 发布:什么叫软件饱和 编辑:程序博客网 时间:2024/06/18 10:24

input_data.py代码如下

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at##     http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# =============================================================================="""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

在input_data.py文件的相同工程目录下新建test.py

import input_datamnist = input_data.read_data_sets("MNIST_data/", one_hot=True)import tensorflow as tfx = 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_entropy = -tf.reduce_sum(y_*tf.log(y))#交叉熵成本函数train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)#使用梯度下降法使得成本函数最小化,学习率为0.01init = tf.global_variables_initializer()#进行初始化#进入会话执行初始化操作sess = tf.Session()sess.run(init)#模型循环训练1000次,每次随机抓取训练数据中的100个批处理数据点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}))

运行如下

runfile('E:/MNIST/test.py', wdir='E:/MNIST')Reloaded modules: input_dataExtracting MNIST_data/train-images-idx3-ubyte.gzExtracting MNIST_data/train-labels-idx1-ubyte.gzExtracting MNIST_data/t10k-images-idx3-ubyte.gzExtracting MNIST_data/t10k-labels-idx1-ubyte.gz0.9163

正确率在0.91左右

初始化变量操作应该使用tf.global_variables_initializer()

原创粉丝点击