使用Java API将维度0的索引0切片到超出范围

使用Java API将维度0的索引0切片到超出范围,java,tensorflow,Java,Tensorflow,我已经生成了一个SavedModel,可以与下面的Python代码一起使用 import base64 import numpy as np import tensorflow as tf ​ ​ fn_load_image = lambda filename: np.array([base64.urlsafe_b64encode(open(filename, "rb").read())]) filename='test.jpg' with tf.Session() as sess: l

我已经生成了一个SavedModel,可以与下面的Python代码一起使用

import base64
import numpy as np
import tensorflow as tf
​
​
fn_load_image = lambda filename: np.array([base64.urlsafe_b64encode(open(filename, "rb").read())])
filename='test.jpg'
with tf.Session() as sess:
    loaded = tf.saved_model.loader.load(sess, ['serve'], 'tools/base64_model/1')
    image = fn_load_image(filename)
    p = sess.run('predictions:0', feed_dict={"input:0": image})
    print(p)
这给了我期望的价值

在同一模型上使用下面的Java代码时

    // load the model Bundle
    try (SavedModelBundle b = SavedModelBundle.load("tools/base64_model/1",
            "serve")) {

        // create the session from the Bundle
        Session sess = b.session();

        // base64 representation of JPG
        byte[] content = IOUtils.toByteArray(new FileInputStream(new File((args[0]))));

        String encodedString = Base64.getUrlEncoder().encodeToString(content);

        Tensor t = Tensors.create(encodedString);

        // run the model and get the classification
        final List<Tensor<?>> result = sess.runner().feed("input", 0, t).fetch("predictions", 0).run();

        // print out the result.
        System.out.println(result);
    }

您的模型期望输入张量为秩-1,而您提供的张量为秩-0

这一行产生一个可变长度的标量张量(即
dtu字符串

tensort=Tensors.create(encodedString);
然而,预期的张量是秩-1,正如您可以从这里的形状
(-1)
中看到的,这意味着它预期的是一个包含不同数量元素的向量

The given SavedModel SignatureDef contains the following input(s):
    inputs['inputs'] tensor_info:
        dtype: DT_STRING
        shape: (-1)
        name: input:0
因此,通过传递字符串数组,您的问题可能会得到解决。只有将字符串作为字节数组传递时,才可以使用
张量
工厂,如下所示:

//JPG的base64表示
byte[]content=IOUtils.toByteArray(新文件inputstream(新文件((args[0])));
字节[]encodedBytes=Base64.getUrlEncoder().encode(内容);
张量t=Tensors.create(新字节[][{encodedBytes});
...
The given SavedModel SignatureDef contains the following input(s):
    inputs['inputs'] tensor_info:
        dtype: DT_STRING
        shape: (-1)
        name: input:0