tensor操作中的api和numpy非常相似
1、基本操作
x = torch.ones(2,2)
print(x)
x.type()
# 将其转换为整型
x = x.long()
print(x)
# 再将其转回float
x = x.float()
print(x)
x = torch.randn(4,3)
print(x)
# 沿着行取最大值
max_value, max_idx = torch.max(x, dim=1)
# 沿着行对x求和
sum_x = torch.sum(x, dim=1)
print(sum_x)
2、增加维度或者减少维度
print(x.shape)
x = x.unsqueeze(0)
print(x.shape)
> torch.Size([4, 3])
> torch.Size([1, 4, 3])
x = x.unsqueeze(1) # 在第二维增加
print(x.shape)
> torch.Size([1, 1, 4, 3])
x = x.squeeze(0) # 减少第一维
print(x.shape)
> torch.Size([1, 4, 3])
x = x.squeeze()
print(x.shape)
> torch.Size([4, 3])
3、维度交换
x = torch.randn(3,4,5)
print(x.shape)
> torch.Size([3, 4, 5])
# 使用permute和transpose进行维度交换
x = x.permute(1,0,2)
print(x.shape)
>torch.Size([4, 3, 5])
# transpose交换tensor中的两个维度
x = x.transpose(0,2)
print(x.shape)
> torch.Size([5, 3, 4])
4、使用view对tensor进行reshape
x = torch.randn(3,4,5)
x = x.view(-1, 5)
# -1 表示任意的大小,5表示第二维变成5
print(x.shape)
# 重新reshape成(3, 2, 10)的大小
x = x.view(3,2,10)
print(x.shape)
5、求和
x = torch.randn(3,4)
y = torch.randn(3,4)
# 两个tensor求和
z = x + y
# z = torch.add(x,y)
6、inplace操作
pytorch中大多数的操作都支持inplace操作,也就是可以直接对tensor进行操作而不需要另外开辟内存空间,方式非常简单,一般都是在操作的符号后面加_,比如
x = torch.ones(3, 3)
print(x.shape)
# unsqueeze 进行inplace
x.unsqueeze_(0)
print(x.shape)
# transpose 进行inplace
x.transpose_(1,0)
print(x.shape)
x = torch.ones(3, 3)
y = torch.ones(3, 3)
print(x)
x.add_(y)
print(x)