torch.cat()使用详解

官方文档

这里看
torch.cat

torch.cat(inputs, dimension=0) → Tensor

在给定维度上对输入的张量序列seq 进行连接操作。

torch.cat()可以看做 torch.split() 和 torch.chunk()的反操作。 cat() 函数可以通过下面例子更好的理解。

参数:

inputs (sequence of Tensors) – 可以是任意相同Tensor 类型的python 序列
dimension (int, optional) – 沿着此维连接张量序列。

官方例子

>>> x = torch.randn(2, 3)
>>> x

 0.5983 -0.0341  2.4918
 1.5981 -0.5265 -0.8735
[torch.FloatTensor of size 2x3]

>>> torch.cat((x, x, x), 0)

 0.5983 -0.0341  2.4918
 1.5981 -0.5265 -0.8735
 0.5983 -0.0341  2.4918
 1.5981 -0.5265 -0.8735
 0.5983 -0.0341  2.4918
 1.5981 -0.5265 -0.8735
[torch.FloatTensor of size 6x3]

>>> torch.cat((x, x, x), 1)

 0.5983 -0.0341  2.4918  0.5983 -0.0341  2.4918  0.5983 -0.0341  2.4918
 1.5981 -0.5265 -0.8735  1.5981 -0.5265 -0.8735  1.5981 -0.5265 -0.8735
[torch.FloatTensor of size 2x9]

补充例子之高维

import torch
a = torch.randn(2,3,4)
a
Out[4]: 
tensor([[[ 0.1728,  1.2299,  1.1025,  1.2469],
         [-1.7841, -0.0682, -1.3842,  0.1034],
         [-0.2922,  0.5537,  1.8052,  1.6766]],
        [[ 0.6606, -0.1216,  0.6336, -0.9340],
         [-0.3626, -1.1162,  0.8975, -0.1320],
         [-0.2133,  0.3769,  0.5940, -1.3333]]])
b = torch.cat((a,a),dim=0)
b
Out[6]: 
tensor([[[ 0.1728,  1.2299,  1.1025,  1.2469],
         [-1.7841, -0.0682, -1.3842,  0.1034],
         [-0.2922,  0.5537,  1.8052,  1.6766]],
        [[ 0.6606, -0.1216,  0.6336, -0.9340],
         [-0.3626, -1.1162,  0.8975, -0.1320],
         [-0.2133,  0.3769,  0.5940, -1.3333]],
        [[ 0.1728,  1.2299,  1.1025,  1.2469],
         [-1.7841, -0.0682, -1.3842,  0.1034],
         [-0.2922,  0.5537,  1.8052,  1.6766]],
        [[ 0.6606, -0.1216,  0.6336, -0.9340],
         [-0.3626, -1.1162,  0.8975, -0.1320],
         [-0.2133,  0.3769,  0.5940, -1.3333]]])
b.size()
Out[7]: torch.Size([4, 3, 4])


补充例子之数据输入形式变化

b = torch.cat((a,2*a),dim=0)
b.size()
Out[9]: torch.Size([4, 3, 4])
b
Out[10]: 
tensor([[[ 0.1728,  1.2299,  1.1025,  1.2469],
         [-1.7841, -0.0682, -1.3842,  0.1034],
         [-0.2922,  0.5537,  1.8052,  1.6766]],
        [[ 0.6606, -0.1216,  0.6336, -0.9340],
         [-0.3626, -1.1162,  0.8975, -0.1320],
         [-0.2133,  0.3769,  0.5940, -1.3333]],
        [[ 0.3455,  2.4599,  2.2050,  2.4939],
         [-3.5681, -0.1363, -2.7684,  0.2069],
         [-0.5845,  1.1074,  3.6105,  3.3531]],
        [[ 1.3212, -0.2432,  1.2671, -1.8680],
         [-0.7252, -2.2325,  1.7951, -0.2641],
         [-0.4266,  0.7537,  1.1880, -2.6667]]])
发布了61 篇原创文章 · 获赞 20 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43914889/article/details/104616034