无法在AI平台自定义预测中使用configparser

时间:2020-05-05 17:28:32

标签: setuptools google-cloud-ml

我正在寻找一种在预测器代码中将configparser用于自定义预测例程的方法。 我尝试了以下代码段

common.cfg

[MODEL]
VERSION=config-true

setup.py

from setuptools import setup

REQUIRED_PACKAGES = [
    'joblib==0.13.0'
]

setup(
    name='test',
    description='Custom prediction routine',
    version=0.1,
    install_requires=REQUIRED_PACKAGES,
    scripts=['src/predictor.py', 'config/common.cfg']
)

predictor.py

import os
import joblib
import subprocess
import configparser

class CustomPredictor(object):
    def __init__(self, model, config):
        self._model = model
        self._config = config

    def predict(self, instances, **kwargs):
        version_value = self._config.get('MODEL', 'VERSION', fallback='config-false')
        print(f'version value = {version_value}', flush=True) # printing config-false

        preprocessed_input = self._preprocess(instances)

        score = self._model.predict(preprocessed_input)

        print(f'predicted score {score}', flush=True)
        return score.to_list()

    @classmethod
    def from_path(cls, model_dir):
        config = configparser.RawConfigParser()
        result = config.read('config/common.cfg')
        print(f'read config result: {result}', flush=True) # empty
        print(f'config sections: {config.sections()}', flush=True) # empty

        subprocess.run(["ls", "-l"]) # don't see the config file or folder

        model_path = os.path.join(model_dir, "model.joblib")
        model = joblib.load(model_path)

        return cls(model, config)

关于我做错了什么或想念什么的任何建议吗?

3 个答案:

答案 0 :(得分:0)

我运行了这段代码,它显示了预期的结果:

config = configparser.RawConfigParser()
result = config.read('common.cfg')
print(f'read config result: {result}', flush=True) # empty
print(f'config sections: {config.sections()}', flush=True) # empty

输出为

read config result: ['common.cfg']
config sections: ['MODEL']

所以可能的错误可能是common.cfg文件的路径。

当我复制代码并运行它时,它显示输出为空列表,因为文件位于同一目录中,而不是config目录中,但是一旦我更正路径,它就会打印出预期结果。

答案 1 :(得分:0)

您有2个选择:

  1. 配置setup.py并在其中添加configparser
REQUIRED_PACKAGES = [
    'joblib==0.13.0',
    'configparser'
]
  1. 创建模型时,使用package-uris将配置解析器作为软件包传递。在pypi中,我已经找到tar.gz文件。 请看一下this的示例,当我们传递一个PyTorch包时,在您的情况下,请从pypi下载文件并将其放入GCS Bucket,然后在创建模型时在其中定义它:
gcloud beta ai-platform versions create {MODEL_VERSION} --model {MODEL_NAME} \
 --origin=gs://{BUCKET_NAME}/{MODEL_DIR}/ \
 --python-version=3.7 \
 --runtime-version={RUNTIME_VERSION} \
 --package-uris=gs://{BUCKET_NAME}/{PACKAGES_DIR}/text_classification-0.1.tar.gz,
gs://{BUCKET_NAME}/configparser-5.0.0.tar.gz  \
 --machine-type=mls1-c4-m4 \
 --prediction-class=model.CustomModelPrediction

答案 2 :(得分:0)

我发现我在自定义预测例程的部署过程中犯的错误,ai平台将文件保留在/tmp/custom_lib/bin/下,并将执行路径保留为根目录。因此,在我的代码中,我已将配置路径更新为类似

config_file = pathlib.Path(__file__).parent.absolute() / 'common.cfg'
config.read(config_file)

这可以解决问题!

注意:我还认为我们需要将配置文件保留在 scripts 标签下,因为当部署逻辑安装软件包时,setuptools会将脚本复制到AI平台定义的PATH并使其可用。