Tensorflow MNIST实验

因为墙的关系,下面这段程序运行时会出问题的
自己去http://yann.lecun.com/exdb/mnist/下载吧,一共4个文件,下载好了放入MNIST_data/文件夹
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf

import numpy as np
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
新手版完整代码如下,准确率92.2%
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf

import numpy as np
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

sess = tf.Session()

x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# tf做了太多假设,比如二维数组与一维数组相加,建议写成下面的形式
# b = tf.Variable(tf.zeros([1,10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)

y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

# test = tf.reduce_sum(tf.ones([2, 3, 4]), reduction_indices=[1])
# print(sess.run(test))

train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy)

sess.run(tf.global_variables_initializer())

for _ in range(5000):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

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}))
运行可能会遇到错误
module 'pandas' has no attribute 'computation'
需要将pandas切换到老版本
pip uninstall pandas
install pandas=0.19.2
切换到老版本后依然不行,需要将tensorflow也同时切换到老版本
RuntimeError: module compiled against API version 0xb but this version of numpy is 0xa
建议不要用tensorflow.examples.tutorials这个包,因为大神们是不需要去跑新手实验的,所以几乎不维护

不要用tensorflow.examples.tutorials这个包是最简单的方法:
https://github.com/microic/niy/tree/master/TensorFlow/mnist


发表于:2017-11-15 14:57:36

原文链接(转载请保留): http://www.multisilicon.com/blog/a23316640.html

友情链接: MICROIC
首页