当前位置: 代码迷 >> python >> 从TFSaved_Model预测时发生ValueError
  详细解决方案

从TFSaved_Model预测时发生ValueError

热度:28   发布时间:2023-07-14 08:46:24.0

我已经保存了DNNestimator,现在我正在尝试使用该模型来预测某些数据。

模型训练:

feature_columns = [tf.contrib.layers.real_valued_column("x", dimension=500)]

classifier = tf.estimator.DNNClassifier(
feature_columns=feature_columns,
hidden_units=[500],
optimizer=tf.train.AdamOptimizer(1e-4),
n_classes=18,
dropout=0,
model_dir=None)

train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={'x': train_vec.values},
y=train.code.astype(np.int32),
num_epochs=None,
batch_size=50,
shuffle=True)

classifier.train(input_fn=train_input_fn, steps=1000)

feature_spec = {'x':tf.FixedLenFeature(shape= [500],dtype=np.float32)}
serving_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn( feature_spec)
export_path = "path/to/export"
classifier.export_savedmodel(export_path,serving_fn)

我想在这里预测:

a=np.expand_dims(test_vec.iloc[0].values,axis=0)
predict_fn = tf.contrib.predictor.from_saved_model(export_path_folder)
predictions = predict_fn({"inputs":a})

Train_vec和test_vec是具有500列(功能)的数据帧。 预测时出现以下错误:

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

以下是我的saved_model_cli:

The given SavedModel SignatureDef contains the following input(s):
inputs['inputs'] tensor_info:
  dtype: DT_STRING
  shape: (-1)
  name: input_example_tensor:0
The given SavedModel SignatureDef contains the following output(s):
outputs['classes'] tensor_info:
  dtype: DT_STRING
  shape: (-1, 18)
  name: dnn/head/Tile:0
 outputs['scores'] tensor_info:
  dtype: DT_FLOAT
  shape: (-1, 18)
  name: dnn/head/predictions/probabilities:0
Method name is: tensorflow/serving/classify

对于tensorflow来说还很新,任何帮助或指导都是有价值的。 谢谢!

解决:

无法解决以上错误,但是DNNClassifier“热启动”起作用了。

classifier = tf.estimator.DNNClassifier(
feature_columns=feature_columns,
hidden_units=[500],
optimizer=tf.train.AdamOptimizer(1e-4),
n_classes=18,
dropout=0,
warm_start_from=export_path_folder)

然后使用classifier.predict

  相关解决方案