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

PyTorch测试脚本报‘IndexError: Dimension out of range’错误原因排查

问题原因&解决办法

为什么会报维度越界?

你用model.encode处理单句时,返回的是一维数组(比如形状是(768,)),转成PyTorch张量后还是一维的。一维张量的维度索引只有0(或者用-1指代最后一维),但torch.cosine_similarity默认用dim=1,这个维度在一维张量里根本不存在,自然就报错了。

两种修复方式

方式一:给张量加个维度

把一维张量转成二维(比如(1,768)),这样dim=1就合法了:

embeddings1 = torch.from_numpy(model.encode(sentence1)).unsqueeze(0)
embeddings2 = torch.from_numpy(model.encode(sentence2)).unsqueeze(0)
similarity = torch.cosine_similarity(embeddings1, embeddings2)

方式二:直接指定正确的维度

既然张量只有一维,直接把dim设为0就行:

similarity = torch.cosine_similarity(embeddings1, embeddings2, dim=0)

两种方法得到的结果完全一致,选哪种都可以。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:32:02