【问题标题】:Google AI Platform: Unexpected error when loading the model: 'str' object has no attribute 'decode' [Keras 2.3.1, TF 1.15]Google AI Platform:加载模型时出现意外错误:'str' object has no attribute 'decode' [Keras 2.3.1, TF 1.15]
【发布时间】:2021-02-23 23:28:26
【问题描述】:

我正在尝试使用 Google 人工智能平台中的测试版 Google 自定义预测例程来运行我的模型的实时版本。

我在我的包中包含predictor.py,其中包含一个Predictor 类:

import os
import numpy as np
import pickle
import keras
from keras.models import load_model

class Predictor(object):
    """Interface for constructing custom predictors."""

    def __init__(self, model, preprocessor):
        self._model = model
        self._preprocessor = preprocessor

    def predict(self, instances, **kwargs):
        """Performs custom prediction.

        Instances are the decoded values from the request. They have already
        been deserialized from JSON.

        Args:
            instances: A list of prediction input instances.
            **kwargs: A dictionary of keyword args provided as additional
                fields on the predict request body.

        Returns:
            A list of outputs containing the prediction results. This list must
            be JSON serializable.
        """
        # pre-processing
        preprocessed_inputs = self._preprocessor.preprocess(instances[0])

        # predict
        outputs = self._model.predict(preprocessed_inputs)

        # post-processing
        outputs = np.array([np.fliplr(x) for x in x_test])
        return outputs.tolist()

    @classmethod
    def from_path(cls, model_dir):
        """Creates an instance of Predictor using the given path.

        Loading of the predictor should be done in this method.

        Args:
            model_dir: The local directory that contains the exported model
                file along with any additional files uploaded when creating the
                version resource.

        Returns:
            An instance implementing this Predictor class.
        """
        model_path = os.path.join(model_dir, 'keras.model')
        model = load_model(model_path, compile=False)

        preprocessor_path = os.path.join(model_dir, 'preprocess.pkl')
        with open(preprocessor_path, 'rb') as f:
            preprocessor = pickle.load(f)

        return cls(model, preprocessor)

完整的错误Create Version failed. Bad model detected with error: "Failed to load model: Unexpected error when loading the model: 'str' object has no attribute 'decode' (Error code: 0)" 表明问题出在此脚本中,特别是在加载模型时。但是,我可以使用predict.py 中的相同代码块在本地成功地将模型加载到我的笔记本中:

from keras.models import load_model
model = load_model('keras.model', compile=False)

我看过类似的帖子,建议设置h5py<3.0.0 的版本,但这没有帮助。我可以在setup.py 文件中为我的自定义预测例程设置模块版本:

from setuptools import setup

REQUIRED_PACKAGES = ['keras==2.3.1', 'h5py==2.10.0', 'opencv-python', 'pydicom', 'scikit-image']

setup(
    name='my_custom_code',
    install_requires=REQUIRED_PACKAGES,
    include_package_data=True,
    version='0.23',
    scripts=['predictor.py', 'preprocess.py'])

很遗憾,我在 google 的 AI Platform 中没有找到调试模型部署的好方法,故障排除指南也无济于事。任何指针将不胜感激。谢谢!

编辑 1:

h5py 模块的版本错误 –– 3.1.0,尽管在setup.py 中将其设置为 2.10.0。有谁知道为什么?我确认 Keras 版本和其他模块设置正确。我试过'h5py==2.9.0''h5py<3.0.0' 无济于事。更多关于包含 PyPi 包依赖项here

编辑 2:

所以事实证明,谷歌目前不支持此功能。

【问题讨论】:

  • 可以添加完整的回溯吗?我认为是 h5py 的问题,所以请确认实际使用的是早于 3.0.0 的版本。
  • @Dr.Snoopy 感谢您的回复。我很想进行调试,但谷歌 AI 平台向我展示的都是这个错误。错误消息似乎是由谷歌云包装的,我看不到至少在模型部署时为自定义预测例程调试事物的方法。
  • @Dr.Snoopy 你是对的,它奇怪地使用了 3.1.0 版本。我做了一些 hacky 的东西(注释掉模型的加载,预测函数只返回 h5py 版本)。我知道事实上它正在正确设置 keras 的版本,而不是由于某种原因而不是 h5py。将调查:)

标签: python tensorflow keras gcloud google-ai-platform


【解决方案1】:

我在使用 AI 平台和两个月前运行良好的代码时遇到了同样的问题,那时我们最后一次训练我们的模型。事实上,这是由于对 h5py 的依赖导致无法突然加载 h5 模型。

一段时间后,我能够使其与运行时 2.2 和 python 版本 3.7 一起工作。我也在使用自定义预测例程,我的模型是一个简单的 2 层双向 LSTM 服务分类。

我有一个使用 TF == 2.1 设置的笔记本 VM,并将 h5py 降级为

!pip uninstall -y h5py

!pip install 'h5py < 3.0.0'

我的 setup.py 看起来像这样:

from setuptools import setup

REQUIRED_PACKAGES = ['tensorflow==2.1', 'h5py<3.0.0']

setup(
  name="my_package",
  version="0.1",
  include_package_data=True,
  scripts=["preprocess.py", "model_prediction.py"]
)

我在模型加载代码中添加了compile=False。没有它,我遇到了另一个部署问题,出现以下错误:Create Version failed. Bad model detected with error: "Failed to load model: Unexpected error when loading the model: 'sample_weight_mode' (Error code: 0)"

OP 的代码变化:

model = keras.models.load_model(
        os.path.join(model_dir,'model.h5'), compile = False)

这使得模型像以前一样部署没有问题。我怀疑 compile=False 可能意味着更慢的预测服务,但到目前为止还没有注意到任何事情。

希望这可以帮助任何卡在谷歌上搜索这些问题的人!

【讨论】:

    猜你喜欢
    • 2019-05-13
    • 2017-05-10
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 2019-06-09
    相关资源
    最近更新 更多