2021.3.23
AD
保存较少的中间变量
Tensor N维数组
def softmax(x):
s=0
for i in x:
s+=np.exp(i)
return np.array(np.exp(x)/s)
import tensorflow as tf
实质是具有统一类型的N维数组
tf.constant(
value,
dtype=None,
shape=None,
name='Const',
verify_shape=False
)
0,1,2,3维张量
r0_tensor=tf.constant(4)
r1_tensor=tf.constant([2.,3.,4.])
r2_tensor=tf.constant([[2.,3.,4.],
[5,6,7]],dtype=tf.float16)
shape(3,2,4,5)从大到小分区定义
张量转换为numpy数组
r2_tensor.numpy() #以numpy形式调用
np.array(r2_tensor) #创建numpy数组
四则运算
tf.add()
a+b
tf.multiply()
a*b
tf.matmul()
a @ b
张量运算符运算(op)
执行张量数据类型转换
tf.cast(x,dtype,name=None)
tf.cast(r1_tensor,dtype= tf.uint8)
Tensor reshape
遵循标准Python索引
- 从0开始
- -1,-2倒序
- 冒号用于切片 start:step:stop
- 左闭右开
单轴
r3_tensor[::-1].numpy()
多轴切片
r2_tensor[1,1]
>>> 6
r2_tensor[:,1]
r2_tensor[:,1:]
>>> [[3,4],[6,7]]
特殊张量表示
tf.Tensor(b'Gray wolf',shape=(),dtype=string) #字符串张量
字符串张量
稀疏张量
a=tf.Variable([2.0,3.0])
a.shape
a.dtype
a.numpy()
a.trainable() #bool 自动微分
tf.Variable([5,6]) #可以是常量、变量或numpy
变量的值可以通过assign
函数更改
autodiff
梯度带
持久梯度带
记录控制流
#example
import tensorflow as tf
x=tf.constant(1.0)
with tf.GradientTape() as t:
t.watch(x)
y=x*x+tf.exp(x)
dy_dx=t.gradient(y,x)
del t
dy_dx.numpy()
>>> 4.7182817
进行高阶导数求导
d2y_dx2=t.gradient(dy_dx,x)