fig*_*uto 10 tensorflow tensorflow-estimator
我有一个保存的模型(一个目录 model.pd和 变量)并希望在 Pandas 数据框上运行预测。
我尝试了几种方法都没有成功:
尝试 1:从保存的模型中恢复估算器
estimator = tf.estimator.LinearClassifier(
feature_columns=create_feature_cols(),
model_dir=path,
warm_start_from=path)
Run Code Online (Sandbox Code Playgroud)
其中 path 是具有model.pd和 variables 文件夹的目录。我有一个错误
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]
}
Run Code Online (Sandbox Code Playgroud)
尝试 2:通过运行直接从保存的模型运行预测
imported = tf.saved_model.load(path) # path is the directory that has a `model.pd` and variables folder
imported.signatures["predict"](example)
Run Code Online (Sandbox Code Playgroud)
但尚未成功传递参数 - 看起来该函数正在寻找 atf.example并且我不确定如何将数据框转换为tf.example. 我的转换尝试如下,但出现 df[f] 不是张量的错误:
for f in features:
example.features.feature[f].float_list.value.extend(df[f])
Run Code Online (Sandbox Code Playgroud)
我在 StackOverflow 上看到过解决方案,但它们都是 tensorflow 1.14。如果有人可以帮助使用 tensorflow 2.0,将不胜感激。
考虑到您保存的模型如下所示:
my_model
assets saved_model.pb variables
Run Code Online (Sandbox Code Playgroud)
您可以使用以下方法加载保存的模型:
new_model = tf.keras.models.load_model('saved_model/my_model')
# Check its architecture
new_model.summary()
Run Code Online (Sandbox Code Playgroud)
要对 DataFrame 执行预测,您需要:
convert_to_tensor每个功能示例 1: 如果第一个测试行的值为
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)
)
Run Code Online (Sandbox Code Playgroud)
示例 2: 或者如果有多行与训练数据的顺序相同
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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
795 次 |
| 最近记录: |