我必须将 30*126 的二维数组放入 tflite 模型。如何在 java 中将二维浮点数组转换为 ByteBuffer

I have to put a 2D array of 30*126 to tflite model. How to convert a 2D array of float to ByteBuffer in java

我是 Nguyen,一名越南高中生,正在使用计算机视觉和 AI 开发手语翻译应用程序项目。 在我的应用程序中,我使用了 LSTM 模型,当转换为 tflite 模型时,我看到了这个示例代码:

try {
    SignLangModel model = SignLangModel.newInstance(context);

    // Creates inputs for reference.
    TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 30, 126}, DataType.FLOAT32);
    inputFeature0.loadBuffer(byteBuffer);

    // Runs model inference and gets result.
    SignLangModel.Outputs outputs = model.process(inputFeature0);
    TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();

    // Releases model resources if no longer used.
    model.close();
} catch (IOException e) {
    // TODO Handle the exception
}

这是我的二维数组的样子

[[ 0.62733257,  0.44471735, -0.69024068, ...,  0.40363967, 0.28696212, -0.06274992],
 [ 0.62688404,  0.4438577 , -0.73676074, ...,  0.40629318, 0.28771287, -0.05781016],
 [ 0.62661999,  0.44294813, -0.7216031 , ...,  0.40591961, 0.28609812, -0.06014785],
...
 [ 0.62216419,  0.43501934, -0.69985718, ...,  0.38580206, 0.29433241, -0.05569796]]

我想知道如何将 2D 浮点数组转换为 ByteBuffer。

您可以尝试转换,如下所示:

public byte[] ToByteArray(float[,] nmbs)
    {
        byte[] nmbsBytes = new byte[nmbs.GetLength(0) * nmbs.GetLength(1)*4];
        int k = 0;
        for (int i = 0; i < nmbs.GetLength(0); i++)
        {
            for (int j = 0; j < nmbs.GetLength(1); j++)
            {
                byte[] array = BitConverter.GetBytes(nmbs[i, j]);
                for (int m = 0; m < array.Length; m++)
                {
                    nmbsBytes[k++] = array[m];
                }
            }
        }
        return nmbsBytes;
    }

在代码有字节的地方使用当然浮动...然后

floar[] array = returnedArrayfromAbove;
ByteBuffer buffer = ByteBuffer.wrap(array);

但我认为您可以按照 TensorFlow Lite 指南 here 在 build.gradle 文件中使用适当的依赖项,然后:

try (Interpreter interpreter = new Interpreter(file_of_a_tensorflowlite_model)) {
  interpreter.run(input, output);
}

使用 Interpreter.run(),您可以在其中直接输入二维数组。 通常 Interpreter.run() 方法比 AS 生成的代码更灵活。你可以找到很多直接使用 Interpreter 的例子 there

如果您需要更多帮助,请标记我。