Skip to content

Commit 11bbfd9

Browse files
committed
Merge branch 'main' into dataset-rework
2 parents d3b1a70 + a5a6c01 commit 11bbfd9

File tree

12 files changed

+275
-24
lines changed

12 files changed

+275
-24
lines changed

main.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,14 +66,14 @@ def main():
6666
"--modelname",
6767
type=str,
6868
default="MagnusModel",
69-
choices=["MagnusModel", "ChristianModel"],
69+
choices=["MagnusModel", "ChristianModel", "SolveigModel"],
7070
help="Model which to be trained on",
7171
)
7272
parser.add_argument(
7373
"--dataset",
7474
type=str,
7575
default="svhn",
76-
choices=["svhn", "usps_0-6"],
76+
choices=["svhn", "usps_0-6", "uspsh5_7_9"],
7777
help="Which dataset to train the model on.",
7878
)
7979

tests/test_metrics.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from utils.metrics import Recall
1+
from utils.metrics import Recall, F1Score
22

33

44
def test_recall():
@@ -14,3 +14,19 @@ def test_recall():
1414
assert recall_score.allclose(torch.tensor(0.7143), atol=1e-5), (
1515
f"Recall Score: {recall_score.item()}"
1616
)
17+
18+
19+
def test_f1score():
20+
import torch
21+
22+
f1_metric = F1Score(num_classes=3)
23+
preds = torch.tensor(
24+
[[0.8, 0.1, 0.1], [0.2, 0.7, 0.1], [0.2, 0.3, 0.5], [0.1, 0.2, 0.7]]
25+
)
26+
27+
target = torch.tensor([0, 1, 0, 2])
28+
29+
f1_metric.update(preds, target)
30+
assert f1_metric.tp.sum().item() > 0, "Expected some true positives."
31+
assert f1_metric.fp.sum().item() > 0, "Expected some false positives."
32+
assert f1_metric.fn.sum().item() > 0, "Expected some false negatives."

utils/dataloaders/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1-
__all__ = ["USPSDataset0_6"]
1+
__all__ = ["USPSDataset0_6", "USPSH5_Digit_7_9_Dataset"]
22

33
from .usps_0_6 import USPSDataset0_6
4+
from .uspsh5_7_9 import USPSH5_Digit_7_9_Dataset

utils/load_data.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
from torch.utils.data import Dataset
22

3-
from .dataloaders import USPSDataset0_6
3+
from .dataloaders import USPSDataset0_6, USPSH5_Digit_7_9_Dataset
44

55

66
def load_data(dataset: str, *args, **kwargs) -> Dataset:
77
match dataset.lower():
88
case "usps_0-6":
99
return USPSDataset0_6(*args, **kwargs)
10+
case "usps_7-9":
11+
return USPSH5_Digit_7_9_Dataset(*args, **kwargs)
1012
case _:
1113
raise ValueError(f"Dataset: {dataset} not implemented.")

utils/load_metric.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import numpy as np
44
import torch.nn as nn
55

6-
from .metrics import EntropyPrediction
6+
from .metrics import EntropyPrediction, F1Score, precision
77

88

99
class MetricWrapper(nn.Module):
@@ -35,11 +35,11 @@ def _get_metric(self, key):
3535
case "entropy":
3636
return EntropyPrediction()
3737
case "f1":
38-
raise NotImplementedError("F1 score not implemented yet")
38+
raise F1Score()
3939
case "recall":
4040
raise NotImplementedError("Recall score not implemented yet")
4141
case "precision":
42-
raise NotImplementedError("Precision score not implemented yet")
42+
return precision()
4343
case "accuracy":
4444
raise NotImplementedError("Accuracy score not implemented yet")
4545
case _:

utils/load_model.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import torch.nn as nn
22

3-
from .models import ChristianModel, MagnusModel
3+
from .models import ChristianModel, MagnusModel, SolveigModel
44

55

66
def load_model(modelname: str, *args, **kwargs) -> nn.Module:
@@ -9,6 +9,8 @@ def load_model(modelname: str, *args, **kwargs) -> nn.Module:
99
return MagnusModel(*args, **kwargs)
1010
case "christianmodel":
1111
return ChristianModel(*args, **kwargs)
12+
case "solveigmodel":
13+
return SolveigModel(*args, **kwargs)
1214
case _:
1315
raise ValueError(
1416
f"Model: {modelname} has not been implemented. \nCheck the documentation for implemented metrics, or check your spelling"

utils/metrics/F1.py

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -85,16 +85,3 @@ def compute(self):
8585

8686
return f1_score
8787

88-
89-
def test_f1score():
90-
f1_metric = F1Score(num_classes=3)
91-
preds = torch.tensor(
92-
[[0.8, 0.1, 0.1], [0.2, 0.7, 0.1], [0.2, 0.3, 0.5], [0.1, 0.2, 0.7]]
93-
)
94-
95-
target = torch.tensor([0, 1, 0, 2])
96-
97-
f1_metric.update(preds, target)
98-
assert f1_metric.tp.sum().item() > 0, "Expected some true positives."
99-
assert f1_metric.fp.sum().item() > 0, "Expected some false positives."
100-
assert f1_metric.fn.sum().item() > 0, "Expected some false negatives."

utils/metrics/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
__all__ = ["EntropyPrediction", "Recall"]
1+
__all__ = ["EntropyPrediction", "Recall", "F1Score"]
22

33
from .EntropyPred import EntropyPrediction
4+
from .F1 import F1Score
45
from .recall import Recall

utils/metrics/precision.py

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import torch
2+
import torch.nn as nn
3+
4+
USE_MEAN = True
5+
6+
# Precision = TP / (TP + FP)
7+
8+
9+
class Precision(nn.Module):
10+
"""Metric module for precision. Can calculate precision both as a mean of precisions or as brute function of true positives and false positives. This is for now controller with the USE_MEAN macro.
11+
12+
Parameters
13+
----------
14+
num_classes : int
15+
Number of classes in the dataset.
16+
"""
17+
18+
def __init__(self, num_classes):
19+
super().__init__()
20+
21+
self.num_classes = num_classes
22+
23+
def forward(self, y_true, y_pred):
24+
"""Calculates the precision score given number of classes and the true and predicted labels.
25+
26+
Parameters
27+
----------
28+
y_true : torch.tensor
29+
true labels
30+
y_pred : torch.tensor
31+
predicted labels
32+
33+
Returns
34+
-------
35+
torch.tensor
36+
precision score
37+
"""
38+
# One-hot encode the target tensor
39+
true_oh = torch.zeros(y_true.size(0), self.num_classes).scatter_(
40+
1, y_true.unsqueeze(1), 1
41+
)
42+
pred_oh = torch.zeros(y_pred.size(0), self.num_classes).scatter_(
43+
1, y_pred.unsqueeze(1), 1
44+
)
45+
46+
if USE_MEAN:
47+
tp = torch.sum(true_oh * pred_oh, 0)
48+
fp = torch.sum(~true_oh.bool() * pred_oh, 0)
49+
50+
else:
51+
tp = torch.sum(true_oh * pred_oh)
52+
fp = torch.sum(~true_oh[pred_oh.bool()].bool())
53+
54+
return torch.nanmean(tp / (tp + fp))
55+
56+
57+
def test_precision_case1():
58+
true_precision = 25.0 / 36 if USE_MEAN else 7.0 / 10
59+
60+
true1 = torch.tensor([0, 1, 2, 1, 0, 2, 1, 0, 2, 1])
61+
pred1 = torch.tensor([0, 2, 1, 1, 0, 2, 0, 0, 2, 1])
62+
P = Precision(3)
63+
precision1 = P(true1, pred1)
64+
assert precision1.allclose(torch.tensor(true_precision), atol=1e-5), (
65+
f"Precision Score: {precision1.item()}"
66+
)
67+
68+
69+
def test_precision_case2():
70+
true_precision = 8.0 / 15 if USE_MEAN else 6.0 / 15
71+
72+
true2 = torch.tensor([0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4])
73+
pred2 = torch.tensor([0, 0, 4, 3, 4, 0, 4, 4, 2, 3, 4, 1, 2, 4, 0])
74+
P = Precision(5)
75+
precision2 = P(true2, pred2)
76+
assert precision2.allclose(torch.tensor(true_precision), atol=1e-5), (
77+
f"Precision Score: {precision2.item()}"
78+
)
79+
80+
81+
def test_precision_case3():
82+
true_precision = 3.0 / 4 if USE_MEAN else 4.0 / 5
83+
84+
true3 = torch.tensor([0, 0, 0, 1, 0])
85+
pred3 = torch.tensor([1, 0, 0, 1, 0])
86+
P = Precision(2)
87+
precision3 = P(true3, pred3)
88+
assert precision3.allclose(torch.tensor(true_precision), atol=1e-5), (
89+
f"Precision Score: {precision3.item()}"
90+
)
91+
92+
93+
def test_for_zero_denominator():
94+
true_precision = 0.0
95+
true4 = torch.tensor([1, 1, 1, 1, 1])
96+
pred4 = torch.tensor([0, 0, 0, 0, 0])
97+
P = Precision(2)
98+
precision4 = P(true4, pred4)
99+
assert precision4.allclose(torch.tensor(true_precision), atol=1e-5), (
100+
f"Precision Score: {precision4.item()}"
101+
)
102+
103+
104+
if __name__ == "__main__":
105+
pass

utils/models/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
__all__ = ["MagnusModel", "ChristianModel"]
1+
__all__ = ["MagnusModel", "ChristianModel", "SolveigModel"]
22

33
from .christian_model import ChristianModel
44
from .magnus_model import MagnusModel
5+
from .solveig_model import SolveigModel

0 commit comments

Comments
 (0)