tensorflow下对MNIST数据集进行识别的程序代码

xiaoxiao2021-02-28  100

# 下载mnist数据集: from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # 引入tensorflow: import tensorflow as tf x = tf.placeholder(tf.float32, [None, 784]) # None意味着可以是任意长度的维度 W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) # 实现模型 y = tf.nn.softmax(tf.matmul(x, W) + b) # 定义cost/loss,用cross_entropy y_ = tf.placeholder(tf.float32, [None, 10]) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) # 注:tensorflow源码中用的是tf.nn.softmax_cross_entropy_with_logits,目的是保持数值稳定 # 开始训练 train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) # 启动模型,用InteractiveSession sess = tf.InteractiveSession() # 初始化变量 tf.global_variables_initializer().run() # 运行 train_step 1000次 for _ in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # 注:feed进去的数据,代替placeholder # 评价模型 correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

运行结果:

0.9172
转载请注明原文地址: https://www.6miu.com/read-51488.html

最新回复(0)