-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_utils.py
More file actions
58 lines (51 loc) · 1.91 KB
/
plot_utils.py
File metadata and controls
58 lines (51 loc) · 1.91 KB
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
import matplotlib.pyplot as plt
import numpy as np
def plot_histories(
history,
name: str,
n_epochs=10,
):
"""
Plot history of the passed models.
:param history: History of the first model.
:param name: Name of the first model.
:param n_epochs: Number of epochs to plot.
"""
# Get the n first values of the metrics
acc_key, loss_key, val_acc_key, val_loss_key = 'accuracy', 'loss', 'val_accuracy', 'val_loss'
if not all(k in history.history for k in [acc_key, loss_key, val_acc_key, val_loss_key]):
print(f'Fehlende Metriken in History von {name}')
return
tr_acc: np.ndarray = _first_n(history, acc_key, n_epochs)
tr_loss: np.ndarray = _first_n(history, loss_key, n_epochs)
va_acc: np.ndarray = _first_n(history, val_acc_key, n_epochs)
va_loss: np.ndarray = _first_n(history, val_loss_key, n_epochs)
# Create figures
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
epochs = np.arange(1, len(tr_loss) + 1)
# Plot loss
axes[0].plot(epochs, tr_loss, label=f"{name} train loss")
axes[0].plot(epochs, va_loss, label=f"{name} val loss")
axes[0].set_xlabel("Epoche")
axes[0].set_ylabel("Loss")
axes[0].set_title(f"Loss (erste {len(epochs)} Epochen)")
axes[0].legend()
axes[0].grid(True)
# Plot accuracy
axes[1].plot(epochs, tr_acc, label=f"{name} train acc")
axes[1].plot(epochs, va_acc, label=f"{name} val acc")
axes[1].set_xlabel("Epoche")
axes[1].set_ylabel("Accuracy")
axes[1].set_title(f"Accuracy (erste {len(epochs)} Epochen)")
axes[1].legend()
axes[1].grid(True)
plt.tight_layout()
plt.show()
def _first_n(history, key: str, n: int = 10) -> np.ndarray:
"""
Get the n first values of a metric.
:param history: History of the model.
:key: Metric to get.
:n: Number of values to get.
"""
return np.array(history.history[key][:n], dtype=float)