test03.py 1.4 KB

1234567891011121314151617181920212223242526
  1. import tensorflow as tf
  2. import tensorflow.examples.tutorials.mnist.input_data as input_data
  3. import os
  4. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
  5. mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
  6. x = tf.placeholder(tf.float32, [None, 784])
  7. y_actual = tf.placeholder(tf.float32, shape=[None, 10])
  8. W = tf.Variable(tf.zeros([784, 10])) # 初始化权值W
  9. b = tf.Variable(tf.zeros([10])) # 初始化偏置项b
  10. y_predict = tf.nn.softmax(tf.matmul(x, W) + b) # 加权变换并进行softmax回归,得到预测概率
  11. cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_actual * tf.log(y_predict))) # 求交叉熵
  12. train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) # 用梯度下降法使得残差最小
  13. correct_prediction = tf.equal(tf.argmax(y_predict, 1), tf.argmax(y_actual, 1)) # 在测试阶段,测试准确度计算
  14. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) # 多个批次的准确度均值
  15. init = tf.global_variables_initializer()
  16. with tf.Session() as sess:
  17. sess.run(init)
  18. for i in range(1000): # 训练阶段,迭代1000次
  19. batch_xs, batch_ys = mnist.train.next_batch(100) # 按批次训练,每批100行数据
  20. sess.run(train_step, feed_dict={x: batch_xs, y_actual: batch_ys}) # 执行训练
  21. if i % 100 == 0: # 每训练100次,测试一次
  22. print("accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images, y_actual: mnist.test.labels}))