【pytorch】-张量

torch.einsum

参考文章

1.张量创建

1.1 将已有的转换为张量

data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

1.2 根据维度创建

shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
tensor = torch.full([1,2,3], 5)

1.3 张量属性

rand_tensor.dtype
rand_tensor.shape
rand_tensor.device

2.张量操作

# We move our tensor to the GPU if available
if torch.cuda.is_available():
    tensor = tensor.to("cuda")

2.1 合并张量

x = torch.randn(2, 3)
torch.cat((x, x, x), 0)  # [6, 3]
torch.cat((x, x, x), 1)  # [2, 9]

torch.stack((x, x, x), dim=0) # [3, 2, 3]  添加新维度

2.2 改变张量维度

torch.reshape(a, (2, 2))

2.3 将张量划分为更小的张量

a = torch.arange(10).reshape(5,2)
a
torch.split(a, 2)  # 每一维度都是2,默认dim = 0
torch.split(a, [1,4])  # 列表的话就指明了划分后的每一维度

2.4 将张量压缩/张开

doc

x = torch.zeros(2, 1, 2, 1, 2)
x.size()
y = torch.squeeze(x) # torch.Size([2, 2, 2])
y.size()
y = torch.squeeze(x, 0)  # 没用,第一维不为1
y.size()
y = torch.squeeze(x, 1)
y.size()
x = torch.tensor([1, 2, 3, 4])
torch.unsqueeze(x, 0)
torch.unsqueeze(x, 1)

2.5 改变张量视角

x = torch.randn(2, 3)
x
torch.transpose(x, 0, 1)  # [3, 2]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值