You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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)。

你的两个断言都存在逻辑错误:

  1. 第一个断言中,你错误使用tensor1_t.shape[1](值为4)计算拼接后的dim=0长度,实际应该用tensor1_t.shape[0](值为2),正确的等式是concat_tensor.shape[0] == tensor1_t.shape[0] + tensor2.shape[0]
  2. 第二个断言中,你错误将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 11:14:53