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.
相关产品推荐
相关产品推荐

