我有一个保存的模型,我设法加载,运行并获得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
问题是-我需要像问题here一样对每行进行run()
答案 0 :(得分:2)
好的,所以我发现我无法为所有想要的行(预测)运行一次问题。可能是我混淆了输入和输出矩阵的tensorflow新手问题。 当报表工具(python)说您有输入Tensor时 形状(-1,9)映射到java long [] {1,9}并不意味着您不能传递与long [] {1000,9}一样的输入-这意味着可以进行1000行预测。 输入后,定义为[1,1]的输出张量可以为[1000,1]。
此代码实际上比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]);
}
}
}