Upload train.py
Browse files
train.py
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import skops
|
2 |
+
import sklearn
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
from sklearn.preprocessing import OneHotEncoder
|
5 |
+
from sklearn.impute import SimpleImputer
|
6 |
+
from sklearn.compose import ColumnTransformer
|
7 |
+
from sklearn.tree import DecisionTreeClassifier
|
8 |
+
from sklearn.pipeline import Pipeline
|
9 |
+
|
10 |
+
# preprocess the dataset
|
11 |
+
|
12 |
+
df = pd.read_csv("../input/tabular-playground-series-aug-2022/train.csv")
|
13 |
+
|
14 |
+
|
15 |
+
column_transformer_pipeline = ColumnTransformer([
|
16 |
+
("loading_missing_value_imputer", SimpleImputer(strategy="mean"), ["loading"]),
|
17 |
+
("numerical_missing_value_imputer", SimpleImputer(strategy="mean"), list(df.columns[df.dtypes == 'float64'])),
|
18 |
+
("attribute_0_encoder", OneHotEncoder(categories = "auto"), ["attribute_0"]),
|
19 |
+
("attribute_1_encoder", OneHotEncoder(categories = "auto"), ["attribute_1"]),
|
20 |
+
("product_code_encoder", OneHotEncoder(categories = "auto"), ["product_code"])])
|
21 |
+
|
22 |
+
df = df.drop(["id"], axis=1)
|
23 |
+
|
24 |
+
|
25 |
+
pipeline = Pipeline([
|
26 |
+
('transformation', column_transformer_pipeline),
|
27 |
+
('model', DecisionTreeClassifier(max_depth=4))
|
28 |
+
])
|
29 |
+
|
30 |
+
X = df.drop(["failure"], axis = 1)
|
31 |
+
y = df.failure
|
32 |
+
|
33 |
+
# split the data and train the model
|
34 |
+
|
35 |
+
from sklearn.model_selection import train_test_split
|
36 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y)
|
37 |
+
pipeline.fit(X_train, y_train)
|
38 |
+
|
39 |
+
# we will now use skops to initialize a repository
|
40 |
+
# create a model card, and push the model to the
|
41 |
+
# Hugging Face Hub
|
42 |
+
from skops import card, hub_utils
|
43 |
+
import pickle
|
44 |
+
|
45 |
+
model_path = "model.pkl"
|
46 |
+
local_repo = "decision-tree-playground-kaggle"
|
47 |
+
|
48 |
+
# save the model
|
49 |
+
with open(model_path, mode="bw") as f:
|
50 |
+
pickle.dump(pipeline, file=f)
|
51 |
+
|
52 |
+
# initialize the repository
|
53 |
+
hub_utils.init(
|
54 |
+
model=model_path,
|
55 |
+
requirements=[f"scikit-learn={sklearn.__version__}"],
|
56 |
+
dst=local_repo,
|
57 |
+
task="tabular-classification",
|
58 |
+
data=X_test,
|
59 |
+
)
|
60 |
+
|
61 |
+
# initialize the model card
|
62 |
+
from pathlib import Path
|
63 |
+
model_card = card.Card(pipeline, metadata=card.metadata_from_config(Path(local_repo)))
|
64 |
+
|
65 |
+
## let's fill some information about the model
|
66 |
+
limitations = "This model is not ready to be used in production."
|
67 |
+
model_description = "This is a DecisionTreeClassifier model built for Kaggle Tabular Playground Series August 2022, trained on supersoaker production failures dataset."
|
68 |
+
model_card_authors = "huggingface"
|
69 |
+
get_started_code = f"import pickle \nwith open({local_repo}/{model_path}, 'rb') as file: \n clf = pickle.load(file)"
|
70 |
+
|
71 |
+
# pass this information to the card
|
72 |
+
model_card.add(
|
73 |
+
get_started_code=get_started_code,
|
74 |
+
model_card_authors=model_card_authors,
|
75 |
+
limitations=limitations,
|
76 |
+
model_description=model_description,
|
77 |
+
)
|
78 |
+
|
79 |
+
# we will now evaluate the model and write eval results to the card
|
80 |
+
from sklearn.metrics import accuracy_score, f1_score, ConfusionMatrixDisplay, confusion_matrix
|
81 |
+
model_card.add(eval_method="The model is evaluated using test split, on accuracy and F1 score with micro average.")
|
82 |
+
model_card.add_metrics(accuracy=accuracy_score(y_test, y_pred))
|
83 |
+
model_card.add_metrics(**{"f1 score": f1_score(y_test, y_pred, average="micro")})
|
84 |
+
|
85 |
+
model = pipeline.steps[-1][1]
|
86 |
+
|
87 |
+
# we will plot the tree and add the plot to our card
|
88 |
+
from sklearn.tree import plot_tree
|
89 |
+
plt.figure()
|
90 |
+
plot_tree(model,filled=True)
|
91 |
+
plt.savefig(f'{local_repo}/tree.png',format='png',bbox_inches = "tight")
|
92 |
+
|
93 |
+
# let's make a prediction and evaluate the model
|
94 |
+
y_pred = pipeline.predict(X_test)
|
95 |
+
cm = confusion_matrix(y_test, y_pred, labels=model.classes_)
|
96 |
+
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=model.classes_)
|
97 |
+
disp.plot()
|
98 |
+
|
99 |
+
# save the plot
|
100 |
+
plt.savefig(Path(local_repo) / "confusion_matrix.png")
|
101 |
+
|
102 |
+
# add figures to model card with their new sections as keys to the dictionary
|
103 |
+
model_card.add_plot(**{"Tree Plot": f'{local_repo}/tree.png', "Confusion Matrix": f"{local_repo}/confusion_matrix.png"})
|
104 |
+
|
105 |
+
#save the card
|
106 |
+
model_card.save(f"{local_repo}/README.md")
|
107 |
+
|
108 |
+
# we can now push the model!
|
109 |
+
# if the repository doesn't exist remotely on the Hugging Face Hub, it will be created when we set create_remote to True
|
110 |
+
repo_id = "scikit-learn/tabular-playground"
|
111 |
+
hub_utils.push(
|
112 |
+
repo_id=repo_id,
|
113 |
+
source=local_repo,
|
114 |
+
token=token,
|
115 |
+
commit_message="pushing files to the repo from the example!",
|
116 |
+
create_remote=True,
|
117 |
+
)
|