从 tensorflow 2.0 中保存的模型运行预测 [英] Run prediction from saved model in tensorflow 2.0

查看:87
本文介绍了从 tensorflow 2.0 中保存的模型运行预测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个已保存的模型(一个包含 model.pd 和变量的目录),并且想对 Pandas 数据框进行预测.

I have a saved model (a directory with model.pd and variables) and wanted to run predictions on a pandas data frame.

我尝试了几种方法都没有成功:

I've unsuccessfully tried a few ways to do this:

尝试 1:从保存的模型中恢复估算器

estimator = tf.estimator.LinearClassifier(
    feature_columns=create_feature_cols(),
    model_dir=path,
    warm_start_from=path)

其中 path 是具有 model.pd 和 variables 文件夹的目录.我有一个错误

Where path is the directory that has a model.pd and variables folder. I got an error

ValueError: Tensor linear/linear_model/dummy_feature1/weights is not found in 
gs://bucket/Trainer/output/2013/20191008T170504.583379-63adee0eaee0/serving_model_dir/export/1570554483/variables/variables 
checkpoint {'linear/linear_model/dummy_feature1/weights': [1, 1], 'linear/linear_model/dummy_feature2/weights': [1, 1]
}

尝试 2:通过运行直接从保存的模型运行预测

imported = tf.saved_model.load(path)  # path is the directory that has a `model.pd` and variables folder
imported.signatures["predict"](example)

但尚未成功传递参数 - 看起来该函数正在寻找 tf.example 并且我不确定如何将数据框转换为 tf.example>.我的转换尝试如下,但出现 df[f] 不是张量的错误:

But has not successfully passed the argument - looks like the function is looking for a tf.example and I am not sure how to convert a data frame to tf.example. My attempt to convert is below but got an error that df[f] is not a tensor:

for f in features:
    example.features.feature[f].float_list.value.extend(df[f])

我在 StackOverflow 上看到过解决方案,但它们都是 tensorflow 1.14.如果有人可以帮助使用 tensorflow 2.0,将不胜感激.

I've seen solutions on StackOverflow but they are all tensorflow 1.14. Greatly appreciate it if someone can help with tensorflow 2.0.

推荐答案

考虑到您保存的模型如下所示:

Considering you have your saved model present like this:

my_model
assets  saved_model.pb  variables

您可以使用以下方法加载保存的模型:

You can load your saved model using:

new_model = tf.keras.models.load_model('saved_model/my_model')

# Check its architecture
new_model.summary()

要对 DataFrame 执行预测,您需要:

To perform prediction on a DataFrame you need to:

  1. 将标量包装成一个列表,以便有一个批量维度(模型只处理批量数据,而不是单个样本)
  2. 对每个特征调用convert_to_tensor

示例 1:如果您将第一个测试行的值设为

Example 1: If you have values for the first test row as

sample = {
    'Type': 'Cat',
    'Age': 3,
    'Breed1': 'Tabby',
    'Gender': 'Male',
    'Color1': 'Black',
    'Color2': 'White',
    'MaturitySize': 'Small',
    'FurLength': 'Short',
    'Vaccinated': 'No',
    'Sterilized': 'No',
    'Health': 'Healthy',
    'Fee': 100,
    'PhotoAmt': 2,
}

input_dict = {name: tf.convert_to_tensor([value]) for name, value in sample.items()}
predictions = new_model.predict(input_dict)
prob = tf.nn.sigmoid(predictions[0])

print(
    "This particular pet had a %.1f percent probability "
    "of getting adopted." % (100 * prob)
)

示例 2:或者,如果您有多行与火车数据的顺序相同

Example 2: Or if you have multiple rows present in the same order as the train data

predict_dataset = tf.convert_to_tensor([
    [5.1, 3.3, 1.7, 0.5,],
    [5.9, 3.0, 4.2, 1.5,],
    [6.9, 3.1, 5.4, 2.1]
])

# training=False is needed only if there are layers with different
# behavior during training versus inference (e.g. Dropout).
predictions = new_model(predict_dataset, training=False)

for i, logits in enumerate(predictions):
  class_idx = tf.argmax(logits).numpy()
  p = tf.nn.softmax(logits)[class_idx]
  name = class_names[class_idx]
  print("Example {} prediction: {} ({:4.1f}%)".format(i, name, 100*p))

这篇关于从 tensorflow 2.0 中保存的模型运行预测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆