可解譯性:自動化 ML 中的模型可解釋性 (預覽)

適用於:Python SDK azureml 第 1 版

在本文中,您將了解如何使用 Python SDK,在 Azure Machine Learning 中取得自動化機器學習 (自動 ML) 模型的說明。 自動化 ML 可協助您了解所產生模型的特徵重要度。

根據預設,1.0.85 之後的所有 SDK 版本都會設定 model_explainability=True。 在 1.0.85 版和更舊版本的 SDK 中,使用者必須在 AutoMLConfig 物件中設定 model_explainability=True,才能使用模型可解譯性。

在本文中,您將學會如何:

  • 在定型期間,針對最佳模型或任何模型執行可解譯性。
  • 啟用視覺效果,以協助您查看資料中的模式和說明。
  • 在推斷或評分期間執行可解譯性。

必要條件

  • 可解譯性特徵。 執行 pip install azureml-interpret 以取得必要的套件。
  • 建置自動化 ML 實驗的知識。 如需如何使用 Azure Machine Learning SDK 的詳細資訊,請完成此物件偵測模型教學課程,或了解如何設定自動化 ML 實驗

重要

此功能目前處於公開預覽。 此預覽版本沒有服務等級協定,不建議用於處理生產工作負載。 可能不支援特定功能,或可能已經限制功能。

如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用條款

在定型期間針對最佳模型執行可解譯性

best_run 取得的說明,其中包含原始和工程特徵兩者的說明。

注意

可解譯性 (模型說明) 無法供自動 ML 預測實驗所建議的 TCNForecaster 模型使用。

從最佳執行下載工程特徵重要度

您可以使用 ExplanationClient,從 best_run 的成品存放區下載工程特徵說明。

from azureml.interpret import ExplanationClient

client = ExplanationClient.from_run(best_run)
engineered_explanations = client.download_model_explanation(raw=False)
print(engineered_explanations.get_feature_importance_dict())

從最佳執行下載原始特徵重要度

您可以使用 ExplanationClient,從 best_run 的成品存放區下載原始特徵說明。

from azureml.interpret import ExplanationClient

client = ExplanationClient.from_run(best_run)
raw_explanations = client.download_model_explanation(raw=True)
print(raw_explanations.get_feature_importance_dict())

在定型期間針對任何模型執行可解譯性

計算模型說明並將其視覺化時,您不會受限於 AutoML 模型的現有模型說明。 您也可以使用不同的測試資料來取得模型的說明。 本節中的步驟說明如何根據您的測試資料,計算並視覺化工程特徵重要度。

從定型中擷取任何其他 AutoML 模型

automl_run, fitted_model = local_run.get_output(metric='accuracy')

設定模型說明

使用 automl_setup_model_explanations 來取得工程和原始說明。 fitted_model 可以產生下列項目:

  • 來自定型或測試樣本的特徵資料
  • 工程特徵名稱清單
  • 分類案例中已標記資料行中的 Findable 類別

automl_explainer_setup_obj 包含上述清單中的所有結構。

from azureml.train.automl.runtime.automl_explain_utilities import automl_setup_model_explanations

automl_explainer_setup_obj = automl_setup_model_explanations(fitted_model, X=X_train, 
                                                             X_test=X_test, y=y_train, 
                                                             task='classification')

初始化特徵重要度的模仿解譯器

若要產生自動化 ML 模型的說明,請使用 MimicWrapper 類別。 您可以使用下列參數來初始化 MimicWrapper:

  • 解譯器設定物件
  • 您的工作區
  • 用來說明 fitted_model 自動化 ML 模型的代理模型

MimicWrapper 也會採用將上傳工程說明的 automl_run 物件。

from azureml.interpret import MimicWrapper

# Initialize the Mimic Explainer
explainer = MimicWrapper(ws, automl_explainer_setup_obj.automl_estimator,
                         explainable_model=automl_explainer_setup_obj.surrogate_model, 
                         init_dataset=automl_explainer_setup_obj.X_transform, run=automl_run,
                         features=automl_explainer_setup_obj.engineered_feature_names, 
                         feature_maps=[automl_explainer_setup_obj.feature_map],
                         classes=automl_explainer_setup_obj.classes,
                         explainer_kwargs=automl_explainer_setup_obj.surrogate_model_params)

使用模仿解譯器進行計算,並將工程特徵重要度視覺化

您可以在 MimicWrapper 中使用已轉換的測試範例來呼叫 explain() 方法,為產生的工程特徵取得特徵重要度。 您也可以登入 Azure Machine Learning 工作室,透過自動化的 ML 特徵化工具,檢視所產生工程特徵的特徵重要度的說明儀表板視覺效果。

engineered_explanations = explainer.explain(['local', 'global'], eval_dataset=automl_explainer_setup_obj.X_test_transform)
print(engineered_explanations.get_feature_importance_dict())

針對使用自動化 ML 定型的模型,您可以在本機使用 get_output() 方法和計算說明來取得最佳模型。 您可以使用 raiwidgets 套件中的 ExplanationDashboard 將說明結果視覺化。

best_run, fitted_model = remote_run.get_output()

from azureml.train.automl.runtime.automl_explain_utilities import AutoMLExplainerSetupClass, automl_setup_model_explanations
automl_explainer_setup_obj = automl_setup_model_explanations(fitted_model, X=X_train,
                                                             X_test=X_test, y=y_train,
                                                             task='regression')

from interpret.ext.glassbox import LGBMExplainableModel
from azureml.interpret.mimic_wrapper import MimicWrapper

explainer = MimicWrapper(ws, automl_explainer_setup_obj.automl_estimator, LGBMExplainableModel,
                         init_dataset=automl_explainer_setup_obj.X_transform, run=best_run,
                         features=automl_explainer_setup_obj.engineered_feature_names,
                         feature_maps=[automl_explainer_setup_obj.feature_map],
                         classes=automl_explainer_setup_obj.classes)
                         
pip install interpret-community[visualization]

engineered_explanations = explainer.explain(['local', 'global'], eval_dataset=automl_explainer_setup_obj.X_test_transform)
print(engineered_explanations.get_feature_importance_dict()),
from raiwidgets import ExplanationDashboard
ExplanationDashboard(engineered_explanations, automl_explainer_setup_obj.automl_estimator, datasetX=automl_explainer_setup_obj.X_test_transform)

 

raw_explanations = explainer.explain(['local', 'global'], get_raw=True,
                                     raw_feature_names=automl_explainer_setup_obj.raw_feature_names,
                                     eval_dataset=automl_explainer_setup_obj.X_test_transform)
print(raw_explanations.get_feature_importance_dict()),
from raiwidgets import ExplanationDashboard
ExplanationDashboard(raw_explanations, automl_explainer_setup_obj.automl_pipeline, datasetX=automl_explainer_setup_obj.X_test_raw)

使用模仿解譯器進行計算,並將原始特徵重要度視覺化

您可以在 MimicWrapper 中使用已轉換的測試範例來呼叫 explain() 方法,為原始特徵取得特徵重要度。 在機器學習工作室中,您可以檢視原始特徵的特徵重要度的儀表板視覺效果。

raw_explanations = explainer.explain(['local', 'global'], get_raw=True,
                                     raw_feature_names=automl_explainer_setup_obj.raw_feature_names,
                                     eval_dataset=automl_explainer_setup_obj.X_test_transform,
                                     raw_eval_dataset=automl_explainer_setup_obj.X_test_raw)
print(raw_explanations.get_feature_importance_dict())

在推斷期間執行可解譯性

在本節中,您會了解如何使用解譯器,讓自動化的 ML 模型能夠運作,而此解譯器已用來計算上一節中的說明。

註冊模型和評分解譯器

使用 TreeScoringExplainer 建立評分解譯器,其會在推斷時計算工程特徵重要度值。 您可以使用先前計算的 feature_map 來初始化評分解譯器。

儲存評分解譯器,然後使用模型管理服務註冊模型和評分解譯器。 執行下列程式碼:

from azureml.interpret.scoring.scoring_explainer import TreeScoringExplainer, save

# Initialize the ScoringExplainer
scoring_explainer = TreeScoringExplainer(explainer.explainer, feature_maps=[automl_explainer_setup_obj.feature_map])

# Pickle scoring explainer locally
save(scoring_explainer, exist_ok=True)

# Register trained automl model present in the 'outputs' folder in the artifacts
original_model = automl_run.register_model(model_name='automl_model', 
                                           model_path='outputs/model.pkl')

# Register scoring explainer
automl_run.upload_file('scoring_explainer.pkl', 'scoring_explainer.pkl')
scoring_explainer_model = automl_run.register_model(model_name='scoring_explainer', model_path='scoring_explainer.pkl')

建立用於設定服務的 Conda 相依性

接下來,在已部署模型的容器中建立必要的環境相依性。 請注意,版本 >= 1.0.45 的 azureml-defaults 必須列示為 pip 相依性,因為其包含將模型裝載為 Web 服務所需的功能。

from azureml.core.conda_dependencies import CondaDependencies

azureml_pip_packages = [
    'azureml-interpret', 'azureml-train-automl', 'azureml-defaults'
]

myenv = CondaDependencies.create(conda_packages=['scikit-learn', 'pandas', 'numpy', 'py-xgboost<=0.80'],
                                 pip_packages=azureml_pip_packages,
                                 pin_sdk_version=True)

with open("myenv.yml","w") as f:
    f.write(myenv.serialize_to_string())

with open("myenv.yml","r") as f:
    print(f.read())

建立評分指令碼

撰寫一個指令碼,載入您的模型,並根據新的資料批次產生預測和說明。

%%writefile score.py
import joblib
import pandas as pd
from azureml.core.model import Model
from azureml.train.automl.runtime.automl_explain_utilities import automl_setup_model_explanations


def init():
    global automl_model
    global scoring_explainer

    # Retrieve the path to the model file using the model name
    # Assume original model is named automl_model
    automl_model_path = Model.get_model_path('automl_model')
    scoring_explainer_path = Model.get_model_path('scoring_explainer')

    automl_model = joblib.load(automl_model_path)
    scoring_explainer = joblib.load(scoring_explainer_path)


def run(raw_data):
    data = pd.read_json(raw_data, orient='records')
    # Make prediction
    predictions = automl_model.predict(data)
    # Setup for inferencing explanations
    automl_explainer_setup_obj = automl_setup_model_explanations(automl_model,
                                                                 X_test=data, task='classification')
    # Retrieve model explanations for engineered explanations
    engineered_local_importance_values = scoring_explainer.explain(automl_explainer_setup_obj.X_test_transform)
    # Retrieve model explanations for raw explanations
    raw_local_importance_values = scoring_explainer.explain(automl_explainer_setup_obj.X_test_transform, get_raw=True)
    # You can return any data type as long as it is JSON-serializable
    return {'predictions': predictions.tolist(),
            'engineered_local_importance_values': engineered_local_importance_values,
            'raw_local_importance_values': raw_local_importance_values}

部署服務

使用先前步驟中的 Conda 檔案和評分檔案來部署服務。

from azureml.core.webservice import Webservice
from azureml.core.webservice import AciWebservice
from azureml.core.model import Model, InferenceConfig
from azureml.core.environment import Environment

aciconfig = AciWebservice.deploy_configuration(cpu_cores=1,
                                               memory_gb=1,
                                               tags={"data": "Bank Marketing",  
                                                     "method" : "local_explanation"},
                                               description='Get local explanations for Bank marketing test data')
myenv = Environment.from_conda_specification(name="myenv", file_path="myenv.yml")
inference_config = InferenceConfig(entry_script="score_local_explain.py", environment=myenv)

# Use configs and models generated above
service = Model.deploy(ws,
                       'model-scoring',
                       [scoring_explainer_model, original_model],
                       inference_config,
                       aciconfig)
service.wait_for_deployment(show_output=True)

使用測試資料進行推斷

使用某些測試資料進行推斷,可查看 AutoML 模型中的預測值,目前只在 Azure Machine Learning SDK 中支援此操作。 檢視對預測值做出貢獻的特徵重要度。

if service.state == 'Healthy':
    # Serialize the first row of the test data into json
    X_test_json = X_test[:1].to_json(orient='records')
    print(X_test_json)
    # Call the service to get the predictions and the engineered explanations
    output = service.run(X_test_json)
    # Print the predicted value
    print(output['predictions'])
    # Print the engineered feature importances for the predicted value
    print(output['engineered_local_importance_values'])
    # Print the raw feature importances for the predicted value
    print('raw_local_importance_values:\n{}\n'.format(output['raw_local_importance_values']))

視覺化以在定型時探索資料中的模式以及說明

Azure Machine Learning 工作室中,您可以視覺化工作區中的特徵重要度圖表。 在 AutoML 執行完成之後,請選取 [檢視模型詳細資料] 來檢視特定執行。 選取 [說明] 索引標籤,在說明儀表板中查看視覺效果。

Machine Learning Interpretability Architecture

如需說明儀表板視覺效果和特定繪圖的詳細資訊,請參閱可解譯性的操作說明文件

下一步

如需如何在非自動化 ML 的區域中啟用模型說明和特徵重要度的詳細資訊,請參閱更多模型可解譯性技術