首页 > 解决方案 > ValueError:不能将 XXX 类型的 numpy 数组用于字符串张量

问题描述

我使用 Tensorflow Hub 的预训练模型创建了一个文本分类模型,模型的摘要是这样的

Model: "sequential_4"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer_5 (KerasLayer)   (None, 128)               112461824 
_________________________________________________________________
flatten_2 (Flatten)          (None, 128)               0         
_________________________________________________________________
dense_6 (Dense)              (None, 16)                2064      
_________________________________________________________________
dense_7 (Dense)              (None, 1)                 17        
=================================================================
Total params: 112,463,905
Trainable params: 2,081
Non-trainable params: 112,461,824
_________________________________________________________________

然后我将此模型转换为tflite格式,tf-nightly并且成功了。之后,我想在 python 中用我自己的文本测试 tflite 模型。这是我的代码:

# Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(r'./model_tf_filterComments.tflite')
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

input_index = interpreter.get_input_details()[0]["index"]
output_index = interpreter.get_output_details()[0]["index"]

input_data = ["You are extremely strong man, please don't give up!"]
interpreter.set_tensor(input_details[0]['index'], input_data) ## This line causes the error

但是,我不能使用我的文本来使用 tflite 模型进行预测,因为当我为 input_details 设置张量时它总是错误的。错误详情如下所示:

ValueError                                Traceback (most recent call last)
<ipython-input-30-b32325c64589> in <module>()
      1 input_data = ["You are extremely strong man, please don't give up!"]
----> 2 interpreter.set_tensor(input_details[0]['index'], input_data)

/usr/local/lib/python3.7/dist-packages/tensorflow/lite/python/interpreter.py in set_tensor(self, tensor_index, value)
    585       ValueError: If the interpreter could not set the tensor.
    586     """
--> 587     self._interpreter.SetTensor(tensor_index, value)
    588 
    589   def resize_tensor_input(self, input_index, tensor_size, strict=False):

ValueError: Cannot use numpy array of type 32663 for string tensor.

当我尝试int在数组内部使用输入时,会弹出另一个错误,因为它需要 type STRING,而且当我尝试只输入字符串(没有数组括号)时,它需要一个一维数组。

那么如何将文本输入到我的模型中进行预测?

标签: pythonnumpytensorflowtensortensorflow-lite

解决方案


推荐阅读