数值错误: 无法为形状为“(?)”的张量“input_example_tensor:0”提供形状为“()”的值。

3

为什么会出现这个错误?

我找不到类似于我的情况并且有解释原因的答案。对于这种错误,有很多相关信息,但似乎它取决于很多原因,并且对于不同的情况,可能会有不同的解决方案。

所以我正在尝试加载 TensorFlow 训练模型,然后将其转换为 TensorFlow Serving 模型格式并进行预测。

从下面的导入中导入 iris_data.py 文件。

这是我如何导出我的模型(已经完成训练,我只需从磁盘加载):

import tensorflow as tf
import iris_data
from tensorflow.contrib import predictor

# Fetch the data
    (train_x, train_y), (test_x, test_y) = iris_data.load_data()

    # Feature columns describe how to use the input.
    my_feature_columns = []
    for key in train_x.keys():
        my_feature_columns.append(tf.feature_column.numeric_column(key=key))

    # Build 2 hidden layer DNN with 10, 10 units respectively.
    classifier = tf.estimator.DNNClassifier(
        feature_columns=my_feature_columns,
        # Two hidden layers of 10 nodes each.
        hidden_units=[10, 10],
        # The model must choose between 3 classes.
        n_classes=3,
        model_dir='G:\AI models')

    #converting into TensorFlow Serving model format 
    path = 'G:\AI models\serve'
    feature_spec = tf.feature_column.make_parse_example_spec(my_feature_columns)
    export_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec)
    servable_model_path = classifier.export_savedmodel(path, export_input_fn, as_text=True)

这是我使用 TensorFlow Serving 模型进行预测的方法:

 expected = ['Setosa', 'Versicolor', 'Virginica']
    predict_x = {
        'SepalLength': [5.1, 5.9, 6.9],
        'SepalWidth': [3.3, 3.0, 3.1],
        'PetalLength': [1.7, 4.2, 5.4],
        'PetalWidth': [0.5, 1.5, 2.1],
    }
path = 'G:\AI models\serve\\1519413839'
    predict_fn = predictor.from_saved_model(path)
    predictions = predict_fn(
        {"inputs": predict_x})

最后出现错误:

ValueError: Cannot feed value of shape () for Tensor 'input_example_tensor:0', which has shape '(?,)'

它在哪一行失败了? - Yserbius
@Yserbius 预测结果 = predict_fn( {"inputs": predict_x}) - kkost
3个回答

1

你必须使用示例API通过你的样本:

feature = {
    'SepalLength': tf.train.Feature(float_list=tf.train.FloatList(value=[5.1])),
    'SepalWidth': tf.train.Feature(float_list=tf.train.FloatList(value=[3.3])),
    'PetalLength': tf.train.Feature(float_list=tf.train.FloatList(value=[1.7])),
    'PetalWidth': tf.train.Feature(float_list=tf.train.FloatList(value=[0.5]))
}
example = tf.train.Example(
    features=tf.train.Features(
        feature=feature
    )
)
serialized_example = example.SerializeToString()

predictions = predict_fn({"inputs": [serialized_example]})


你可以自己选择很多示例。
有用的链接: http://shzhangji.com/blog/2018/05/14/serve-tensorflow-estimator-with-savedmodel/

0

()代表零阶张量(即标量)的维度,(?,)则是未知维度的一阶张量(向量)。

没有完整的堆栈跟踪信息,这就是我能告诉你的全部内容。


我能为您分享些什么来帮助您?也许我没有以正确的方式转换模型... - kkost
堆栈跟踪是打印在错误上方的行,它应该从您的代码开始,并在tensorflow的某个地方结束。 - G_glop

-1
'G:\AI models\serve\\1519413839' 

应该是

'G:\\AI models\\serve\\1519413839'

反斜杠需要转义。可能是文件没有被读取,导致预测函数的数据形状为零维张量。


不幸的是,它对我没有帮助 :( - kkost

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接