1 回答
TA贡献1111条经验 获得超0个赞
好吧,所以我发现了一个问题,我无法为我想要的所有行(预测)运行一次。可能是一个张量流新手问题,我搞砸了输入和输出矩阵。当报告工具(python)说你有一个形状(-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]);
}
}
}
添加回答
举报