-
Notifications
You must be signed in to change notification settings - Fork 2
/
Meter.cs
115 lines (95 loc) · 3.07 KB
/
Meter.cs
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System.IO;
using Predictions = System.Collections.Generic.List<System.Tuple<float, int>>;
namespace FastText
{
public class Meter
{
struct Metrics
{
public long gold;
public long predicted;
public long predictedGold;
public double Precision()
{
if (predicted == 0)
{
return double.NaN;
}
return predictedGold / (double)predicted;
}
public double Recall()
{
if (gold == 0)
{
return double.NaN;
}
return predictedGold / (double)gold;
}
public double F1Score()
{
if (predicted + gold == 0)
{
return double.NaN;
}
return 2 * predictedGold / (double)(predicted + gold);
}
}
private Metrics metrics_ = new Metrics();
private long nexamples_;
private System.Collections.Generic.Dictionary<int, Metrics> labelMetrics_ = new System.Collections.Generic.Dictionary<int, Metrics>();
public long nexamples => nexamples_;
public void Log(int[] labels, Predictions predictions)
{
nexamples_++;
metrics_.gold += labels.Length;
metrics_.predicted += predictions.Count;
for (int i = 0; i < predictions.Count; i++)
{
var prediction = predictions[i];
var metrics = labelMetrics_[prediction.Item2];
metrics.predicted++;
labelMetrics_[prediction.Item2] = metrics;
if (Utils.Contains(labels, prediction.Item2))
{
metrics = labelMetrics_[prediction.Item2];
metrics.predictedGold++;
labelMetrics_[prediction.Item2] = metrics;
metrics_.predictedGold++;
}
}
for (int i = 0; i < labels.Length; i++)
{
var label = labels[i];
var metrics = labelMetrics_[label];
metrics.gold++;
labelMetrics_[label] = metrics;
}
}
public double Precision(int i)
{
return labelMetrics_[i].Precision();
}
public double Recall(int i)
{
return labelMetrics_[i].Recall();
}
public double F1Score(int i)
{
return labelMetrics_[i].F1Score();
}
public double Precision()
{
return metrics_.Precision();
}
public double Recall()
{
return metrics_.Recall();
}
public void WriteGeneralMetrics(TextWriter writer, int k)
{
writer.WriteLine($"N\t{nexamples_}");
writer.WriteLine($"P@{k}\t{metrics_.Precision():0.###}");
writer.WriteLine($"R@{k}\t{metrics_.Recall():0.###}");
}
}
}