PyTorch中转置张量后拼接触发AssertionError,请求排查
问题排查与修正
各张量形状梳理
- 初始
tensor1形状:(4, 2),转置后tensor1_t的形状为(2, 4) - 初始
tensor2形状:(10, 4)
拼接操作与断言错误原因
用torch.cat在dim=0维度拼接时,要求除拼接维度外的所有维度必须一致。这里tensor1_t和tensor2的dim=1维度都是4,拼接合法,最终concat_tensor的形状是(2+10, 4) = (12, 4)。
你的两个断言都存在逻辑错误:
- 第一个断言中,你错误使用
tensor1_t.shape[1](值为4)计算拼接后的dim=0长度,实际应该用tensor1_t.shape[0](值为2),正确的等式是concat_tensor.shape[0] == tensor1_t.shape[0] + tensor2.shape[0] - 第二个断言中,你错误将
concat_tensor.shape[1]与tensor1_t.shape[0](值为2)做对比,实际拼接后dim=1维度保持不变,应该与tensor1_t.shape[1]或tensor2.shape[1](值均为4)对比
修正后的代码
import torch tensor1 = torch.rand(4, 2) tensor2 = torch.rand(10, 4) tensor1_t = torch.transpose(tensor1, 0, 1) concat_tensor = torch.cat((tensor1_t, tensor2), dim=0) # 修正后的断言 assert concat_tensor.shape[0] == tensor1_t.shape[0] + tensor2.shape[0] assert concat_tensor.shape[1] == tensor1_t.shape[1] print(concat_tensor.shape) # 输出 torch.Size([12, 4])
内容的提问来源于stack exchange,提问作者spoolito
相关产品推荐
相关产品推荐

