forked from Lightning-AI/dl-fundamentals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocal_utilities.py
76 lines (57 loc) · 2.4 KB
/
local_utilities.py
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
import lightning as L
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import torch
import torch.nn.functional as F
import torchmetrics
class LightningModel(L.LightningModule):
def __init__(self, model, learning_rate):
super().__init__()
self.learning_rate = learning_rate
self.model = model
self.train_acc = torchmetrics.Accuracy(task="multiclass", num_classes=2)
self.val_acc = torchmetrics.Accuracy(task="multiclass", num_classes=2)
self.test_acc = torchmetrics.Accuracy(task="multiclass", num_classes=2)
def forward(self, x):
return self.model(x)
def _shared_step(self, batch):
features, true_labels = batch
logits = self(features)
loss = F.cross_entropy(logits, true_labels)
predicted_labels = torch.argmax(logits, dim=1)
return loss, true_labels, predicted_labels
def training_step(self, batch, batch_idx):
loss, true_labels, predicted_labels = self._shared_step(batch)
self.log("train_loss", loss)
self.train_acc(predicted_labels, true_labels)
self.log(
"train_acc", self.train_acc, prog_bar=True, on_epoch=True, on_step=False
)
return loss
def validation_step(self, batch, batch_idx):
loss, true_labels, predicted_labels = self._shared_step(batch)
self.log("val_loss", loss, prog_bar=True)
self.val_acc(predicted_labels, true_labels)
self.log("val_acc", self.val_acc, prog_bar=True)
def test_step(self, batch, batch_idx):
loss, true_labels, predicted_labels = self._shared_step(batch)
self.test_acc(predicted_labels, true_labels)
self.log("test_acc", self.test_acc)
def configure_optimizers(self):
optimizer = torch.optim.SGD(self.parameters(), lr=self.learning_rate)
return optimizer
def plot_csv_logger(
csv_path, loss_names=["train_loss", "val_loss"], eval_names=["train_acc", "val_acc"]
):
metrics = pd.read_csv(csv_path)
aggreg_metrics = []
agg_col = "epoch"
for i, dfg in metrics.groupby(agg_col):
agg = dict(dfg.mean())
agg[agg_col] = i
aggreg_metrics.append(agg)
df_metrics = pd.DataFrame(aggreg_metrics)
df_metrics[loss_names].plot(grid=True, legend=True, xlabel="Epoch", ylabel="Loss")
df_metrics[eval_names].plot(grid=True, legend=True, xlabel="Epoch", ylabel="ACC")
plt.show()