-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
VWTestHelper.cs
280 lines (234 loc) · 11.2 KB
/
VWTestHelper.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using Antlr4.Runtime;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Tree;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VW;
using VW.Serializer;
namespace cs_unittest
{
internal static class VWTestHelper
{
internal static void ParseInput(string text, IParseTreeListener listener)
{
ParseInput(new AntlrInputStream(text), listener);
}
internal static void ParseInput(Stream stream, IParseTreeListener listener)
{
ParseInput(new UnbufferedCharStream(stream), listener);
}
internal static void ParseInput(ICharStream stream, IParseTreeListener listener)
{
// optimized for memory consumption
var lexer = new VowpalWabbitLexer(stream)
{
TokenFactory = new CommonTokenFactory(copyText: true)
};
var tokens = new UnbufferedTokenStream(lexer);
var parser = new VowpalWabbitParser(tokens)
{
// Note; don't disable, as it is required to access the line
// BuildParseTree = false,
};
// fast than LL(*)
parser.Interpreter.PredictionMode = PredictionMode.Sll;
parser.AddParseListener(listener);
parser.AddErrorListener(new TestErrorListener());
parser.start();
}
internal static void Learn<T, TListener>(string args, string inputFile, string stderrFile)
where TListener : VowpalWabbitListenerToEvents<T>, new()
{
using (var vw = new VowpalWabbit<T>(args))
using (var validate = new VowpalWabbitExampleValidator<T>(args))
{
var listener = new TListener();
listener.Created = (line, data, label) =>
{
if (data == null)
{
Assert.Fail("got empty example");
}
validate.Validate(line, data, label);
vw.Learn(data, label);
};
VWTestHelper.ParseInput(File.OpenRead(inputFile), listener);
AssertEqual(stderrFile, vw.Native.PerformanceStatistics);
}
}
internal static void Predict<TData, TListener>(string args, string inputFile, string referenceFile = null)
where TData : BaseData
where TListener : VowpalWabbitListenerToEvents<TData>, new()
{
float[] references = null;
var index = 0;
if (referenceFile != null)
{
references = File.ReadAllLines(referenceFile)
.Select(l => float.Parse(l.Split(' ')[0], CultureInfo.InvariantCulture))
.ToArray();
}
using (var vwRef = new VowpalWabbit(args))
using (var vwModel = new VowpalWabbitModel(args))
using (var vwValidate = new VowpalWabbit(args))
using (var vwInMemoryShared2 = new VowpalWabbit<TData>(new VowpalWabbitSettings { Model = vwModel }))
using (var validate = new VowpalWabbitExampleValidator<TData>(args))
{
var listener = new TListener();
listener.Created = (line, x, label) =>
{
validate.Validate(line, x, label);
var expectedDynamic = vwRef.Predict(x.Line, VowpalWabbitPredictionType.Dynamic);
Assert.IsInstanceOfType(expectedDynamic, typeof(float));
var expected = vwRef.Predict(x.Line, VowpalWabbitPredictionType.Scalar);
var actual = vwInMemoryShared2.Predict(x, VowpalWabbitPredictionType.Scalar, label);
Assert.AreEqual((float)expectedDynamic, actual, 1e-5);
Assert.AreEqual(expected, actual, 1e-5);
if (references != null)
Assert.AreEqual(references[index++], actual, 1e-5);
};
}
}
internal static void AssertEqual(string expectedFile, VowpalWabbitPerformanceStatistics actual)
{
var expectedPerformanceStatistics = ReadPerformanceStatistics(expectedFile);
AssertEqual(expectedPerformanceStatistics, actual);
}
internal static void FuzzyEqual(double? expected, double actual, double epsilon, string message)
{
if (expected == null)
return;
// from test/RunTests
var delta = Math.Abs(expected.Value - actual);
if (delta > epsilon) {
// We have a 'big enough' difference, but this difference
// may still not be meaningful in all contexts:
// Big numbers should be compared by ratio rather than
// by difference
// Must ensure we can divide (avoid div-by-0)
if (Math.Abs(actual) <= 1.0) {
// If numbers are so small (close to zero),
// ($delta > $Epsilon) suffices for deciding that
// the numbers are meaningfully different
Assert.Fail(string.Format("{0} vs {1}: delta={2} > Epsilon={3}: {4}",
expected, actual, delta, epsilon, message));
}
// Now we can safely divide (since abs($word2) > 0)
// and determine the ratio difference from 1.0
var ratio_delta = Math.Abs(expected.Value / actual - 1.0);
if (ratio_delta > epsilon) {
Assert.Fail(string.Format("{0} vs {1}: delta={2} > Epsilon={3}: {4}",
expected, actual, delta, epsilon, message));
}
}
}
internal static void AssertEqual(VowpalWabbitPerformanceStatistics expected, VowpalWabbitPerformanceStatistics actual)
{
if (expected.TotalNumberOfFeatures != actual.TotalNumberOfFeatures)
{
Console.Error.WriteLine(
"Warning: total number of features differs. Expected: {0} vs. actual: {1}",
expected.TotalNumberOfFeatures,
actual.TotalNumberOfFeatures);
}
Assert.AreEqual(expected.NumberOfExamplesPerPass, actual.NumberOfExamplesPerPass, "NumberOfExamplesPerPass");
FuzzyEqual(expected.AverageLoss, actual.AverageLoss, 1e-3, "AverageLoss");
FuzzyEqual(expected.BestConstant, actual.BestConstant, 1e-3, "BestConstant");
// TODO: something weir'd is happening here. BestConstantsLoss is 0 if using RunAll
// has the proper value if just the unit test is run
//Console.WriteLine(expected.BestConstantLoss + " vs. " + actual.BestConstantLoss);
//Assert.AreEqual(expected.BestConstantLoss, actual.BestConstantLoss, 1e-5);
FuzzyEqual(expected.WeightedExampleSum, actual.WeightedExampleSum, 1e-3, "WeightedExampleSum");
FuzzyEqual(expected.WeightedLabelSum, actual.WeightedLabelSum, 1e-3, "WeightedLabelSum");
}
internal static void AssertEqual(VowpalWabbitStdErrPerformanceStatistics expected, VowpalWabbitPerformanceStatistics actual)
{
if (expected.TotalNumberOfFeatures != actual.TotalNumberOfFeatures)
{
Console.Error.WriteLine(
"Warning: total number of features differs. Expected: {0} vs. actual: {1}",
expected.TotalNumberOfFeatures,
actual.TotalNumberOfFeatures);
}
if (expected.NumberOfExamplesPerPass != null)
Assert.AreEqual(expected.NumberOfExamplesPerPass, actual.NumberOfExamplesPerPass, "NumberOfExamplesPerPass");
FuzzyEqual(expected.AverageLoss, actual.AverageLoss, 1e-3, "AverageLoss");
FuzzyEqual(expected.BestConstant, actual.BestConstant, 1e-3, "BestConstant");
// TODO: something weir'd is happening here. BestConstantsLoss is 0 if using RunAll
// has the proper value if just the unit test is run
//Console.WriteLine(expected.BestConstantLoss + " vs. " + actual.BestConstantLoss);
//Assert.AreEqual(expected.BestConstantLoss, actual.BestConstantLoss, 1e-5);
FuzzyEqual(expected.WeightedExampleSum, actual.WeightedExampleSum, 1e-3, "WeightedExampleSum");
FuzzyEqual(expected.WeightedLabelSum, actual.WeightedLabelSum, 1e-3, "WeightedLabelSum");
}
internal static VowpalWabbitStdErrPerformanceStatistics ReadPerformanceStatistics(string filename)
{
var lines = File.ReadAllLines(filename);
var numExamples = FindULongEntry(lines, "number of examples per pass = ");
if (numExamples == 0)
numExamples = FindULongEntry(lines, "number of examples = ");
var stats = new VowpalWabbitStdErrPerformanceStatistics()
{
NumberOfExamplesPerPass = numExamples,
TotalNumberOfFeatures = FindULongEntry(lines, "total feature number = "),
AverageLoss = FindAverageLossEntry(lines),
BestConstant = FindDoubleEntry(lines, "best constant = "),
BestConstantLoss = FindDoubleEntry(lines, "best constant's loss = "),
WeightedExampleSum = FindDoubleEntry(lines, "weighted example sum = "),
WeightedLabelSum = FindDoubleEntry(lines, "weighted label sum = ")
};
return stats;
}
private static double? FindAverageLossEntry(string[] lines)
{
var label = "average loss = ";
var candidate = lines.FirstOrDefault(l => l.StartsWith(label));
if (candidate == null)
{
return null;
}
candidate = candidate.Substring(label.Length);
if (candidate.EndsWith(" h"))
{
candidate = candidate.Substring(0, candidate.Length - 2);
}
var ret = 0.0;
if (double.TryParse(candidate, NumberStyles.Float, CultureInfo.InvariantCulture, out ret))
{
return ret;
}
return null;
}
private static double? FindDoubleEntry(string[] lines, string label)
{
var candidate = lines.FirstOrDefault(l => l.StartsWith(label));
if (candidate == null)
{
return null;
}
var ret = 0.0;
if (double.TryParse(candidate.Substring(label.Length), NumberStyles.Float, CultureInfo.InvariantCulture, out ret))
{
return ret;
}
return null;
}
private static ulong? FindULongEntry(string[] lines, string label)
{
var candidate = lines.FirstOrDefault(l => l.StartsWith(label));
if (candidate == null)
{
return null;
}
ulong ret = 0L;
if (ulong.TryParse(candidate.Substring(label.Length), NumberStyles.Float, CultureInfo.InvariantCulture, out ret))
{
return ret;
}
return null;
}
}
}