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

语言识别模型测试报错:矩阵形状不匹配问题求助

语言分类模型测试时维度不匹配错误

我用PyTorch构建了一个识别4种语言的分类模型,训练过程正常,但测试时触发以下错误:

RuntimeError: mat1 and mat2 shapes cannot be multiplied (1x250 and 10000x128)

错误原因

训练阶段所有句子都通过sentence_to_indices函数被统一处理为固定长度MAX_SEQ_LENGTH=200(过长截断、过短补UNK_IDX),因此模型的全连接层fc1输入维度被设置为embedding_dim * MAX_SEQ_LENGTH = 50*200=10000。但预测阶段的predict_language函数直接拆分句子生成索引,没有做同样的长度统一处理,导致测试输入的序列长度仅为5(对应测试句子的词数),嵌入后flatten的维度为1*5*50=250,和fc1的输入维度10000不匹配,触发矩阵相乘错误。

解决方案

修改predict_language函数,复用训练阶段的sentence_to_indices函数处理输入句子,确保输入序列长度和训练时一致:

def predict_language(model, sentence):
    model.eval()
    # 复用训练时的长度统一处理逻辑
    indexed_sentence = sentence_to_indices(sentence)
    tensor_sentence = torch.tensor(indexed_sentence).unsqueeze(0)
    output = model(tensor_sentence)
    _, predicted_idx = torch.max(output, 1)
    return predicted_idx.item()

额外建议

  • 将sentence_to_indices这类数据处理逻辑封装成工具函数,避免训练和预测阶段代码不一致。
  • 若后续需要支持GPU训练,可在预测时添加设备匹配代码,将模型和输入张量移至同一设备:
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model.to(device)
    tensor_sentence = torch.tensor(indexed_sentence).unsqueeze(0).to(device)
    

内容的提问来源于stack exchange,提问作者Drake0909

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:33:13