【问题标题】:AttributeError: 'Functional' object has no attribute 'predict_segmentation' When importing TensorFlow model KerasAttributeError: 'Functional' object has no attribute 'predict_segmentation' 导入 TensorFlow 模型 Keras 时
【发布时间】:2021-12-06 21:25:38
【问题描述】:

我已经成功训练了一个 Keras 模型,例如:

import tensorflow as tf
from keras_segmentation.models.unet import vgg_unet

# initaite the model
model = vgg_unet(n_classes=50, input_height=512, input_width=608)

# Train
model.train(
    train_images=train_images,
    train_annotations=train_annotations,
    checkpoints_path="/tmp/vgg_unet_1", epochs=5
)

并将其保存为 hdf5 格式:

tf.keras.models.save_model(model,'my_model.hdf5')

然后我加载我的模型

model=tf.keras.models.load_model('my_model.hdf5')

最后我想对一张新图像进行分割预测

out = model.predict_segmentation(
    inp=image_to_test,
    out_fname="/tmp/out.png"
)

我收到以下错误:

AttributeError: 'Functional' object has no attribute 'predict_segmentation'

我做错了什么? 是在保存模型时还是在加载模型时?

谢谢!

【问题讨论】:

  • 从哪里得知这个 predict_segmentation 方法确实存在?
  • 嗯,在我保存模型之前它确实存在,因为我可以使用相同的代码进行良好的分割预测。
  • 当然,但这不是 Keras 模型的标准方法。

标签: python tensorflow keras deep-learning


【解决方案1】:

predict_segmentation 不是普通 Keras 模型中可用的函数。好像是在keras_segmentation库中创建模型后添加的,这可能是Keras无法再次加载它的原因。

我认为您有两种选择。

  1. 您可以使用我链接的代码中的行手动将函数添加回模型。
model.predict_segmentation = MethodType(keras_segmentation.predict.predict, model)
  1. 您可以在重新加载模型时使用相同的参数创建一个新的vgg_unet,然后按照Keras documentation 中的建议将权重从您的hdf5 文件传输到该模型。
model = vgg_unet(n_classes=50, input_height=512, input_width=608)
model.load_weights('my_model.hdf5')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 2020-11-21
    • 1970-01-01
    相关资源
    最近更新 更多