如何连接 axis=1 内的张量?
How to concatenate a tensor WITHIN axis=1?
我有一个形状的张量(2,2,2,2)
:
tensor([[[[ 5., 5.],
[ 5., 5.]],
[[ 10., 10.],
[ 10., 10.]]],
[[[ 100., 100.],
[ 100., 100.]],
[[1000., 1000.],
[1000., 1000.]]]], device='cuda:0')
我想对其进行变换,使沿 axis=1 的张量重复 3 次。在应用 .view(-1)
之后,我得到一个一维结果张量:
tensor([ 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 10., 10., 10., 10., 10., 10., 10., 10., 10., 10., 10., 10., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 1000., 1000., 1000., 1000. 1000., 1000., 1000., 1000. 1000., 1000., 1000., 1000. 1000., 1000., 1000., 1000.], device='cuda:0')
如何操作?
试试这个:
final_features = feature_combined.view(1, -1, feature_combined.size(-1))
.repeat(1, 1, 3).view(1, -1).squeeze(0)
我假设你的 (2, 2, 2, 2)
形状的输入张量在 feature_combined
中。生成的 final_features
的形状是 ([48])
,如您所愿。
print(feature_combined)
>>tensor([ 5., 5., 5., 5., 5., 5., 5., 5., 5., 5.,
5., 5., 10., 10., 10., 10., 10., 10., 10., 10.,
10., 10., 10., 10., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 1000., 1000., 1000., 1000.,
1000., 1000., 1000., 1000., 1000., 1000., 1000., 1000.])
使用torch.repeat_interleave
重复张量的元素。
t.repeat_interleave(repeats=3, dim=1).view(-1)
tensor([ 5., 5., 5., 5., 5., 5., 5., 5., 5., 5.,
5., 5., 10., 10., 10., 10., 10., 10., 10., 10.,
10., 10., 10., 10., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 1000., 1000., 1000., 1000.,
1000., 1000., 1000., 1000., 1000., 1000., 1000., 1000.])
我有一个形状的张量(2,2,2,2)
:
tensor([[[[ 5., 5.],
[ 5., 5.]],
[[ 10., 10.],
[ 10., 10.]]],
[[[ 100., 100.],
[ 100., 100.]],
[[1000., 1000.],
[1000., 1000.]]]], device='cuda:0')
我想对其进行变换,使沿 axis=1 的张量重复 3 次。在应用 .view(-1)
之后,我得到一个一维结果张量:
tensor([ 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 10., 10., 10., 10., 10., 10., 10., 10., 10., 10., 10., 10., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 1000., 1000., 1000., 1000. 1000., 1000., 1000., 1000. 1000., 1000., 1000., 1000. 1000., 1000., 1000., 1000.], device='cuda:0')
如何操作?
试试这个:
final_features = feature_combined.view(1, -1, feature_combined.size(-1))
.repeat(1, 1, 3).view(1, -1).squeeze(0)
我假设你的 (2, 2, 2, 2)
形状的输入张量在 feature_combined
中。生成的 final_features
的形状是 ([48])
,如您所愿。
print(feature_combined)
>>tensor([ 5., 5., 5., 5., 5., 5., 5., 5., 5., 5.,
5., 5., 10., 10., 10., 10., 10., 10., 10., 10.,
10., 10., 10., 10., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 1000., 1000., 1000., 1000.,
1000., 1000., 1000., 1000., 1000., 1000., 1000., 1000.])
使用torch.repeat_interleave
重复张量的元素。
t.repeat_interleave(repeats=3, dim=1).view(-1)
tensor([ 5., 5., 5., 5., 5., 5., 5., 5., 5., 5.,
5., 5., 10., 10., 10., 10., 10., 10., 10., 10.,
10., 10., 10., 10., 100., 100., 100., 100., 100., 100.,
100., 100., 100., 100., 100., 100., 1000., 1000., 1000., 1000.,
1000., 1000., 1000., 1000., 1000., 1000., 1000., 1000.])