Tensorflow2.0的简介
Tensorflow1.X版本有哪些问题?
- 调试困难
- API混乱不堪
- 导致从入门到放弃
为什么使用Tensorflow,而不是Pytroch呢?
- GPU加速
- 自动求导
- 神经网络Layers
最大改变就是移除tf.contrib,分别用tf.keras tf.losses tf.metrices等开代替
使用免费薅羊毛的Google colab做简单说明:
import tensorflow as tf
import timeit
# 定义两个矩阵,并求乘机,使用GPU加速计算
with tf.device('/gpu:0'):
mat_a = tf.random.normal([1000,800])
mat_b = tf.random.normal([800,600])
def run():
with tf.device('/gpu:0'):
result = tf.matmul(mat_a, mat_b)
return result
# 计算10次的时间
run_time = timeit.timeit(run, number=10)
print('run_time: ', run_time)
run_time: 0.0023373889998765662 #速度飞快,远高于CPU
import tensorflow as tf
import os
# 设置显示框显示信息等级,更清爽
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
x = tf.constant(1.)
a = tf.constant(2.)
b = tf.constant(3.)
# 新增tf.GradientTape 用于自动微分运算
with tf.GradientTape() as tape:
tape.watch([a, b])
y = a**2 * x + b * x
# 分别计算y对a和b的求导值
[da, db] = tape.gradient(y, [a, b])
print(da, db)
tf.Tensor(4.0, shape=(), dtype=float32) tf.Tensor(1.0, shape=(), dtype=float32)
e=(), dtype=float32) tf.Tensor(1.0, shape=(), dtype=float32)