|
|
|
import sklearn |
|
from sklearn.datasets import load_breast_cancer |
|
from sklearn.tree import DecisionTreeClassifier |
|
from sklearn.model_selection import train_test_split |
|
from skops import card, hub_utils |
|
import pickle |
|
from sklearn.metrics import (ConfusionMatrixDisplay, confusion_matrix, |
|
accuracy_score, f1_score) |
|
import matplotlib.pyplot as plt |
|
from pathlib import Path |
|
|
|
|
|
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 |
|
) |
|
|
|
|
|
model = DecisionTreeClassifier().fit(X_train, y_train) |
|
|
|
|
|
model_path = "example.pkl" |
|
local_repo = "my-awesome-model" |
|
with open(model_path, mode="bw") as f: |
|
pickle.dump(model, file=f) |
|
|
|
|
|
hub_utils.init( |
|
model=model_path, |
|
requirements=[f"scikit-learn={sklearn.__version__}"], |
|
dst=local_repo, |
|
task="tabular-classification", |
|
data=X_test, |
|
) |
|
|
|
|
|
|
|
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}}" |
|
|
|
|
|
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, |
|
) |
|
|
|
|
|
model_card.metadata.license = "mit" |
|
|
|
|
|
y_pred = model.predict(X_test) |
|
|
|
|
|
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")}) |
|
|
|
|
|
cm = confusion_matrix(y_test, y_pred, labels=model.classes_) |
|
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=model.classes_) |
|
disp.plot() |
|
|
|
|
|
plt.savefig(Path(local_repo) / "confusion_matrix.png") |
|
|
|
|
|
|
|
model_card.add_plot(confusion_matrix="confusion_matrix.png") |
|
|
|
|
|
model_card.save(Path(local_repo) / "README.md") |
|
|
|
|
|
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, |
|
) |
|
|
|
|