如何沿特定维度向 PyTorch 张量添加元素?
How can I add an element to a PyTorch tensor along a certain dimension?
我有一个张量 inps
,大小为 [64, 161, 1]
,我有一些新数据 d
,大小为 [64, 161]
。如何将 d
添加到 inps
以使新尺寸为 [64, 161, 2]
?
您必须首先重塑 d
以便它具有第三个维度,沿着这个维度可以进行串联。当它有了第三个维度后,两个张量的维度数相同,那么就可以用torch.cat((inps, d),2)来叠加了。
old_shape = tuple(d.shape)
new_shape = old_shape + (1,)
inps_new = torch.cat( (inps, d.view( new_shape ), 2)
使用 .unsqueeze()
和 torch.cat()
有一种更简洁的方法,它直接使用 PyTorch 接口:
import torch
# create two sample vectors
inps = torch.randn([64, 161, 1])
d = torch.randn([64, 161])
# bring d into the same format, and then concatenate tensors
new_inps = torch.cat((inps, d.unsqueeze(2)), dim=-1)
print(new_inps.shape) # [64, 161, 2]
本质上,解压缩第二个维度已经使两个张量具有相同的形状;你只需要小心沿着正确的维度解压。
同样,不幸的是, concatenation 的名称与名称相似的 NumPy 函数不同,但行为相同。请注意,不是让 torch.cat
通过提供 dim=-1
来计算维度,您还可以显式提供要连接的维度,在这种情况下,将其替换为 dim=2
.
记住,这对张量维度的类似问题很有帮助。
或者,您可以通过压缩较大的张量和堆叠来实现:
inps = torch.randn([64, 161, 1])
d = torch.randn([64, 161])
res = torch.stack((inps.squeeze(), d), dim=-1)
res.shape
>>> [64, 161, 2]
我有一个张量 inps
,大小为 [64, 161, 1]
,我有一些新数据 d
,大小为 [64, 161]
。如何将 d
添加到 inps
以使新尺寸为 [64, 161, 2]
?
您必须首先重塑 d
以便它具有第三个维度,沿着这个维度可以进行串联。当它有了第三个维度后,两个张量的维度数相同,那么就可以用torch.cat((inps, d),2)来叠加了。
old_shape = tuple(d.shape)
new_shape = old_shape + (1,)
inps_new = torch.cat( (inps, d.view( new_shape ), 2)
使用 .unsqueeze()
和 torch.cat()
有一种更简洁的方法,它直接使用 PyTorch 接口:
import torch
# create two sample vectors
inps = torch.randn([64, 161, 1])
d = torch.randn([64, 161])
# bring d into the same format, and then concatenate tensors
new_inps = torch.cat((inps, d.unsqueeze(2)), dim=-1)
print(new_inps.shape) # [64, 161, 2]
本质上,解压缩第二个维度已经使两个张量具有相同的形状;你只需要小心沿着正确的维度解压。
同样,不幸的是, concatenation 的名称与名称相似的 NumPy 函数不同,但行为相同。请注意,不是让 torch.cat
通过提供 dim=-1
来计算维度,您还可以显式提供要连接的维度,在这种情况下,将其替换为 dim=2
.
记住
或者,您可以通过压缩较大的张量和堆叠来实现:
inps = torch.randn([64, 161, 1])
d = torch.randn([64, 161])
res = torch.stack((inps.squeeze(), d), dim=-1)
res.shape
>>> [64, 161, 2]