EduardoPacheco commited on
Commit
e757838
·
1 Parent(s): db42b5d

Utilities to run app

Browse files
Files changed (1) hide show
  1. utils.py +60 -0
utils.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+ import plotly.express as px
5
+ import plotly.graph_objects as go
6
+ from sklearn.base import ClassifierMixin
7
+ from sklearn.pipeline import make_pipeline
8
+ from sklearn.metrics import roc_curve, auc
9
+ from sklearn.datasets import make_classification
10
+ from sklearn.linear_model import LogisticRegression
11
+ from sklearn.model_selection import train_test_split
12
+ from sklearn.preprocessing import FunctionTransformer, OneHotEncoder
13
+ from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, RandomTreesEmbedding
14
+
15
+
16
+ def create_and_split_dataset(n_samples: int) -> list[tuple[np.ndarray, np.array]]:
17
+ # Create Data
18
+ X, y = make_classification(n_samples=n_samples, random_state=10)
19
+
20
+ # Split Data
21
+ X_full_train, X_test, y_full_train, y_test = train_test_split(
22
+ X, y, test_size=0.5, random_state=10
23
+ )
24
+
25
+ # Split Data for Ensemble and Linear Model
26
+ X_train_ensemble, X_train_linear, y_train_ensemble, y_train_linear = train_test_split(
27
+ X_full_train, y_full_train, test_size=0.5, random_state=10
28
+ )
29
+
30
+ return (X_train_ensemble, y_train_ensemble), (X_train_linear, y_train_linear), (X_test, y_test)
31
+
32
+ def rf_apply(X, model):
33
+ return model.apply(X)
34
+
35
+ def gbdt_apply(X, model):
36
+ return model.apply(X)[:, :, 0]
37
+
38
+ def plot_roc(X: np.ndarray, y:np.array, models: tuple[str, ClassifierMixin]):
39
+ fig = go.Figure()
40
+
41
+ fig.add_shape(
42
+ type='line', line=dict(dash='dash'),
43
+ x0=0, x1=1, y0=0, y1=1
44
+ )
45
+
46
+ for model_name, model in models:
47
+ y_score = model.predict_proba(X)[:, 1]
48
+ fpr, tpr, _ = roc_curve(y, y_score)
49
+ auc_val = auc(fpr, tpr)
50
+ name = f"{model_name} (AUC={auc_val:.4f})"
51
+ fig.add_trace(go.Scatter(x=fpr, y=tpr, name=name, mode='lines'))
52
+
53
+ fig.update_layout(
54
+ title="Model ROC Curve Comparison",
55
+ xaxis_title='False Positive Rate',
56
+ yaxis_title='True Positive Rate',
57
+ width=1000, height=600
58
+ )
59
+
60
+ return fig