ITeye博客

TensorFlow 之 入门体验

rensanning · 2017-06-28 09:51 · TensorFlow · 企业架构 · Markdown

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

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

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

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

相关文章: TensorFlow 之 入门体验 TensorFlow 之 手写数字识别MNIST TensorFlow 之 物体检测 TensorFlow 之 构建人物识别系统

(1)安装Python

# python -V
Python 2.7.5
# yum -y install epel-release
# yum -y install python-pip
# yum -y install python-devel

也可以安装Python3

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

从ius可以安装python34u、python35u、python36u。

(2)安装TensorFlow

# 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

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

如果不是从代码安装的TensorFlow,每次执行时都会有以下警告:

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.

(3)环境确认

确认python

(tensorflow2) [root@localhost local]# vi hello.py
print("Hello, Python!")
(tensorflow2) [root@localhost local]# python hello.py
Hello, Python!

确认tensorflow

(tensorflow2) [root@localhost local]# vi hello_tf.py
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
(tensorflow2) [root@localhost local]# python hello_tf.py
Hello, TensorFlow!

*** python3输出的是“b'Hello, TensorFlow!'”

(tensorflow2) [root@localhost local]# python
>>> import tensorflow as tf
>>> hello = tf.constant('Hello, TensorFlow!');
>>> sess = tf.Session()
>>> print(sess.run(hello))
Hello, TensorFlow!

退出当前环境

(tensorflow2) [root@localhost local]# deactivate

(4)卸载TensorFlow

# rm -rf /usr/local/tensorflow2

(5)TensorFlow基础

引入

import tensorflow as tf

常量

const2 = tf.constant(3)

变量

var1 = tf.Variable(0)

符号变量

holder2 = tf.placeholder(tf.int32)

运算

add_op = tf.add(var1, const2)
update_var1 = tf.assign(var1, add_op)
mul_op = tf.multiply(add_op, update_var1)

会话

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已经被移除,比如

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()

等。 具体可以看官方的 Release Notes,或者这里:http://www.jianshu.com/p/04850ffc1021

TensorFlow也同时提供了代码自动升级工具:https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/compatibility

# python tf_upgrade.py --infile sample1.py --outfile sample.py

基本概念

图(Graph):图描述了计算的过程,TensorFlow使用图来表示计算任务。 计算图(Computational Graph) 张量(Tensor):TensorFlow使用tensor表示数据。每个Tensor是一个类型化的多维数组。 操作(Operation):图中的节点,一个op获得0个或多个Tensor,执行计算,产生0个或多个Tensor。 会话(Session):图必须在“会话”的上下文中被执行。会话将图的op分发到CPU或GPU之类的设备上执行。 变量(Variable):运行过程中可以被改变,用于维护状态。(placeholder:占位符变量、feed_dict:传递数据) TensorFlow虽然封装了大部分深度学习的细节,但还是需要了解深度学习的一些核心概念,比如:

  • 用于图像识别的卷积神经网络(CNN, Convolutional Neural Network)
  • 用于自然语言处理的循环神经网络(RNN, Recurrent Neural Networks)

(6)TensorBoard 可视化界面

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: http://localhost:6006/#scalars

http://localhost:6006/#graphs

(7)下载TensorFlow Models

# 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/

(8)图像识别

# source /usr/local/tensorflow2/bin/activate
(tensorflow) [root@localhost ~]# cd /usr/local/tensorflow2/tensorflow-models/tutorials/image/imagenet/
(tensorflow) [root@localhost ~]# python classify_image.py

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)

使用在 ImageNet 2012 比赛数据集上训练过的 Inception 模型,识别 JPEG 图像给出最高概率的 5 个预测结果。 默认识别的是一张熊猫的图片/tmp/imagenet/cropped_panda.jpg。

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

测试一张猫的图片:

(tensorflow) [root@localhost imagenet]# python classify_image.py --image_file=/tmp/cat-test.jpg

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)

测试一张狗的图片:

(tensorflow) [root@localhost imagenet]# python classify_image.py --image_file=/tmp/dog-test.jpg

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)

(9)其他

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

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

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

视觉领域的开源数据集:

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收购。

常见文件:

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文件,保存图像数据和标签的二进制文件,官方推荐的数据读取方式。

学习资源: 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/

高级运用: 动态计算图 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

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

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

参考: 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

评论(1)

  1. #1 楼 · it_node · 2017-11-02 15:56

    写的真不错,这里推荐一个有配套的在线环境的不用安装直接对照文章内容就可以练习的,有兴趣的可以去试试:

    (http://xc.hubwiz.com/course/

评论功能维护中,当前仅展示历史评论。