

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 自動向 SageMaker 模型註冊庫註冊 SageMaker AI 模型
<a name="mlflow-track-experiments-model-registration"></a>

您可以記錄 MLflow 模型，並使用 Python SDK 或直接透過 MLflow UI 自動向 SageMaker 模型註冊庫註冊它們。

**注意**  
請勿在模型名稱中使用空格。雖然 MLflow 支援具有空格的模型名稱，但 SageMaker AI 模型套件不支援。如果您在模型名稱中使用空格，則自動註冊程序會失敗。

## 使用 SageMaker Python SDK 註冊模型
<a name="mlflow-track-experiments-model-registration-sdk"></a>

在 MLflow 用戶端內使用 `create_registered_model` 在 SageMaker AI 中自動建立與您選擇的現有 MLflow 模型對應的模型套件群組。

```
import mlflow 
from mlflow import MlflowClient

mlflow.set_tracking_uri(arn)

client = MlflowClient()

mlflow_model_name = 'AutoRegisteredModel'
client.create_registered_model(mlflow_model_name, tags={"key1": "value1"})
```

在模型訓練期間，使用 `mlflow.register_model()` 自動向 SageMaker 模型註冊庫註冊模型。註冊 MLflow 模型時，會在 SageMaker AI 中建立對應的模型套件群組和模型套件版本。

```
import mlflow.sklearn
from mlflow.models import infer_signature
from sklearn.datasets import make_regression
from sklearn.ensemble import RandomForestRegressor

mlflow.set_tracking_uri(arn)
params = {"n_estimators": 3, "random_state": 42}
X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False)

# Log MLflow entities
with mlflow.start_run() as run:
    rfr = RandomForestRegressor(**params).fit(X, y)
    signature = infer_signature(X, rfr.predict(X))
    mlflow.log_params(params)
    mlflow.sklearn.log_model(rfr, artifact_path="sklearn-model", signature=signature)

model_uri = f"runs:/{run.info.run_id}/sklearn-model"
mv = mlflow.register_model(model_uri, "RandomForestRegressionModel")

print(f"Name: {mv.name}")
print(f"Version: {mv.version}")
```

## 使用 MLflow UI 註冊模型
<a name="mlflow-track-experiments-model-registration-ui"></a>

您也可以直接在 MLflow UI 中使用 SageMaker 模型註冊庫註冊模型。在 MLflow UI 的**模型**選單中，選擇**建立模型**。以這種方式新建立的任何模型都會新增至 SageMaker 模型註冊庫。

![\[在 MLflow UI 中建立模型註冊庫。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/mlflow/mlflow-ui-register-model.png)


在實驗追蹤期間記錄模型後，導覽至 MLflow UI 中的執行頁面。選擇**成品**窗格，然後選擇右上角的**註冊模型**，以在 MLflow 和 SageMaker 模型註冊庫中註冊模型版本。

![\[在 MLflow UI 中建立模型註冊庫。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/mlflow/mlflow-ui-register-model-2.png)


## 在 Studio 中檢視已註冊的模型
<a name="mlflow-track-experiments-model-registration-ui-view"></a>

在 SageMaker Studio 登陸頁面中，選擇左側導覽窗格中的**模型**以檢視已註冊的模型。如需開始使用 Studio 的相關資訊，請參閱[啟動 Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html)。

![\[在 Studio UI 的 SageMaker 模型註冊庫中註冊的 MLflow 模型。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/mlflow/mlflow-studio-model-registry.png)
