为什么在 运行 TensorFlowLite 模型时出现 BufferOverflowException?

Why do I get a BufferOverflowException when running a TensorFlowLite Model?

我想在 Android 上使用 TensorFlowLite(并使用 Kotlin)运行 自定义 tflite 模型。 尽管使用 TFLite 支持库创建了一个假定形状正确的输入和输出缓冲区,但每次调用我的 run() 方法时,我都会收到以下错误消息。

这是我的 class:

class Inference(context: Context) {
    private val tag = "Inference"
    private var interpreter: Interpreter
    private var inputBuffer: TensorBuffer
    private var outputBuffer: TensorBuffer

    init {
        val mappedByteBuffer= FileUtil.loadMappedFile(context, "CNN_ReLU.tflite")
        interpreter = Interpreter(mappedByteBuffer as ByteBuffer)
        interpreter.allocateTensors()

        val inputShape = interpreter.getInputTensor(0).shape()
        val outputShape = interpreter.getOutputTensor(0).shape()

        inputBuffer = TensorBuffer.createFixedSize(inputShape, DataType.FLOAT32)
        outputBuffer = TensorBuffer.createFixedSize(outputShape, DataType.FLOAT32)
    }

    fun run() {
        interpreter.run(inputBuffer.buffer, outputBuffer.buffer) // XXX: generates error message
    }
}

这是错误消息:

W/System.err: java.nio.BufferOverflowException
W/System.err:     at java.nio.ByteBuffer.put(ByteBuffer.java:615)
W/System.err:     at org.tensorflow.lite.Tensor.copyTo(Tensor.java:264)
W/System.err:     at org.tensorflow.lite.Tensor.copyTo(Tensor.java:254)
W/System.err:     at org.tensorflow.lite.NativeInterpreterWrapper.run(NativeInterpreterWrapper.java:170)
W/System.err:     at org.tensorflow.lite.Interpreter.runForMultipleInputsOutputs(Interpreter.java:347)
W/System.err:     at org.tensorflow.lite.Interpreter.run(Interpreter.java:306)

我只初始化了输入和输出缓冲区,还没有写入任何数据。

我正在使用这些 gradle 依赖项:

implementation 'org.tensorflow:tensorflow-lite:0.0.0-nightly'
implementation 'org.tensorflow:tensorflow-lite-gpu:0.0.0-nightly'
implementation 'org.tensorflow:tensorflow-lite-support:0.0.0-nightly'

.tflite 模型是使用这些 TensorFlow 版本构建的:

tensorflow                        2.3.0
tensorflow-cpu                    2.2.0
tensorflow-datasets               3.1.0
tensorflow-estimator              2.3.0
tensorflow-gan                    2.0.0
tensorflow-hub                    0.7.0
tensorflow-metadata               0.22.0
tensorflow-probability            0.7.0
tensorflowjs                      1.7.4.post1

非常感谢任何想法或提示,谢谢。

将 .rewind() 添加到您的输入和输出缓冲区是否可以正常工作? 如果不是,不知你的输入或输出张量是不是动态张量?在这种情况下 return 形状无法以这种方式使用。