共用方式為


如何在 Microsoft Fabric 中使用 scikit-learn 來定型模型

Scikit-learn (scikit-learn.org) 是熱門的開放原始碼機器學習架構。 它經常用於監督和非監督式學習。 它也提供各種工具,可用於模型調整、數據前置處理、模型選取、模型評估等等。

在本節中,我們將逐步解說如何定型和追蹤 Scikit-Learn 模型的反覆專案。

安裝 scikit-learn

若要開始使用 scikit-learn,您必須確定已在筆記本內安裝。 您可以使用下列命令在您的環境中安裝或升級 scikit-learn 版本:

%pip install scikit-learn

接下來,我們將使用 MLFLow API 建立機器學習實驗。 如果 MLflow set_experiment() API 不存在,將會建立新的機器學習實驗。

import mlflow

mlflow.set_experiment("sample-sklearn")

定型 scikit-learn 模型

建立實驗之後,我們將建立範例數據集,並建立羅吉斯回歸模型。 我們也會啟動 MLflow 執行,並追蹤計量、參數和最終羅吉斯回歸模型。 產生最終模型之後,我們也會儲存產生的模型以取得額外的追蹤。

import mlflow.sklearn
import numpy as np
from sklearn.linear_model import LogisticRegression
from mlflow.models.signature import infer_signature

with mlflow.start_run() as run:

    lr = LogisticRegression()
    X = np.array([-2, -1, 0, 1, 2, 1]).reshape(-1, 1)
    y = np.array([0, 0, 1, 1, 1, 0])
    lr.fit(X, y)
    score = lr.score(X, y)
    signature = infer_signature(X, y)

    print("log_metric.")
    mlflow.log_metric("score", score)

    print("log_params.")
    mlflow.log_param("alpha", "alpha")

    print("log_model.")
    mlflow.sklearn.log_model(lr, "sklearn-model", signature=signature)
    print("Model saved in run_id=%s" % run.info.run_id)

    print("register_model.")
    mlflow.register_model(

        "runs:/{}/sklearn-model".format(run.info.run_id), "sample-sklearn"
    )
    print("All done")

在範例數據集上載入和評估模型

儲存模型之後,也可以載入以進行推斷。 若要這樣做,我們將載入模型,並在範例數據集上執行推斷。

# Inference with loading the logged model
from synapse.ml.predict import MLflowTransformer

spark.conf.set("spark.synapse.ml.predict.enabled", "true")

model = MLflowTransformer(
    inputCols=["x"],
    outputCol="prediction",
    modelName="sample-sklearn",
    modelVersion=1,
)

test_spark = spark.createDataFrame(
    data=np.array([-2, -1, 0, 1, 2, 1]).reshape(-1, 1).tolist(), schema=["x"]
)

batch_predictions = model.transform(test_spark)

batch_predictions.show()