# coding:utf-8
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

# 下载Mnist数据集
mnist_data = input_data.read_data_sets("MNIST_data", one_hot=True)
# 输入数据占位
x = tf.placeholder(tf.float32, shape=[None, 28*28])
# 权值
W = tf.Variable(tf.zeros([28*28, 10]))
# 偏置项
b = tf.Variable(tf.zeros([10]))

# 模型的输出,使用tf.nn.softmax激活
y = tf.nn.softmax(tf.matmul(x,W)+b)
# 实际的图像标签
y_= tf.placeholder(tf.float32, shape=[None,10])
# 计算交叉熵
cross_entry = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y)))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entry)

# 创建会话
sess = tf.InteractiveSession()
# 初始化所有变量,并且分配内存
tf.global_variables_initializer().run()
print("start training...")

for _ in range(1000):
    # 取出100组训练数据
    batch_xs, batch_ys = mnist_data.train.next_batch(100)
    sess.run(train_step, feed_dict={x:batch_xs, y_:batch_ys})
# 计算准确率
correction_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correction_prediction, tf.float32))
# 将准确率打印出来
print(sess.run(accuracy, feed_dict={x:mnist_data.test.images, y_:mnist_data.test.labels}))

'''
start training...
0.9144
'''
0
Posted in 深度学习&强化学习

Leave a Comment:

电子邮件地址不会被公开。