EduardoPacheco commited on
Commit
99addf7
1 Parent(s): d333d0f
Files changed (1) hide show
  1. utils.py +60 -0
utils.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import plotly.express as px
4
+ from sklearn.inspection import permutation_importance
5
+
6
+ def plot_rf_importance(clf):
7
+ feature_names = clf[:-1].get_feature_names_out()
8
+ mdi_importances = pd.Series(
9
+ clf[-1].feature_importances_, index=feature_names
10
+ ).sort_values(ascending=True)
11
+
12
+
13
+ fig = px.bar(mdi_importances, orientation="h", title="Random Forest Feature Importances (MDI)")
14
+ fig.update_layout(showlegend=False, xaxis_title="Importance", yaxis_title="Feature")
15
+
16
+ return fig
17
+
18
+ def plot_permutation_boxplot(clf, X: np.ndarray, y: np.array, set_: str=None):
19
+
20
+ result = permutation_importance(
21
+ clf, X, y, n_repeats=10, random_state=42, n_jobs=2
22
+ )
23
+
24
+ sorted_importances_idx = result.importances_mean.argsort()
25
+ importances = pd.DataFrame(
26
+ result.importances[sorted_importances_idx].T,
27
+ columns=X.columns[sorted_importances_idx],
28
+ )
29
+
30
+ fig = px.box(
31
+ importances.melt(),
32
+ y="variable",
33
+ x="value"
34
+ )
35
+
36
+ # Add dashed vertical line
37
+ fig.add_shape(
38
+ type="line",
39
+ x0=0,
40
+ y0=-1,
41
+ x1=0,
42
+ y1=len(importances.columns),
43
+ opacity=0.5,
44
+ line=dict(
45
+ dash="dash"
46
+ ),
47
+ )
48
+ # Adapt x-range
49
+ x_min = importances.min().min()
50
+ x_min = x_min - 0.005 if x_min < 0 else -0.005
51
+ x_max = importances.max().max() + 0.005
52
+ fig.update_xaxes(range=[x_min, x_max])
53
+ fig.update_layout(
54
+ title=f"Permutation Importances {set_ if set_ else ''}",
55
+ xaxis_title="Importance",
56
+ yaxis_title="Feature",
57
+ showlegend=False
58
+ )
59
+
60
+ return fig