张量
张量是什么?
张量是一个多维数组,它是标量、向量、矩阵的高维拓展。
张量的属性和性质
Variable
Tensor
Tensor 增加 3 种属性
张量的创建
1. 直接创建
torch
.tensor
(
data
,
dtype
=None,
device
=None,
requires_grad
=False,
pin_memory
=False)
torch
.from_numpy
()
2. 依据数值创建
torch
.zeros
(*size
,
out
=None,
dtype
=None,
layout
=torch
.strided
,
device
=None,
requires_grad
=False)
torch
.zeros_like
(input,
dtype
=None,
layout
=None,
device
=None,
requires_grad
=False)
torch
.ones
()
torch
.ones_like
()
torch
.full
(size
,
fill_value
,
)
torch
.arange
(start
=0,
end
,
step
=1)
torch
.linspace
(start
,
end
,
steps
=100)
torch
.logspace
(start
,
end
,
steps
=100,
base
=10.0)
torch
.eye
(n
,
m
=None,
)
3. 依概率分布创建张量
torch
.normal
(mean
,
std
,
out
=None)
四种模式:
mean为标量, std为标量
mean为标量, std为张量
mean为张量, std为标量
mean为张量, std为张量
torch
.randn
(*size
)
torch
.randn_like
()
torch
.rand
(*size
)
torch
.rand_like
()
torch
.randint
()
torch
.randint_like
()
torch
.randperm
(n
)
torch
.bernoulli
()
张量的操作:拼接、切分、索引和变换
张量拼接与切分
拼接
torch
.cat
(tensors
,
dim
=0,
out
=None)
torch
.cat
([torch
.ones
((2, 3)), torch
.ones
((2, 3))], dim
=0)
torch
.stack
(tensors
,
dim
=0,
out
=None)
切分
torch
.chunk
(input,
chunks
,
dim
=0)
torch
.split
(tensor
,
split_size_or_sections
,
dim
=0)
张量索引与变换
索引
torch
.index_select
(input,
dim
,
index
,
out
=None)
torch
.masked_select
(input,
mask
,
out
=None)
变换
torch
.reshape
(input,
shape
)
torch
.transpose
(input,
dim0
,
dim1
)
torch
.t
(input)
torch
.squeeze
(input,
dim
=None,
out
=None)
张量数学运算
torch
.add
()
torch
.addcdiv
()
torch
.addcmul
()
torch
.sub
()
torch
.div
()
torch
.mul
()
torch
.log
(input, out
=None)
torch
.log10
(input, out
=None)
torch
.log2
(input, out
=None)
torch
.exp
(input, out
=None)
torch
.pow()
torch
.abs(input, out
=None)
torch
.acos
(input, out
=None)
torch
.cosh
(input, out
=None)
torch
.cos
(input, out
=None)
torch
.asin
(input, out
=None)
torch
.atan
(input, out
=None)
torch
.atan2
(input, other
, out
=None)
torch
.add
(input,
alpha
=1,
other
,
out
=None)
计算图与动态图机制
计算图:用来描述运算的有向无环图
计算图有两个主要元素: 结点( Node)和边( Edge)
结点表示数据,如向量,矩阵,张量
边表示运算,如加减乘除卷积等
叶子结点:用户创建的结点称为叶子结点,如 X 与 W
is_leaf: 指示张量是否为叶子结点
grad_fn: 记录创建该张量时所用的方法(函数)
动态图vs 静态图
根据计算图搭建方式,可将计算图分为动态图和静态图
动态图:运算与搭建同时进行;灵活 易调节
静态图:先搭建图, 后运算;高效 不灵活
autograd
autograd—自动求导系统
torch
.autograd
.backward
(tensors
,
grad_tensors
=None,
retain_graph
=None,
create_graph
=False)
torch
.autograd
.grad
(outputs
,
inputs
,
grad_outputs
=None,
retain_graph
=None,
create_graph
=False)
如果想保存计算图再次计算,retain_graph 需要设置为 Truegrad_tensors 传入一个张量,不同的梯度有不同的权重torch.autograd.grad() 能计算多阶导数(比如二阶为调用两次,每次的 output 参数不同)
注意:
计算梯度后梯度不会自动清零,需要手动 w.grad.zero_()依赖于叶子结点的结点, requires_grad 默认为 True叶子结点不可执行 in-place 操作,否则反向传播无法计算