You need to enable JavaScript to run this app. TensorFlow Lite文本分类模型输入文本触发ValueError如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow Lite文本分类模型输入文本触发ValueError如何解决?

解决方案

这个报错的核心原因是 tf.lite.Interpreter 的 set_tensor 方法接收字符串输入时,要求输入为 NumPy字符串类型的数组,直接传入Python原生字符串列表无法被识别匹配类型。

修正后的测试代码

import numpy as np
import tensorflow as tf

# 加载TFLite模型并分配张量
interpreter = tf.lite.Interpreter(r'./model_tf_filterComments.tflite')
interpreter.allocate_tensors()

# 获取输入输出张量信息
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

input_index = input_details[0]["index"]
output_index = output_details[0]["index"]

# 核心修改:将原生字符串列表转换为NumPy字符串数组
input_data = np.array(["You are extremely strong man, please don't give up!"], dtype=np.str_)
interpreter.set_tensor(input_index, input_data)

# 执行推理
interpreter.invoke()

# 获取预测结果
output = interpreter.get_tensor(output_index)
print(output)

补充说明

  • 若转换后仍存在类型匹配问题,可先打印print(input_details[0]['dtype'])确认模型要求的输入类型,保证传入数组的dtype和要求一致即可。
  • 批量测试时只需对应调整NumPy数组内的文本数量即可,例如np.array(["文本1", "文本2"], dtype=np.str_)即可实现批量推理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 05:54:05