Skip to content

Commit a582fc4

Browse files
authored
Add metrics for time series classification
1 parent cd16eb2 commit a582fc4

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

basicts/metrics/cls_metrics.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import torch
2+
3+
4+
def accuracy(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
5+
"""
6+
Calculate the accuracy of predictions.
7+
8+
Args:
9+
pred (torch.Tensor): The predicted values as a tensor.
10+
target (torch.Tensor): The ground truth values as a tensor with the same shape as `pred`.
11+
12+
Returns:
13+
torch.Tensor: A scalar tensor representing the accuracy.
14+
"""
15+
return (pred == target).float().mean()
16+
17+
def precision(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
18+
"""
19+
Calculate the precision of predictions.
20+
21+
Args:
22+
pred (torch.Tensor): The predicted values as a tensor.
23+
target (torch.Tensor): The ground truth values as a tensor with the same shape as `pred`.
24+
25+
Returns:
26+
torch.Tensor: A scalar tensor representing the precision.
27+
"""
28+
true_positives = (pred == target).float().sum()
29+
false_positives = (pred != target).float().sum()
30+
return true_positives / (true_positives + false_positives)
31+
32+
def recall(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
33+
"""
34+
Calculate the recall of predictions.
35+
36+
Args:
37+
pred (torch.Tensor): The predicted values as a tensor.
38+
target (torch.Tensor): The ground truth values as a tensor with the same shape as `pred`.
39+
40+
Returns:
41+
torch.Tensor: A scalar tensor representing the recall.
42+
"""
43+
true_positives = (pred == target).float().sum()
44+
false_negatives = (pred != target).float().sum()
45+
return true_positives / (true_positives + false_negatives)
46+
47+
def f1_score(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
48+
"""
49+
Calculate the F1 score of predictions.
50+
51+
Args:
52+
pred (torch.Tensor): The predicted values as a tensor.
53+
target (torch.Tensor): The ground truth values as a tensor with the same shape as `pred`.
54+
55+
Returns:
56+
torch.Tensor: A scalar tensor representing the F1 score.
57+
"""
58+
precision_item = precision(pred, target)
59+
recall_item = recall(pred, target)
60+
return 2 * (precision_item * recall_item) / (precision_item + recall_item)

0 commit comments

Comments
 (0)