TensorFlow 之 入门体验

TensorFlow:2015年Google开源的机器学习框架。

官方网站:[url=https://www.tensorflow.org/]https://www.tensorflow.org/[/url]
官方GitHub仓库:[url=https://github.com/tensorflow/tensorflow]https://github.com/tensorflow/tensorflow[/url]
官方文档:[url=https://www.tensorflow.org/get_started/]https://www.tensorflow.org/get_started/[/url]
官方文档中文版:[url=https://github.com/jikexueyuanwiki/tensorflow-zh]https://github.com/jikexueyuanwiki/tensorflow-zh[/url]

Tensor(张量)表示N维数组,Flow(流)表示基于流图的数据计算,TensorFlow为张量从图的一端流到另一端的计算过程。TensorFlow是将复杂的数据结构传输至人工智能神经网中进行分析和处理的系统。TensorFlow支持CNN、RNN和LSTM算法,这些都是目前在图像,语音和自然语言处理领域最流行的深度神经网络模型。采用C++编写,主要提供Python API,也支持C++、Java、Go等。

学习TensorFlow需要具备的知识:数学统计基础(线性代数、概率与统计、多元微积分)、Python(NumPy 科学计算、Scipy 矩阵计算、Pandas 数据分析、Matplotlib 绘图)。

TensorFlow源代码(C++、Python)已超过40w行,确实不是一个能够迅速上手的小项目。

版本:
CentOS 7.2 + Python 2.7.5 + TensorFlow 1.2.0

[b]TensorFlow 0.6.0后支持Python 3.3+、0.12.0后开始支持Windows。推荐在Linux的Python3.5上运行。[/b]

相关文章:
[url=http://rensanning.iteye.com/blog/2381794]TensorFlow 之 入门体验[/url]
[url=http://rensanning.iteye.com/blog/2382529]TensorFlow 之 手写数字识别MNIST[/url]
[url=http://rensanning.iteye.com/blog/2381885]TensorFlow 之 物体检测[/url]
[url=http://rensanning.iteye.com/blog/2383607]TensorFlow 之 构建人物识别系统[/url]

[b](1)安装Python[/b]
# python -V
Python 2.7.5
# yum -y install epel-release
# yum -y install python-pip
# yum -y install python-devel


也可以安装Python3
[quote]# yum install -y https://centos7.iuscommunity.org/ius-release.rpm
# yum install -y python35u python35u-devel python35u-pip
# python3.5 -V
Python 3.5.3
# which python3.5
/usr/bin/python3.5[/quote]
从ius可以安装python34u、python35u、python36u。

[b](2)安装TensorFlow[/b]
# pip install --upgrade virtualenv
# virtualenv -p /usr/bin/python --system-site-packages /usr/local/tensorflow2
# source /usr/local/tensorflow2/bin/activate
# python -V
Python 2.7.5
# pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.2.0-cp27-none-linux_x86_64.whl

*** Google官方推荐通过VirtualEnv构建(创建独立的多Python虚拟环境),这里安装CPU版本也可以安装基于英伟达的GPU版本
*** 通过pip安装是最快的,需要更多定制设置时需要通过源码编译安装
*** 也可以通过Anaconda(用于科学计算的Python发行版) https://www.continuum.io/downloads 安装
*** 还可以通过Docker镜像安装

确认是否支持GPU
# lspci | grep -i nvidia

对比 [url=https://developer.nvidia.com/cuda-gpus]https://developer.nvidia.com/cuda-gpus[/url] 如果GPU支持cuda,就可以安装GPU版。

如果不是从代码安装的TensorFlow,每次执行时都会有以下警告:
[quote]W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.[/quote]

[b](3)环境确认[/b]

[b]确认python[/b]
[code="shell"](tensorflow2) # vi hello.py
print("Hello, Python!")
(tensorflow2) # python hello.py
Hello, Python![/code]

[b]确认tensorflow[/b]
[code="shell"](tensorflow2) # vi hello_tf.py
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
(tensorflow2) # python hello_tf.py
Hello, TensorFlow![/code]
*** python3输出的是“b'Hello, TensorFlow!'”

[code="shell"](tensorflow2) # python
>>> import tensorflow as tf
>>> hello = tf.constant('Hello, TensorFlow!');
>>> sess = tf.Session()
>>> print(sess.run(hello))
Hello, TensorFlow![/code]

[b]退出当前环境[/b]
[code="sehll"](tensorflow2) # deactivate[/code]

[b](4)卸载TensorFlow[/b]
# rm -rf /usr/local/tensorflow2


[b](5)TensorFlow基础[/b]

[b]引入[/b]
import tensorflow as tf


[b]常量[/b]
const2 = tf.constant(3)


[b]变量[/b]
var1 = tf.Variable(0)


[b]符号变量[/b]
holder2 = tf.placeholder(tf.int32)


[b]运算[/b]
add_op = tf.add(var1, const2)
update_var1 = tf.assign(var1, add_op)
mul_op = tf.multiply(add_op, update_var1)


[b]会话[/b]
tf.Session()

调用sess的run方法来启动整个graph,执行程序
*** 在TensorFlow代码中没有if-else来控制代码逻辑,完全是由数据驱动

举例:
# vi add_tf.py
# python add_tf.py

# Import the library
import tensorflow as tf

# Define the graph
const1 = tf.constant(2)
const2 = tf.constant(3)
add_op = tf.add(const1, const2)

# Define the session to run graph
with tf.Session() as sess:
result = sess.run(add_op)
print(result)


版本问题:从1.0开始API变化比较大,一些API已经被移除,比如
[quote]tf.mul() -> tf.multiply()
tf.sub() -> tf.subtract()
tf.neg() -> tf.negative()
tf.summary.scalar() -> tf.scalar_summary()
tf.summary.merge_all() -> tf.merge_all_summaries()
tf.summary.FileWriter() -> tf.train.SummaryWriter()
tf.global_variables_initializer() -> tf.initialize_all_variables() [/quote]
等。
具体可以看官方的 [url=https://github.com/tensorflow/tensorflow/blob/master/RELEASE.md#breaking-changes-to-the-api-1]Release Notes[/url],或者这里:[url=http://www.jianshu.com/p/04850ffc1021]http://www.jianshu.com/p/04850ffc1021[/url]

TensorFlow也同时提供了代码自动升级工具:[url=https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/compatibility]https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/compatibility[/url]
# python tf_upgrade.py --infile sample1.py --outfile sample.py


[b]基本概念[/b]
[list]
[*]图(Graph):图描述了计算的过程,TensorFlow使用图来表示计算任务。 计算图(Computational Graph)
[*]张量(Tensor):TensorFlow使用tensor表示数据。每个Tensor是一个类型化的多维数组。
[*]操作(Operation):图中的节点,一个op获得0个或多个Tensor,执行计算,产生0个或多个Tensor。
[*]会话(Session):图必须在“会话”的上下文中被执行。会话将图的op分发到CPU或GPU之类的设备上执行。
[*]变量(Variable):运行过程中可以被改变,用于维护状态。(placeholder:占位符变量、feed_dict:传递数据)[/list]
TensorFlow虽然封装了大部分深度学习的细节,但还是需要了解深度学习的一些核心概念,比如:
- 用于图像识别的卷积神经网络(CNN, Convolutional Neural Network)
- 用于自然语言处理的循环神经网络(RNN, Recurrent Neural Networks)

[b](6)TensorBoard 可视化界面[/b]
import tensorflow as tf

x = tf.constant(1.0, name='input')
w = tf.Variable(0.8, name='weight')
y = tf.multiply(w, x, name='output')
y_ = tf.constant(0.0, name='correct_value')
loss = tf.pow(y - y_, 2, name='loss')
train_step = tf.train.GradientDescentOptimizer(0.025).minimize(loss)

for value in [x, w, y, y_, loss]:
tf.summary.scalar(value.op.name, value)

summaries = tf.summary.merge_all()

sess = tf.Session()
summary_writer = tf.summary.FileWriter('log_simple_stats', sess.graph)

sess.run(tf.global_variables_initializer())
for i in range(100):
summary_writer.add_summary(sess.run(summaries), i)
sess.run(train_step)

# vi sample_tb.py
# python sample_tb.py
# tensorboard --logdir=log_simple_stats

访问以下URL:
[color=blue]http://localhost:6006/#scalars[/color]
[img]http://dl2.iteye.com/upload/attachment/0125/7200/fe2c8112-2caa-3d88-950c-486711b2394c.png[/img]

[color=blue]http://localhost:6006/#graphs[/color]
[img]http://dl2.iteye.com/upload/attachment/0125/7202/afd8e8c0-9552-323e-892b-098308eaa1f4.png[/img]

[b](7)下载TensorFlow Models[/b]
# cd /usr/local/src/
# wget https://codeload.github.com/tensorflow/models/zip/master -O tensorflow-models-master.zip
# unzip tensorflow-models-master.zip
# mv models-master/ /usr/local/tensorflow2/tensorflow-models/


[b](8)图像识别[/b]
[code="shell"]# source /usr/local/tensorflow2/bin/activate
(tensorflow) # cd /usr/local/tensorflow2/tensorflow-models/tutorials/image/imagenet/
(tensorflow) # python classify_image.py[/code]
[quote]giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca (score = 0.89107)
indri, indris, Indri indri, Indri brevicaudatus (score = 0.00779)
lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens (score = 0.00296)
custard apple (score = 0.00147)
earthstar (score = 0.00117)[/quote]

使用在 ImageNet 2012 比赛数据集上训练过的 Inception 模型,识别 JPEG 图像给出最高概率的 5 个预测结果。
默认识别的是一张熊猫的图片/tmp/imagenet/cropped_panda.jpg。
[img]http://dl2.iteye.com/upload/attachment/0125/7194/202f79b5-c707-321c-b925-ae983350229c.jpg[/img]

可以通过参数--image_file来指定任意图片。

测试一张猫的图片:
[img]http://dl2.iteye.com/upload/attachment/0125/7198/c15b8c5e-18d1-3ade-8c8f-97e69a65a56c.jpg[/img]
[code="shell"](tensorflow) # python classify_image.py --image_file=/tmp/cat-test.jpg[/code]
[quote]Persian cat (score = 0.89983)
tabby, tabby cat (score = 0.01014)
Egyptian cat (score = 0.00906)
lynx, catamount (score = 0.00490)
Angora, Angora rabbit (score = 0.00378)[/quote]

测试一张狗的图片:
[img]http://dl2.iteye.com/upload/attachment/0125/7196/32cf56cc-8f63-370b-b7ef-2c7cebe3a255.jpg[/img]
[code="shell"](tensorflow) # python classify_image.py --image_file=/tmp/dog-test.jpg[/code]
[quote]Siberian husky (score = 0.46671)
Eskimo dog, husky (score = 0.38190)
dogsled, dog sled, dog sleigh (score = 0.02570)
malamute, malemute, Alaskan malamute (score = 0.00802)
timber wolf, grey wolf, gray wolf, Canis lupus (score = 0.00114)[/quote]

[b](9)其他[/b]

[b]机器学习方法分类:[/b]
1)监督学习Supervised Learning: 也叫有教师学习,提供正确的数据,推测未知数据、分类回归
2)无监督学习Unsupervised Learning: 也叫无教师学习,没有正确的数据可以学习,实时数据处理、异常检测、clustering
3)强化学习Reinforcement Learning: 象棋、围棋等
*** 结果均为推荐结果,不是唯一结果。

[b]主要应用:[/b]
图像识别(验证码、车牌号、各种物体、手写字符等)、声音识别、文字处理、搜索引擎、过滤垃圾邮件、推荐系统、预测系统、医疗诊断、机器人、侦测服务器攻击等等

[b]自然语言处理NLP:[/b]
1)word2vec模型:
例如vector('queen') ~= vector('king') - vector('man') + vector('woman') (女王~=国王-男人+女人)
2)Seq2seq模型:
例如输入(hello) -> 输出 (你好)

[b]视觉领域的开源数据集:[/b]

1)MNIST http://yann.lecun.com/exdb/mnist/
由Yann LeCun(杨乐坤)建立的手写数字库,相当于机器学习界的Hello World。
它有60000个训练样本集和10000个测试样本集,

2)ImageNet http://www.image-net.org/
由斯坦福Fei Fei(李飞飞)教授主导创建的图像分类数据集,计算机视觉领域的标准参照集。
有1400多万幅图片,涵盖2万多个类别

3)CIFAR http://www.cs.utoronto.ca/~kriz/cifar.html
CIFAR-10有10个分类,每个分类有已经标记的5000张训练图片和1000张测试图片
CIFAR-100有100个分类,每个分类变成了500张训练图片+100张测试图片

4)Oxford-IIIT Pet Dataset http://www.robots.ox.ac.uk/~vgg/data/pets/
和CIFAR-10类似,主要是动物系图像。目前有37个分类,每个分类有200多张图像。

5)MS COCO http://mscoco.org/
由微软赞助,除过对图像分类外还有对图像的语义文本描述。
有80个分类大约8万多张图片

6)Pascal VOC Challenge http://host.robots.ox.ac.uk/pascal/VOC/index.html
提供了一整套标准化的图像识别和分类的数据集,用于每年一次的挑战。

7)Kaggle https://www.kaggle.com/
数据建模和数据分析竞赛平台,已被Google收购。

[b]常见文件:[/b]

protocol相关
.proto文件: 定义 protocol buffer message 类型,指定序列化的结构数据
.pb文件: 保存序列化之后的对象的二进制文件
.pbtxt文件: 保存序列化之后的对象的文本文件(可读,占用磁盘空间大)

.ckpt文件: checkpoint文件,saver.save(sess)的输出。等价于.ckpt-data。
.ckpt-meta文件: 包含了metagraph,比如计算图的结构,但不包含变量的值。
.ckpt-data文件和.ckpt-index文件: 包含了变量的值,但不包含计算图。
.pb文件: 保存了整个计算图及数据(meta + data),可加载继续使用。
.pbtxt文件: 文本化的pb文件
.record 文件和.tfrecords 文件: TFRecord文件,保存图像数据和标签的二进制文件,官方推荐的数据读取方式。

[b]学习资源:[/b]
https://github.com/jtoy/awesome-tensorflow
https://github.com/BinRoot/TensorFlow-Book
https://github.com/astorfi/TensorFlow-World
https://github.com/nfmcclure/tensorflow_cookbook
https://github.com/pkmital/tensorflow_tutorials
https://github.com/aymericdamien/TensorFlow-Examples/
https://github.com/nlintz/TensorFlow-Tutorials
http://learningtensorflow.com/
http://www.deeplearningbook.org/

[b]高级运用:[/b]
动态计算图 Tensorflow Fold https://github.com/tensorflow/fold
调试 tfdbg https://www.tensorflow.org/programmers_guide/debugger
部署 TensorFlow Serving https://tensorflow.github.io/serving/
分布式 tf.train.ClusterSpec https://www.tensorflow.org/deploy/distributed
框架(High-Level API)
TFLearn http://tflearn.org/
Keras https://keras.io/
Sonnet https://github.com/deepmind/sonnet
TF-Slim https://github.com/tensorflow/models/tree/master/inception/inception/slim

[b]学习视频:[/b]
Andrew Ng的机器学习课程:
[url=http://open.163.com/special/opencourse/machinelearning.html]http://open.163.com/special/opencourse/machinelearning.html[/url]
Fei-Fei Li CS231n深度学习与计算机视觉:
[url=http://study.163.com/course/introduction/1003223001.htm]http://study.163.com/course/introduction/1003223001.htm[/url]
Deep Learning by Google
[url=https://www.udacity.com/course/deep-learning--ud730]https://www.udacity.com/course/deep-learning--ud730[/url]

- Tensorflow and deep learning - without a PhD by Martin Görner
[color=blue]https://www.youtube.com/watch?v=vq2nnJ4g6N0[/color]
- Tensorflow tutorials (Eng Sub) 神经网络教学教程 周莫烦
[color=blue]https://www.youtube.com/playlist?list=PLXO45tsB95cKI5AIlf5TxxFPzb-0zeVZ8[/color]
- Tensorflow tutorials (中文)
[color=blue]https://www.youtube.com/playlist?list=PLnUknG7KBFzqMSDZC1mnYMN0zMoRaH68r[/color]
- TensorFlow Tutorial 修炼指南
[color=blue]https://www.youtube.com/playlist?list=PLwY2GJhAPWRcZxxVFpNhhfivuW0kX15yG[/color]
- Machine Learning Recipes with Josh Gordon
[color=blue]https://www.youtube.com/playlist?list=PLOU2XLYxmsIIuiBfYad6rFYQU_jL2ryal[/color]
- Deep Learning with Tensorflow
[color=blue]https://www.youtube.com/playlist?list=PL-XeOa5hMEYxNzHM7YLRjIwE1k3VQpqEh[/color]

参考:
https://www.oreilly.com/learning/hello-tensorflow
https://eatcodeplay.com/installing-tensorflow-with-python-3-on-ec2-gpu-instances-f9fa199eb3cc
https://research.googleblog.com/2017/06/supercharge-your-computer-vision-models.html
https://cloud.google.com/blog/big-data/2017/01/learn-tensorflow-and-deep-learning-without-a-phd
https://cloud.google.com/blog/big-data/2017/06/training-an-object-detector-using-cloud-machine-learning-engine
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值