如何将已安装的变压器保存到Blob中,以便您的预测管道可以在AML服务中使用它?

时间:2019-06-12 09:11:16

标签: python azure-machine-learning-service

我正在Azure机器学习服务上建立数据转换和培训管道。我想将安装好的变压器(例如tf-idf)保存到Blob,以便我的预测管道稍后可以访问它。

transformed_data = PipelineData("transformed_data", 
                               datastore = default_datastore,
                               output_path_on_compute="my_project/tfidf")

step_tfidf = PythonScriptStep(name = "tfidf_step",
                              script_name = "transform.py",
                              arguments = ['--input_data', blob_train_data, 
                                           '--output_folder', transformed_data],
                              inputs = [blob_train_data],
                              outputs = [transformed_data],
                              compute_target = aml_compute,
                              source_directory = project_folder,
                              runconfig = run_config,
                              allow_reuse = False)

上面的代码将转换器保存到当前运行的文件夹中,该文件夹在每次运行期间动态生成。

我想将转换器保存到blob上的固定位置,以便稍后在调用预测管道时可以访问它。

我尝试将DataReference类的实例用作PythonScriptStep的输出,但是会导致错误: ValueError: Unexpected output type: <class 'azureml.data.data_reference.DataReference'>

这是因为PythonScriptStep仅接受PipelineDataOutputPortBinding对象作为输出。

我如何保存我安装的变压器,以便以后可以通过任意过程访问它(例如,我的预测管道)?

3 个答案:

答案 0 :(得分:1)

这可能不够灵活,无法满足您的需求(而且,我还没有测试过),但是如果您使用scikit-learn,则一种可能性是将tf-idf / transformation步骤包含在scikit-learn { {1}}对象并将其注册到您的工作空间中。

您的训练脚本将因此包含:

Pipeline

,您的实验提交脚本将包含

pipeline = Pipeline([
    ('vectorizer', TfidfVectorizer(stop_words = list(text.ENGLISH_STOP_WORDS))),
    ('classifier', SGDClassifier()
])

pipeline.fit(train[label].values, train[pred_label].values)

# Serialize the pipeline
joblib.dump(value=pipeline, filename='outputs/model.pkl')

然后,您可以使用已注册的“模型”,并通过{p> 3将其加载到评分脚本中,将其作为explained in the documentation部署为服务。

run = exp.submit(src)
run.wait_for_completion(show_output = True)
model = run.register_model(model_name='my_pipeline', model_path='outputs/model.pkl')

但是,这会使管道中的转换发生变化,因此不会像您要求的那样模块化...

答案 1 :(得分:1)

另一种解决方案是将DataReference作为输入传递到PythonScriptStep

然后在transform.py内,您可以将此DataReference作为命令行参数来读取。

您可以解析它并将其用作保存矢量化器的任何常规路径。

例如您可以:

step_tfidf = PythonScriptStep(name = "tfidf_step",
                              script_name = "transform.py",
                              arguments = ['--input_data', blob_train_data, 
                                           '--output_folder', transformed_data,
                                           '--transformer_path', trained_transformer_path],
                              inputs = [blob_train_data, trained_transformer_path],
                              outputs = [transformed_data],
                              compute_target = aml_compute,
                              source_directory = project_folder,
                              runconfig = run_config,
                              allow_reuse = False)

然后在脚本中(例如上例中的transform.py),例如:

import argparse
import joblib as jbl
import os

from sklearn.feature_extraction.text import TfidfVectorizer

parser = argparse.ArgumentParser()
parser.add_argument('--transformer_path', dest="transformer_path", required=True)
args = parser.parse_args()

tfidf = ### HERE CREATE AND TRAIN YOUR VECTORIZER ###

vect_filename = os.path.join(args.vectorizer_path, 'my_vectorizer.jbl')


额外:第三种方法是将矢量化器注册为工作空间中的另一个模型。然后,您可以将其与其他任何注册模型完全一样地使用。 (尽管该选项不涉及对blob的显式写入-如上面的问题中所述)

答案 2 :(得分:1)

另一种选择是使用DataTransferStep并将其复制到“已知位置”。 This notebook举例说明了使用DataTransferStep在各种受支持的数据存储之间复制数据。

from azureml.data.data_reference import DataReference
from azureml.exceptions import ComputeTargetException
from azureml.core.compute import ComputeTarget, DataFactoryCompute
from azureml.pipeline.steps import DataTransferStep

blob_datastore = Datastore.get(ws, "workspaceblobstore")

blob_data_ref = DataReference(
    datastore=blob_datastore,
    data_reference_name="knownloaction",
    path_on_datastore="knownloaction")

data_factory_name = 'adftest'

def get_or_create_data_factory(workspace, factory_name):
    try:
        return DataFactoryCompute(workspace, factory_name)
    except ComputeTargetException as e:
        if 'ComputeTargetNotFound' in e.message:
            print('Data factory not found, creating...')
            provisioning_config = DataFactoryCompute.provisioning_configuration()
            data_factory = ComputeTarget.create(workspace, factory_name, provisioning_config)
            data_factory.wait_for_completion()
            return data_factory
        else:
            raise e

data_factory_compute = get_or_create_data_factory(ws, data_factory_name)

# Assuming output data is your output from the step that you want to copy

transfer_to_known_location = DataTransferStep(
    name="transfer_to_known_location",
    source_data_reference=[output_data],
    destination_data_reference=blob_data_ref,
    compute_target=data_factory_compute
    )

from azureml.pipeline.core import Pipeline
from azureml.core import Workspace, Experiment

pipeline_01 = Pipeline(
    description="transfer_to_known_location",
    workspace=ws,
    steps=[transfer_to_known_location])

pipeline_run_01 = Experiment(ws, "transfer_to_known_location").submit(pipeline_01)
pipeline_run_01.wait_for_completion()