介紹 Skops

釋出於 2022 年 8 月 12 日
在 GitHub 上更新

介紹 Skops

在 Hugging Face,我們致力於解決開源機器學習中的各種問題,包括安全開放地託管模型、實現可復現性、可解釋性和協作。我們很高興向您介紹我們的新庫:Skops!藉助 Skops,您可以在 Hugging Face Hub 上託管您的 scikit-learn 模型,建立模型卡用於模型文件並與他人協作。

讓我們透過一個端到端示例:首先訓練一個模型,然後逐步瞭解如何在生產中利用 Skops for sklearn。

# let's import the libraries first
import sklearn
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split

# Load the data and split
X, y = load_breast_cancer(as_frame=True, return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=42
)

# Train the model
model = DecisionTreeClassifier().fit(X_train, y_train)

您可以使用任何模型檔名和序列化方法,例如 `pickle` 或 `joblib`。目前,我們的後端使用 `joblib` 載入模型。`hub_utils.init` 會建立一個本地資料夾,其中包含給定路徑中的模型,以及包含模型訓練環境規範的配置檔案。傳遞給 `init` 的資料和任務將幫助 Hugging Face Hub 在模型頁面上啟用推理小部件,以及查詢模型的發現功能。

from skops import hub_utils
import pickle

# let's save the model
model_path = "example.pkl"
local_repo = "my-awesome-model"
with open(model_path, mode="bw") as f:
    pickle.dump(model, file=f)

# we will now initialize a local repository
hub_utils.init(
    model=model_path, 
    requirements=[f"scikit-learn={sklearn.__version__}"], 
    dst=local_repo,
    task="tabular-classification",
    data=X_test,
)

該倉庫現在包含序列化模型和配置檔案。該配置包含以下內容

  • 模型特性,
  • 模型要求,
  • 我們傳入的 `X_test` 中的示例輸入,
  • 模型檔名,
  • 此處要解決的任務名稱。

我們現在將建立模型卡。該卡應符合預期的 Hugging Face Hub 格式:一個 Markdown 部分和一個元資料部分,即頂部的 `yaml` 部分。元資料部分的鍵在此處定義here,並用於模型的發現。模型卡的內容由一個模板確定,該模板具有一個

  • 頂部的 `yaml` 部分用於元資料(例如模型許可證、庫名稱等)
  • Markdown 部分包含自由文字和待填充部分(例如模型的簡單描述),以下部分由 `skops` 提取以填充模型卡
  • 模型超引數,
  • 模型的互動式圖表,
  • 對於元資料,將填充庫名稱、任務識別符號(例如 tabular-classification)以及推理小部件所需的其他資訊。

我們將向您介紹如何以程式設計方式傳遞資訊以填充模型卡。您可以檢視我們關於 `skops` 提供的預設模板及其部分的文件here,以瞭解模板的預期內容及其外觀here

您可以從 `skops` 例項化 `Card` 類來建立模型卡。在模型序列化期間,任務名稱和庫名稱寫入配置檔案。此資訊也需要在卡的元資料中,因此您可以使用 `metadata_from_config` 方法從配置檔案中提取元資料並在建立卡時將其傳遞給卡。您可以使用 `add` 新增資訊和元資料。

from skops import card

# create the card 
model_card = card.Card(model, metadata=card.metadata_from_config(Path(destination_folder)))

limitations = "This model is not ready to be used in production."
model_description = "This is a DecisionTreeClassifier model trained on breast cancer dataset."
model_card_authors = "skops_user"
get_started_code = "import pickle \nwith open(dtc_pkl_filename, 'rb') as file: \n    clf = pickle.load(file)"
citation_bibtex = "bibtex\n@inproceedings{...,year={2020}}"

# we can add the information using add
model_card.add(
    citation_bibtex=citation_bibtex,
    get_started_code=get_started_code,
    model_card_authors=model_card_authors,
    limitations=limitations,
    model_description=model_description,
)

# we can set the metadata part directly
model_card.metadata.license = "mit"

我們現在將評估模型並使用 `add` 新增評估方法的描述。度量指標透過 `add_metrics` 新增,它將被解析為表格。

from sklearn.metrics import (ConfusionMatrixDisplay, confusion_matrix,
                            accuracy_score, f1_score)
# let's make a prediction and evaluate the model
y_pred = model.predict(X_test)
# we can pass metrics using add_metrics and pass details with add
model_card.add(eval_method="The model is evaluated using test split, on accuracy and F1 score with macro average.")
model_card.add_metrics(accuracy=accuracy_score(y_test, y_pred))
model_card.add_metrics(**{"f1 score": f1_score(y_test, y_pred, average="micro")})

我們還可以使用 `add_plot` 將我們選擇的任何圖表新增到卡中,如下所示。

import matplotlib.pyplot as plt
from pathlib import Path
# we will create a confusion matrix
cm = confusion_matrix(y_test, y_pred, labels=model.classes_)
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=model.classes_)
disp.plot()

# save the plot
plt.savefig(Path(local_repo) / "confusion_matrix.png")

# the plot will be written to the model card under the name confusion_matrix
# we pass the path of the plot itself
model_card.add_plot(confusion_matrix="confusion_matrix.png")

讓我們將模型卡儲存到本地倉庫。這裡的檔名應該是 `README.md`,因為這是 Hugging Face Hub 期望的。

model_card.save(Path(local_repo) / "README.md")

我們現在可以將倉庫推送到 Hugging Face Hub。為此,我們將使用 `hub_utils` 中的 `push`。Hugging Face Hub 需要令牌進行身份驗證,因此如果您從筆記本登入,則需要在 `notebook_login` 中傳入您的令牌;如果您從 CLI 登入,則需要在 `huggingface-cli login` 中傳入您的令牌。

# if the repository doesn't exist remotely on the Hugging Face Hub, it will be created when we set create_remote to True
repo_id = "skops-user/my-awesome-model"
hub_utils.push(
    repo_id=repo_id,
    source=local_repo,
    token=token,
    commit_message="pushing files to the repo from the example!",
    create_remote=True,
)

一旦我們將模型推送到 Hub,除非倉庫是私有的,否則任何人都可以使用它。您可以使用 `download` 下載模型。除了模型檔案,倉庫還包含模型配置和環境要求。

download_repo = "downloaded-model"
hub_utils.download(repo_id=repo_id, dst=download_repo)

推理小部件已啟用,可以在倉庫中進行預測。

Hosted Inference Widget

如果您的專案要求發生變化,您可以使用 `update_env` 更新環境。

hub_utils.update_env(path=local_repo, requirements=["scikit-learn"])

您可以在此處檢視使用上述程式碼推送的示例倉庫。我們準備了兩個示例來展示如何儲存模型和使用模型卡實用程式。您可以在下面的資源部分找到它們。

資源

社群

註冊登入 發表評論

© . This site is unofficial and not affiliated with Hugging Face, Inc.