用softmax对MNIST数据集进行分类

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np

mnist = input_data.read_data_sets('MNIST_data/', one_hot=True)

x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# 1.tf.multiply()两个矩阵中对应元素各自相乘 ## tf.matmul()将矩阵a乘以矩阵b,生成a * b。
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_real = tf.placeholder(tf.float32, [None, 10])
# 构造较少上损失函数     python中 \ 是续航符(换行符)
cross_entropy = \
    tf.reduce_mean(-tf.reduce_sum(y_real * tf.log(y)))
# 梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# 创建一个sess
sess=tf.InteractiveSession()
tf.global_variables_initializer().run()

for i in range(1000):
    batch_xs,batch_ys=mnist.train.next_batch(100)
    sess.run(train_step,feed_dict={x:batch_xs,y_real:batch_ys})


for i in range(20):
    one_hot_label = mnist.train.labels[i, :]
    # 通过np.argmax,可以直接获取原始label
    label = np.argmax(one_hot_label)
    print('mnist_train_%d.jpg: %d label' % (i, label))
correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_real,1))
accuary=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print(sess.run(accuary,feed_dict={x:mnist.test.images,y_real:mnist.test.labels}))

精度大概91.43%,用卷积的话基本上能达到99%

你可能感兴趣的:(Python深度学习)