PyTorch如何将一个tensor的数值插入到另一个tensor的指定维度中
报错原因
torch.cat要求所有待拼接的张量,除了拼接维度之外的其他维度形状完全一致。你代码中的y形状为(100,),和x的(100, 16, 16)/(100, 16, 16, 1)形状不匹配,因此无法直接拼接。
实现逻辑
要让y对应x第0维的100个元素,即同个第0维索引下的所有16×16位置共享同一个y值,你需要先对y做升维、广播操作,匹配x的维度后再拼接。
完整可运行代码
分两种场景对应你注释中的两种x定义:
场景1:x初始为3维 (100, 16, 16)
如果你的需求是最终输出(100, 16, 16, 1)且仅保留y值作为最后一维,直接取下方代码中的y_expanded即可;如果需要拼接x原有值和y值,最终输出维度为(100, 16, 16, 2)(x原有1个隐式通道+新增y通道)。
import torch x = torch.randn(100, 16, 16) y = torch.randn(100) # 步骤1:y升维到4维,形状变为(100, 1, 1, 1) y_reshaped = y.reshape(-1, 1, 1, 1) # 步骤2:广播扩展到和x的空间维度匹配,形状变为(100, 16, 16, 1) y_expanded = y_reshaped.expand(-1, x.shape[1], x.shape[2], -1) # 步骤3:x升维后和y拼接,dim=-1表示最后一维 Xy = torch.cat([x.unsqueeze(-1), y_expanded], dim=-1) print(Xy.shape) # 输出 torch.Size([100, 16, 16, 2])
场景2:x初始为4维 (100, 16, 16, 1),最终输出维度 (100, 16, 16, 2)
import torch y_dim = 1 x = torch.randn(100, 16, 16, y_dim) y = torch.randn(100) y_reshaped = y.reshape(-1, 1, 1, 1) y_expanded = y_reshaped.expand(-1, x.shape[1], x.shape[2], -1) Xy = torch.cat([x, y_expanded], dim=-1) print(Xy.shape) # 输出 torch.Size([100, 16, 16, 2])
内容的提问来源于stack exchange,提问作者MariusKuzmin
相关产品推荐
相关产品推荐

