深度学习框架介绍
1. TensorFlow发展历程
(1) 2015
- Scikit-learn
- Machine Learning,No GPU
- Caffe
- 2013,第一个面向深度学习的框架
- No auto-grad,C++
- Keras
- wrapper
- Theano
- 开发难,调试难
- Torch
- Lua语言
(2) TensorFlow
- Caffe
- Facebook,Caffe → \to → Torch
- Torch → \to → PyTorch
- Theano
- Google, → \to → TensorFlow
- TensorFlow → \to → TensorFlow2
- Chainer
- MXNet
(3) 2017: TensorFlow1.0
- tf.contrib
- tf.layers,tf.metrics,tf.losses
- tfdbg
- PyTorch 0.1
(4) TensorFlow 1.X 缺点
- 调试困难
- API混乱
- 入门困难,入了门依旧困难
- 大批研究人员转向PyTorch
(5) 2019
- TensorFlow 2.0 发布
- TF+Keras
- 更容易使用
去掉了一些概念,例如:
session.run
tf.comtrol_dependencies
tf.global_variables_initializer
tf.cond,tf.while_loop
2. TensorFlow eco-system
(1) TensorFlow 2.0
TensorFlow核心库
- @tf.function
将动态图的语言变为静态图,使计算加速。
(2) TensorFlow Lite
(3) TensorFlow.JS
(4) TensorFlow Extended
TensorFlow Lite、TensorFlow.JS、TensorFlow Extended构成了TensorFlow的生态系统,从这点上看,TensorFlow是领先于PyTorch的。
(5) TensorFlow Prob
(6) TPU Cloud
Google自己研发的加速硬件。
3. 学习建议
(1) 忘掉TensorFlow 1.X
(2) PyTorch和TensorFlow选一主修(二者都要掌握)
(3) Keras逐渐淡出(已经被Google收购了)
- TF+Keras
- PyTorch+Caffe2
4. 为什么要使用TensorFlow
- GPU加速
- 自动求导
- 神经网络Layers
(1) GPU加速
GPU和CPU对比
import tensorflow as tf
import timeit
with tf.device('/cpu:0'):
cpu_a = tf.random.normal([10000, 1000])
cpu_b = tf.random.normal([1000, 2000])
print(cpu_a.device, cpu_b.device)
with tf.device('/gpu:0'):
gpu_a = tf.random.normal([10000, 1000])
gpu_b = tf.random.normal([1000, 2000])
print(gpu_a.device, gpu_b.device)
def cpu_run():
with tf.device('/cpu:0'):
c = tf.matmul(cpu_a, cpu_b)
return c
def gpu_run():
with tf.device('/gpu:0'):
c = tf.matmul(gpu_a, gpu_b)
return c
# warm up
cpu_time = timeit.timeit(cpu_run, number=10)
gpu_time = timeit.timeit(gpu_run, number=10)
print('warmup:', cpu_time, gpu_time)
cpu_time = timeit.timeit(cpu_run, number=10)
gpu_time = timeit.timeit(gpu_run, number=10)
print('run time:', cpu_time, gpu_time)
运行结果:
可以看到,使用GPU运行要比使用CPU运行快(正常是快很多,我用的MacBook运行的)。
(2) 自动求导
例子:
y
=
a
2
∗
x
+
b
∗
x
+
c
y=a^2*x+b*x+c
y=a2∗x+b∗x+c
其中:
x
=
1
;
a
=
2
;
b
=
3
;
c
=
4
x=1;a=2;b=3;c=4
x=1;a=2;b=3;c=4
代码如下:
import tensorflow as tf
x = tf.constant(1.)
a = tf.constant(2.)
b = tf.constant(3.)
c = tf.constant(4.)
with tf.GradientTape() as tape:
tape.watch([a, b, c])
y = a**2 * x + b * x + c
[dy_da, dy_db, dy_dc] = tape.gradient(y, [a, b, c])
print(dy_da, dy_db, dy_dc)
运行结果:
(3) 神经网络API
神经网络API | 神经网络API |
---|---|
tf.matmul | layers.Dense |
tf.nn.conv2d | layers.Conv2D |
tf.nn.relu | layers.SimpleRNN |
tf.nn.max_pool2d | layers.LSTM |
tf.nn.sigmoid | layers.ReLU |
tf.nn.softmax | layers.MAxPool2D |
参考文献:
[1] 龙良曲:《深度学习与TensorFlow2入门实战》