tensorflow通过pip安装和手写数字检测

一、安装tensorflow

安装 TensorFlow方法有很多:通过 Pip, Docker, Virtualenv, Anaconda 或 源码编译的方法。具体安装哪一种,看具体需求,比如操作系统是windows还是linux,是否需要单独编译等等。


作为学习入门者,主要精力应该是尽快开启搭模型的阶段,而不是把大把时间花在各种坑爹的安装上。我在windows系统下用virtualbox搭建了虚拟机,ubantu16.0.4系统。选择用pip实现傻瓜式的安装:

1,在终端中输入 python -V 或者 python3 -V,发现python2python3都已经安装好了。用哪一个都行,这里我选择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) 测试集或验证集上进行准确率评估。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值