一、安装tensorflow
安装 TensorFlow方法有很多:通过 Pip, Docker, Virtualenv, Anaconda 或 源码编译的方法。具体安装哪一种,看具体需求,比如操作系统是windows还是linux,是否需要单独编译等等。
作为学习入门者,主要精力应该是尽快开启搭模型的阶段,而不是把大把时间花在各种坑爹的安装上。我在windows系统下用virtualbox搭建了虚拟机,ubantu16.0.4系统。选择用pip实现傻瓜式的安装:
1,在终端中输入 python -V 或者 python3 -V,发现python2和python3都已经安装好了。用哪一个都行,这里我选择python3。
安装pip:执行 sudo apt install python3-pip
2,接下来配置pip源,使用国内的pip源会比官方的快一些。。。
常用的有:
清华:https://pypi.tuna.tsinghua.edu.cn/simple
豆瓣:http://pypi.douban.com/simple/
临时使用可以在pip的时候加参数 -i https://pypi.tuna.tsinghua.edu.cn/simple
3,安装TensorFlow:
sudo -H pip3 install --upgrade tensorflow --proxy dev-proxy.oa.com:8080
--proxy是代理设置,主要是因为公司不能直接上外网。、
测试tensorflow
$ python3
...
>>> import tensorflow as tf
>>> hello = tf.constant('Hello, TensorFlow!')
>>> sess = tf.Session()
>>> print(sess.run(hello))
Hello, TensorFlow!
>>> a = tf.constant(10)
>>> b = tf.constant(32)
>>> print(sess.run(a + b))
42
完成安装。
(二)手写字符识别
首先,下载手写数字数据集MNIST,原下载地址已经不能用,Lecun主页上提供了数据集的四个文件,http://yann.lecun.com/exdb/mnist/ ,下载下来后放入一个自定义的文件中。我命名为MNIST_data。然后读取数据:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
然后可以数据格式:
print(mnist.train.images.shape, mnist.trian.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape, mnist.validation.labels.shape)
然后用softmax regression实现一个最简单的多分类:
>>> import tensorflow as tf
>>> sess = tf.InteractiveSession()
>>> x= tf.placeholder(tf.float32,[None,784])
>>> 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])
>>> cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))
>>> train_step=tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
>>> tf.global_variables_initializer().run()
>>> for i in range(1000):
... batch_xs, batch_ys=mnist.train.next_batch(100);\
... train_step.run({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(accuracy.eval({x:mnist.test.images, y_:mnist.test.labels}))
0.9157
这个简单的例子体现了tensorflow的基本流程:
(1) 定义算法公式,即forward计算,同时还包括算法;
(2) 定义loss, 这里使用cross_entropy, 同时指定优化器;
(3) 迭代地对数据进行训练;
(4) 测试集或验证集上进行准确率评估。