Mnist数据集训练 (使用softmax_regression)

# 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
'''
发布了125 篇原创文章 · 获赞 126 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/Valieli/article/details/103891116