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

TFDistilBERT多输入模型predict时NumPy转Tensor报错如何解决

问题排查与解决方案

报错根因

该报错由两方面的输入不匹配导致:

  • 所有模型输入都缺少batch维度:Keras要求所有输入的第一维为样本批量维度,单样本预测时也需要显式补充该维度
  • 词频特征数组可能存在类型异常:如果构造freq_representation时传入的列表嵌套或数值不一致,numpy会生成object类型数组,无法转换为Tensor

修复步骤

1. 修正Tokenizer新增词汇的写法(规避后续隐式错误)

直接修改vocab属性不会更新Tokenizer的编解码映射关系,需改用官方add_tokens方法,且该操作要放在模型创建之前,保证模型输入维度和实际词表长度匹配:

# 新增特殊词正确写法
new_tokens = ["htg", "mtn", "url", "rtw"]
dbert_tokenizer.add_tokens(new_tokens)
dbert_model.resize_token_embeddings(len(dbert_tokenizer))

# 再创建模型
model = create_model()

2. 修正预测阶段的输入维度与类型

给三个输入都补充batch维度,同时显式指定词频特征的数据类型:

# 处理BERT输入,补充batch维度并对齐类型
input_ids = np.expand_dims(bert_inps["input_ids"], axis=0).astype("int64")
attention_mask = np.expand_dims(bert_inps["attention_mask"], axis=0).astype("int64")

# 处理词频特征:指定类型+补充batch维度
freq_representation = np.array(..., dtype="float64") # 构造数组时显式指定float64类型
freq_representation = np.expand_dims(freq_representation, axis=0)

# 执行预测
preds = model.predict([input_ids, attention_mask, freq_representation], batch_size=1)

验证方法

如果仍报错,可先打印三个输入的属性确认匹配:

  • input_ids.shape 应为 (1, 50),dtype 为 int64
  • attention_mask.shape 应为 (1, 50),dtype 为 int64
  • freq_representation.shape 应为 (1, 30525),dtype 为 float64

内容的提问来源于stack exchange,提问作者S. D. chowdhury

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:06:04