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np
|
| 2 |
+
from sklearn.datasets import load_iris
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
|
| 5 |
+
from sklearn import svm, linear_model
|
| 6 |
+
from sklearn.metrics import auc
|
| 7 |
+
from sklearn.metrics import RocCurveDisplay
|
| 8 |
+
from sklearn.model_selection import StratifiedKFold
|
| 9 |
+
import gradio as gr
|
| 10 |
+
|
| 11 |
+
from functools import partial
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# Wrap the [Initial Analysis](https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc_crossval.html)
|
| 15 |
+
|
| 16 |
+
def auc_analysis(selected_data, n_folds, cls_name):
|
| 17 |
+
default_base = {"n_folds": 5}
|
| 18 |
+
|
| 19 |
+
# Load and prepare iris data
|
| 20 |
+
iris = load_iris()
|
| 21 |
+
X_iris, y_iris, target_names_iris = iris.data, iris.target, iris.target_names
|
| 22 |
+
X_iris, y_iris, target_names_iris = X_iris[y_iris != 2], y_iris[y_iris != 2], target_names_iris[0:-1]
|
| 23 |
+
n_samples_iris, n_features_iris = X_iris.shape
|
| 24 |
+
# Add noisy features to make the problem harder
|
| 25 |
+
random_state = np.random.RandomState(0)
|
| 26 |
+
X_iris = np.concatenate([X_iris, random_state.randn(n_samples_iris, 200 * n_features_iris)], axis=1)
|
| 27 |
+
|
| 28 |
+
dataset_list = {
|
| 29 |
+
"Iris": [X_iris, y_iris, target_names_iris]
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
# Load selected data
|
| 33 |
+
params = default_base.copy()
|
| 34 |
+
params.update({"n_folds": n_folds})
|
| 35 |
+
X, y, target_names = dataset_list[selected_data]
|
| 36 |
+
|
| 37 |
+
# Define classification model
|
| 38 |
+
svc_linear = svm.SVC(kernel="linear", probability=True, random_state=random_state)
|
| 39 |
+
logistic_regression = linear_model.LogisticRegression()
|
| 40 |
+
|
| 41 |
+
classification_models = {
|
| 42 |
+
"SVC - linear kernel": svc_linear,
|
| 43 |
+
"Logistic Regression": logistic_regression
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
classifier = classification_models[cls_name]
|
| 47 |
+
|
| 48 |
+
# Define folds
|
| 49 |
+
cv = StratifiedKFold(n_splits=params["n_folds"])
|
| 50 |
+
|
| 51 |
+
# ROC analysis
|
| 52 |
+
tprs = []
|
| 53 |
+
aucs = []
|
| 54 |
+
mean_fpr = np.linspace(0, 1, 100)
|
| 55 |
+
|
| 56 |
+
fig, ax = plt.subplots(figsize=(6, 6))
|
| 57 |
+
for fold, (train, test) in enumerate(cv.split(X, y)):
|
| 58 |
+
classifier.fit(X[train], y[train])
|
| 59 |
+
viz = RocCurveDisplay.from_estimator(
|
| 60 |
+
classifier,
|
| 61 |
+
X[test],
|
| 62 |
+
y[test],
|
| 63 |
+
name=f"ROC fold {fold}",
|
| 64 |
+
alpha=0.5,
|
| 65 |
+
lw=1,
|
| 66 |
+
ax=ax,
|
| 67 |
+
)
|
| 68 |
+
interp_tpr = np.interp(mean_fpr, viz.fpr, viz.tpr)
|
| 69 |
+
interp_tpr[0] = 0.0
|
| 70 |
+
tprs.append(interp_tpr)
|
| 71 |
+
aucs.append(viz.roc_auc)
|
| 72 |
+
ax.plot([0, 1], [0, 1], "k--", label="chance level (AUC = 0.5)")
|
| 73 |
+
|
| 74 |
+
mean_tpr = np.mean(tprs, axis=0)
|
| 75 |
+
mean_tpr[-1] = 1.0
|
| 76 |
+
mean_auc = auc(mean_fpr, mean_tpr)
|
| 77 |
+
std_auc = np.std(aucs)
|
| 78 |
+
ax.plot(
|
| 79 |
+
mean_fpr,
|
| 80 |
+
mean_tpr,
|
| 81 |
+
color="b",
|
| 82 |
+
label=r"Mean ROC (AUC = %0.2f $\pm$ %0.2f)" % (mean_auc, std_auc),
|
| 83 |
+
lw=2,
|
| 84 |
+
alpha=0.8,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
std_tpr = np.std(tprs, axis=0)
|
| 88 |
+
tprs_upper = np.minimum(mean_tpr + std_tpr, 1)
|
| 89 |
+
tprs_lower = np.maximum(mean_tpr - std_tpr, 0)
|
| 90 |
+
ax.fill_between(
|
| 91 |
+
mean_fpr,
|
| 92 |
+
tprs_lower,
|
| 93 |
+
tprs_upper,
|
| 94 |
+
color="grey",
|
| 95 |
+
alpha=0.2,
|
| 96 |
+
label=r"$\pm$ 1 std. dev.",
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
ax.set(
|
| 100 |
+
xlim=[-0.05, 1.05],
|
| 101 |
+
ylim=[-0.05, 1.05],
|
| 102 |
+
xlabel="False Positive Rate",
|
| 103 |
+
ylabel="True Positive Rate",
|
| 104 |
+
title=f"Mean ROC curve with variability\n(Positive label '{target_names[1]}')",
|
| 105 |
+
)
|
| 106 |
+
ax.axis("square")
|
| 107 |
+
ax.legend(loc="lower right")
|
| 108 |
+
|
| 109 |
+
return fig
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# Build the Demo
|
| 113 |
+
|
| 114 |
+
def iter_grid(n_rows, n_cols):
|
| 115 |
+
# create a grid using gradio Block
|
| 116 |
+
for _ in range(n_rows):
|
| 117 |
+
with gr.Row():
|
| 118 |
+
for _ in range(n_cols):
|
| 119 |
+
with gr.Column():
|
| 120 |
+
yield
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
input_models = ["SVC - linear kernel", "Logistic Regression"]
|
| 124 |
+
|
| 125 |
+
title = "🔬 Receiver Operating Characteristic (ROC) with cross validation"
|
| 126 |
+
with gr.Blocks(title=title) as demo:
|
| 127 |
+
gr.Markdown(f"## {title}")
|
| 128 |
+
gr.Markdown(
|
| 129 |
+
"This app demonstrates Receiver Operating Characteristic (ROC) metric estimate variability using "
|
| 130 |
+
"cross-validation. It shows the response of ROC and of its variance to different datasets, created from "
|
| 131 |
+
"K-fold cross-validation. "
|
| 132 |
+
"See the [source](https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc_crossval.html)"
|
| 133 |
+
" for more details.")
|
| 134 |
+
gr.Markdown(f'Available classification models: {", ".join(input_models)}.')
|
| 135 |
+
|
| 136 |
+
with gr.Row():
|
| 137 |
+
with gr.Column():
|
| 138 |
+
input_data = gr.Radio(
|
| 139 |
+
choices=["Iris"],
|
| 140 |
+
value="Iris",
|
| 141 |
+
label="Dataset",
|
| 142 |
+
info="Available datasets"
|
| 143 |
+
)
|
| 144 |
+
with gr.Column():
|
| 145 |
+
n_folds = gr.Radio(
|
| 146 |
+
[3, 4, 5, 6, 7, 8, 9], value=4, label="Folds", info="Number of cross-validation splits"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
counter = 0
|
| 150 |
+
for _ in iter_grid(len(input_models) // 2 + len(input_models) % 2, 2):
|
| 151 |
+
if counter >= len(input_models):
|
| 152 |
+
break
|
| 153 |
+
input_model = input_models[counter]
|
| 154 |
+
plot = gr.Plot(label=input_model)
|
| 155 |
+
fn = partial(auc_analysis, cls_name=input_model)
|
| 156 |
+
input_data.change(fn=fn, inputs=[input_data, n_folds], outputs=plot)
|
| 157 |
+
n_folds.change(fn=fn, inputs=[input_data, n_folds], outputs=plot)
|
| 158 |
+
counter += 1
|
| 159 |
+
|
| 160 |
+
if __name__ == "__main__":
|
| 161 |
+
demo.launch()
|