Tensorflow fisrt example ------------- 实现手写数字识别 无隐含层最浅的神经网络

# -*- coding: utf-8 -*-
"""
Created on Tue Mar 13 14:59:24 2018


@author: 102121


Tensorflow fisrt example -------------     实现手写数字识别     无隐含层最浅的神经网络
"""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/",one_hot = True)


print(mnist.train.images.shape,mnist.train.labels.shape)
print(mnist.test.images.shape,mnist.test.labels.shape)
print(mnist.validation.images.shape,mnist.validation.labels.shape)


sess = tf.InteractiveSession()#创建一个新的InteractiveSession,会将这个session 注册为默认的 session
#softmax回归模型中的x,W,b
x = tf.placeholder("float", [None, 784])#输入数据的地方          第一个参数 :输入数据类型,第二个参数 :(数据个数,None为不限制输入数据个数 , 数据的维数
W = tf.Variable(tf.zeros([784,10]))    # 创建 variable 对象,存储模型参数 W b
b = tf.Variable(tf.zeros([10]))
#softmax回归模型
y = tf.nn.softmax(tf.matmul(x,W) + b)
y_ = tf.placeholder("float", [None,10])
#计算交叉熵 H      # y 预测的概率分布  y' 真实的概率分布    H = -sum(y'(i)*logy(i))
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
#设置TensorFlow用梯度下降算法以0.01的学习速率最小化交叉熵
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
#初始化变量
init = tf.global_variables_initializer()
#评估模型
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
#开启Tesnsorflow
sess = tf.Session()
sess.run(init)
#循环训练模型
for i in range(1000):
  batch = mnist.train.next_batch(100)
  sess.run(train_step,feed_dict={x: batch[0], y_: batch[1]})
#输出结果
print("softmax回归测试MNIST数据集正确率:")
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))



















猜你喜欢

转载自blog.csdn.net/m0_37758017/article/details/79541303
今日推荐