安装TensorFlow
1.安装docker ,具体参考我的上一篇博客
2.执行:
docker run -it b.gcr.io/tensorflow/tensorflow:latest-devel
如此就把TensorFlow的环境搭建好了...深深感觉docker是个好东西..
运行TensorFlow的Hello World ---MNIST手写体识别
虽然称他为hello world,但是要理解他还是有一定的难度的。我是参考了如下两篇博客:
http://www.jeyzhang.com/tensorflow-learning-notes.html
http://www.tensorfly.cn/tfdoc/tutorials/mnist_beginners.html
进入Python环境,然后具体代码如下:
__author__ = 'chapter'
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print("Download Done!")
x = tf.placeholder(tf.float32, [None, 784])
# paras
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])
# loss func
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# init
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
# train
for i in range(1000):
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.arg_max(y, 1), tf.arg_max(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print("Accuarcy on Test-dataset: ", sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
这个有个问题就是加载训练集和测试集的文件时非常慢,
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
我采用的方法是直接到对应的网站上把如下四个文件下载下来:
t10k-images-idx3-ubyte.gz
train-images-idx3-ubyte.gz
t10k-labels-idx1-ubyte.gz
train-labels-idx1-ubyte.gz
然后放到MNIST_data这个目录下
运行结果如下:
('Accuarcy on Test-dataset: ', 0.91289997)
准确率为0.91