0
点赞
收藏
分享

微信扫一扫

pytorch常见运算

小布_cvg 2022-03-14 阅读 70
import torch
a=torch.tensor([[1,2],[3,4]])
b=torch.tensor([[5,6],[7,8]])
#按行进行组合:
c=torch.cat((a,b),dim=0)
# print(c)
# tensor([[1, 2],
#         [3, 4],
#         [5, 6],
#         [7, 8]])
c=torch.cat((a,b),dim=1)
# print(c)
# tensor([[1, 2, 5, 6],
#         [3, 4, 7, 8]])
#stack后维数会升高
c=torch.stack((a,b),dim=0)
print(c.shape)
# print(c)
# tensor([[[1, 2],
#          [3, 4]],
#         [[5, 6],
#          [7, 8]]])

c=torch.stack((a,b),dim=1)
# print(c)
# tensor([[[1, 2],
#          [5, 6]],
#         [[3, 4],
#          [7, 8]]])
#print(c.shape)
c=torch.stack((a,b),dim=2)
# tensor([[[1, 5],
#          [2, 6]],
#         [[3, 7],
#          [4, 8]]])
#大于1的部分填充2,其余填充6:
c=torch.where(a>1,2,6)
# print(c)
# tensor([[6, 2],
#         [2, 2]])
#其最大最小值调整至0至2之间
c=a.clamp(0,2)
# print(c)
# tensor([[1, 2],
#         [2, 2]])
#进行维度互换:
c=torch.tensor([[[1,2],[3,4]]])
print(c.shape)
#torch.Size([1, 2, 2])
c=torch.permute(c,[1,0,2])
#torch.Size([2, 1, 2])
print(c.shape)
#将某个指定维度变为1
c=torch.unsqueeze(c,0)
print(c.shape)
#torch.Size([1, 2, 1, 2])
#再去掉第0维:
c=torch.squeeze(c,0)
#torch.Size([2, 1, 2])
print(c.shape)
print(c.requires_grad)
print(c.storage_type())
#不可求导改为可求导
c=c.float().requires_grad_()
print(c.requires_grad)
举报

相关推荐

0 条评论