TensorFlow 在 java 中提供服务 - 在一个会话中进行多个预测 运行

TensorFlow serving in java - multiple predictions in one session run

我有一个已保存的模型,我设法加载它,运行 并获得对 1 行 9 个特征的预测。 (输入) 现在我正试图预测 100 行, 但是当试图从 Tensor.copyTo() 读取结果到结果数组时,我得到了不兼容的形状

java.lang.IllegalArgumentException: cannot copy Tensor with shape [1, 1] into object with shape [100, 1]

显然我设法 运行 循环中的这一预测 - 但这比等效的 python 在一个 运行.

中执行 100 慢 20 倍

这是 /saved_model_cli.py

报告的已保存模型信息
MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:

signature_def['serving_default']:
  The given SavedModel SignatureDef contains the following input(s):
    inputs['input'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 9)
        name: dense_1_input:0
  The given SavedModel SignatureDef contains the following output(s):
    outputs['output'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 1)
        name: dense_4/BiasAdd:0
  Method name is: tensorflow/serving/predict

问题是 - 我是否需要像问题

一样对每一行进行 运行() 预测

好的,所以我发现了我无法 运行 一次我想要的所有行(预测)的问题。可能是一个 tensorflow 新手问题,我弄乱了输入和输出矩阵。 当报告工具 (python) 说你有一个输入张量 形状 (-1,9) 映射到 java long[]{1,9} 这并不意味着您不能将输入传递为 long[]{1000,9} - 这意味着 1000 行用于预测。 在此输入之后,定义为 [1,1] 的输出张量可以是 [1000,1].

这段代码实际上 运行s 比 python 快得多(1.2 秒对 7 秒) 这是代码(也许会更好地解释)

public Tensor prepareData(){
    Random r = new Random();
    float[]inputArr = new float[NUMBER_OF_KEWORDS*NUMBER_OF_FIELDS];
    for (int i=0;i<NUMBER_OF_KEWORDS * NUMBER_OF_FIELDS;i++){
        inputArr[i] = r.nextFloat();
    }

    FloatBuffer inputBuff = FloatBuffer.wrap(inputArr, 0, NUMBER_OF_KEWORDS*NUMBER_OF_FIELDS);
    return Tensor.create(new long[]{NUMBER_OF_KEWORDS,NUMBER_OF_FIELDS}, inputBuff);
}

public void predict (Tensor inputTensor){
    try ( Session s = savedModelBundle.session()) {
        Tensor result;
        long globalStart = System.nanoTime();
            result = s.runner().feed("dense_1_input", inputTensor).fetch("dense_4/BiasAdd").run().get(0);

            final long[] rshape = result.shape();
            if (result.numDimensions() != 2 || rshape[0] <= NUMBER_OF_KEWORDS) {
                throw new RuntimeException(
                        String.format(
                                "Expected model to produce a [N,1] shaped tensor where N is the number of labels, instead it produced one with shape %s",
                                Arrays.toString(rshape)));
            }


        float[][] resultArray = (float[][]) result.copyTo(new float[NUMBER_OF_KEWORDS][1]);
        System.out.println(String.format("Total of %d,  took : %.4f ms", NUMBER_OF_KEWORDS, ((double) System.nanoTime() - globalStart) / 1000000));
        for (int i=0;i<10;i++){
            System.out.println(resultArray[i][0]);
        }
    }
}