Pytorch与深度学习自查手册1-张量、自动求导和GPU
张量
构造Tensor
dtype类型:dtype=torch.long,torch.float,torch.double
常见的构造Tensor的函数:
函数 | 功能 | 示例 |
---|---|---|
Tensor(sizes) | 基础构造函数 | torch.Tensor(4,3) |
tensor(data) | 类似于np.array | x = torch.tensor([5.5, 3]) |
ones(sizes) | 全1 | |
zeros(sizes) | 全0 | x = torch.zeros(4, 3, dtype=torch.long) |
eye(sizes) | 对角为1,其余为0 | |
arange(s,e,step) | 从s到e,步长为step | |
linspace(s,e,steps) | 从s到e,均匀分成step份 | |
rand/randn(sizes) | x = torch.rand(4, 3) | |
normal(mean,std)/uniform(from,to) | 正态分布/均匀分布 | |
empty(sizes) | result = torch.empty(5, 3) torch.add(x, y, out=result) |
基本属性
x.size()
x.shape
常用方法
改变一个 tensor 的大小或者形状,可以使用 torch.view:view() 返回的新tensor与源tensor共享内存(其实是同一个tensor),也即更改其中的一个,另 外一个也会跟着改变。
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)
转置transpose/维度交换permute
x=torch.randn(2,4,3)
s=x.transpose(1,2) #shape=[2,3,4]
z=x.permute(0,2,1) #shape=[2,3,4]
扩展expand
#返回当前张量在某个维度为1扩展为更大的张量
x = torch.Tensor([[1], [2], [3]])#shape=[3,1]
t=x.expand(3, 4)
print(t)
'''
tensor([[1., 1., 1., 1.],
[2., 2., 2., 2.],
[3., 3., 3., 3.]])
'''
重复repeat
#沿着特定的维度重复这个张量
x=torch.Tensor([[1,2,3]])
t=x.repeat(3, 2)
print(t)
'''
tensor([[1., 2., 3., 1., 2., 3.],
[1., 2., 3., 1., 2., 3.],
[1., 2., 3., 1., 2., 3.]])
'''
拼接cat
x = torch.randn(2,3,6)
y = torch.randn(2,4,6)
c=torch.cat((x,y),1)
#c=(2*7*6)
堆叠stack
"""
而stack则会增加新的维度。
如对两个1*2维的tensor在第0个维度上stack,则会变为2*1*2的tensor&#