forked from zjunlp/DeepKE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics.py
62 lines (50 loc) · 1.67 KB
/
metrics.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
import torch
import numpy as np
from abc import ABCMeta, abstractmethod
from sklearn.metrics import precision_recall_fscore_support
class Metric(metaclass=ABCMeta):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def reset(self):
"""
Resets the metric to to it's initial state.
This is called at the start of each epoch.
"""
pass
@abstractmethod
def update(self, *args):
"""
Updates the metric's state using the passed batch output.
This is called once for each batch.
"""
pass
@abstractmethod
def compute(self):
"""
Computes the metric based on it's accumulated state.
This is called at the end of each epoch.
:return: the actual quantity of interest
"""
pass
class PRMetric():
def __init__(self):
"""
暂时调用 sklearn 的方法
"""
self.y_true = np.empty(0)
self.y_pred = np.empty(0)
def reset(self):
self.y_true = np.empty(0)
self.y_pred = np.empty(0)
def update(self, y_true: torch.Tensor, y_pred: torch.Tensor):
y_true = y_true.cpu().detach().numpy()
y_pred = y_pred.cpu().detach().numpy()
y_pred = np.argmax(y_pred, axis=-1)
self.y_true = np.append(self.y_true, y_true)
self.y_pred = np.append(self.y_pred, y_pred)
def compute(self):
p, r, f1, _ = precision_recall_fscore_support(self.y_true, self.y_pred, average='macro', warn_for=tuple())
_, _, acc, _ = precision_recall_fscore_support(self.y_true, self.y_pred, average='micro', warn_for=tuple())
return acc, p, r, f1