File size: 7,594 Bytes
674a23c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
from typing import List
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sn
from sklearn.metrics import auc
from sklearn.metrics import roc_curve
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from tensorflow import keras
class PlottingManager:
"""Responsible for providing plots & visualization for the models."""
def __init__(self) -> None:
"""Define style for visualizations."""
plt.style.use("seaborn")
def plot_subplots_curve(
self,
training_measure: List[List[float]],
validation_measure: List[List[float]],
title: str,
train_color: str = "orangered",
validation_color: str = "dodgerblue",
) -> None:
"""
Plotting subplots of the elements of `training_measure` vs. `validation_measure`.
Parameters:
------------
- training_measure : List[List[float]]
A `k` by `num_epochs` list contains the trained measure whether it's loss or
accuracy for each fold.
- validation_measure : List[List[float]]
A `k` by `num_epochs` list contains the validation measure whether it's loss
or accuracy for each fold.
- title : str
Represents the title of the plot.
- train_color : str, optional
Represents the graph color for the `training_measure`. (Default is "orangered").
- validation_color : str, optional
Represents the graph color for the `validation_measure`. (Default is "dodgerblue").
"""
plt.figure(figsize=(12, 8))
for i in range(len(training_measure)):
plt.subplot(2, 2, i + 1)
plt.plot(training_measure[i], c=train_color)
plt.plot(validation_measure[i], c=validation_color)
plt.title("Fold " + str(i + 1))
plt.suptitle(title)
plt.show()
def plot_heatmap(
self, measure: List[List[float]], title: str, cmap: str = "coolwarm"
) -> None:
"""
Plotting a heatmap of the values in `measure`.
Parameters:
------------
- measure : List[List[float]]
A `k` by `num_epochs` list contains the measure whether it's loss
or accuracy for each fold.
- title : str
Title of the plot.
- cmap : str, optional
Color map of the plot (default is "coolwarm").
"""
# transpose the array to make it `num_epochs` by `k`
values_array = np.array(measure).T
df_cm = pd.DataFrame(
values_array,
range(1, values_array.shape[0] + 1),
["fold " + str(i + 1) for i in range(4)],
)
plt.figure(figsize=(10, 8))
plt.title(
title + " Throughout " + str(values_array.shape[1]) + " Folds", pad=20
)
sn.heatmap(df_cm, annot=True, cmap=cmap, annot_kws={"size": 10})
plt.show()
def plot_average_curves(
self,
title: str,
x: List[float],
y: List[float],
x_label: str,
y_label: str,
train_color: str = "orangered",
validation_color: str = "dodgerblue",
) -> None:
"""
Plotting the curves of `x` against `y`, where x and y are training and validation
measures (loss or accuracy).
Parameters:
------------
- title : str
Title of the plot.
- x : List[float]
Training measure of the models (loss or accuracy).
- y : List[float]
Validation measure of the models (loss or accuracy).
- x_label : str
Label of the training measure to put it in plot legend.
- y_label : str
Label of the validation measure to put it in plot legend.
- train_color : str, optional
Color of the training plot (default is "orangered").
- validation_color : str, optional
Color of the validation plot (default is "dodgerblue").
"""
plt.title(title, pad=20)
plt.plot(x, c=train_color, label=x_label)
plt.plot(y, c=validation_color, label=y_label)
plt.legend()
plt.show()
def plot_roc_curve(
self,
all_models: List[keras.models.Sequential],
X_test: pd.DataFrame,
y_test: pd.Series,
) -> None:
"""
Plotting the AUC-ROC curve of all the passed models in `all_models`.
Parameters:
------------
- all_models : List[keras.models.Sequential]
Contains all trained models, number of models equals number of
`k` fold cross-validation.
- X_test : pd.DataFrame
Contains the testing vectors.
- y_test : pd.Series
Contains the testing labels.
"""
plt.figure(figsize=(12, 8))
for i, model in enumerate(all_models):
y_pred = model.predict(X_test).ravel()
fpr, tpr, _ = roc_curve(y_test, y_pred)
auc_curve = auc(fpr, tpr)
plt.subplot(2, 2, i + 1)
plt.plot([0, 1], [0, 1], color="dodgerblue", linestyle="--")
plt.plot(
fpr,
tpr,
color="orangered",
label=f"Fold {str(i+1)} (area = {auc_curve:.3f})",
)
plt.legend(loc="best")
plt.title(f"Fold {str(i+1)}")
plt.suptitle("AUC-ROC curves")
plt.show()
def plot_classification_report(
self, model: keras.models.Sequential, X_test: pd.DataFrame, y_test: pd.Series
) -> str | dict:
"""
Plotting the classification report of the passed `model`.
Parameters:
------------
- model : keras.models.Sequential
The trained model that will be evaluated.
- X_test : pd.DataFrame
Contains the testing vectors.
- y_test : pd.Series
Contains the testing labels.
Returns:
--------
- str | dict: The classification report for the given model and testing data.
It returns a string if `output_format` is set to 'str', and returns
a dictionary if `output_format` is set to 'dict'.
"""
y_pred = model.predict(X_test).ravel()
preds = np.where(y_pred > 0.5, 1, 0)
cls_report = classification_report(y_test, preds)
return cls_report
def plot_confusion_matrix(
self,
all_models: List[keras.models.Sequential],
X_test: pd.DataFrame,
y_test: pd.Series,
) -> None:
"""
Plotting the confusion matrix of each model in `all_models`.
Parameters:
------------
- all_models: list[keras.models.Sequential]
Contains all trained models, number of models equals
number of `k` fold cross-validation.
- X_test: pd.DataFrame
Contains the testing vectors.
- y_test: pd.Series
Contains the testing labels.
"""
_, axes = plt.subplots(nrows=2, ncols=2, figsize=(12, 8))
for i, (model, ax) in enumerate(zip(all_models, axes.flatten())):
y_pred = model.predict(X_test).ravel()
preds = np.where(y_pred > 0.5, 1, 0)
conf_matrix = confusion_matrix(y_test, preds)
sn.heatmap(conf_matrix, annot=True, ax=ax)
ax.set_title(f"Fold {i+1}")
plt.suptitle("Confusion Matrices")
plt.tight_layout()
plt.show()
|