【用图说话】PyTorch中Tensor的拼接
PyTorch中Tensor的拼接PyTorch中Tensor的拼接方法:torch.cat() 、torch.stack()【小提示:代码得到下面的图】torch.cat()我们用图+代码来举例import torchx1 = torch.randn(1, 3)x2 = torch.randn(1, 3)# 在 0 维(纵向)进行拼接torch.cat((x1, x2), 0)# size[2,
·
PyTorch中Tensor的拼接
PyTorch中Tensor的拼接方法:torch.cat() 、torch.stack()
【小提示:代码得到下面的图】
- torch.cat()
我们用图+代码来举例
import torch
x1 = torch.randn(1, 3)
x2 = torch.randn(1, 3)
# 在 0 维(纵向)进行拼接
torch.cat((x1, x2), 0)
# size
[2, 3]
# 在 1 维(横向)进行拼接
torch.cat((x1, x2), 1)
# size
[1, 6]
注意:对于需要拼接的张量,维度数量必须相同,进行拼接的维度的尺寸可以不同,但是其它维度的尺寸必须相同。【简而言之,堆积木,对上了就可以拼】
- torch.stack()
我们继续用图+代码来举例
import torch
x1 = torch.randn(3, 4)
x2 = torch.randn(3, 4)
# 在 0 维插入一个维度,进行前后组合
torch.stack((x1, x2), 0)
# size
[2, 3,4]
# 在 1 维插入一个维度
torch.stack((x1, x2), 1)
# size
[3, 2,4]
# 在 2 维插入一个维度
torch.stack((x1, x2), 2)
# size
[3, 4,2]
补充:
拼接多个向量,例如:torch.stack((x1, x2, x3, x4), 2),再上述的方法中接入需要拼接的向量就可以了
点击阅读全文
更多推荐
活动日历
查看更多
直播时间 2025-02-26 16:00:00


直播时间 2025-01-08 16:30:00


直播时间 2024-12-11 16:30:00


直播时间 2024-11-27 16:30:00


直播时间 2024-11-21 16:30:00


目录
所有评论(0)