-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathbayesian_test.go
357 lines (300 loc) · 10.6 KB
/
bayesian_test.go
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
package bayesian
import "testing"
import "fmt"
import "os"
const (
Good Class = "good"
Bad Class = "bad"
)
func Assert(t *testing.T, condition bool, args ...interface{}) {
if !condition {
t.Fatal(args)
}
}
func TestEmpty(t *testing.T) {
c := NewClassifier("Good", "Bad", "Neutral")
priors := c.getPriors()
for _, item := range priors {
Assert(t, item == 0)
}
}
func TestNoClasses(t *testing.T) {
defer func() {
if err := recover(); err != nil {
// we are good
}
}()
c := NewClassifier()
Assert(t, false, "should have panicked:", c)
}
func TestNotUnique(t *testing.T) {
defer func() {
if err := recover(); err != nil {
// we are good
}
}()
c := NewClassifier("Good", "Good", "Bad", "Cow")
Assert(t, false, "should have panicked:", c)
}
func TestOneClass(t *testing.T) {
defer func() {
if err := recover(); err != nil {
// we are good
}
}()
c := NewClassifier(Good)
Assert(t, false, "should have panicked:", c)
}
func TestObserve(t *testing.T) {
c := NewClassifier(Good, Bad)
c.Observe("tall", 2, Good)
c.Observe("handsome", 1, Good)
c.Observe("rich", 1, Good)
c.Observe("bald", 1, Bad)
c.Observe("poor", 2, Bad)
c.Observe("ugly", 1, Bad)
score, likely, strict := c.LogScores([]string{"the", "tall", "man"})
fmt.Printf("%v\n", score)
Assert(t, score[0] > score[1], "not good, round 1") // this is good
Assert(t, likely == 0, "not good, round 1")
Assert(t, strict == true, "not strict, round 1")
score, likely, strict = c.LogScores([]string{"poor", "ugly", "girl"})
fmt.Printf("%v\n", score)
Assert(t, score[0] < score[1]) // this is bad
Assert(t, likely == 1)
Assert(t, strict == true)
score, likely, strict = c.LogScores([]string{"the", "bad", "man"})
fmt.Printf("%v\n", score)
Assert(t, score[0] == score[1], "not the same") // same
Assert(t, likely == 0, "not good") // first one is picked
Assert(t, strict == false, "not strict")
}
func TestLearn(t *testing.T) {
c := NewClassifier(Good, Bad)
c.Learn([]string{"tall", "handsome", "rich"}, Good)
c.Learn([]string{"bald", "poor", "ugly"}, Bad)
score, likely, strict := c.LogScores([]string{"the", "tall", "man"})
fmt.Printf("%v\n", score)
Assert(t, score[0] > score[1], "not good, round 1") // this is good
Assert(t, likely == 0, "not good, round 1")
Assert(t, strict == true, "not strict, round 1")
score, likely, strict = c.LogScores([]string{"poor", "ugly", "girl"})
fmt.Printf("%v\n", score)
Assert(t, score[0] < score[1]) // this is bad
Assert(t, likely == 1)
Assert(t, strict == true)
score, likely, strict = c.LogScores([]string{"the", "bad", "man"})
fmt.Printf("%v\n", score)
Assert(t, score[0] == score[1], "not the same") // same
Assert(t, likely == 0, "not good") // first one is picked
Assert(t, strict == false, "not strict")
}
func TestProbScores(t *testing.T) {
c := NewClassifier(Good, Bad)
c.Learn([]string{"tall", "handsome", "rich"}, Good)
c.Learn([]string{"bald", "poor", "ugly"}, Bad)
score, likely, strict := c.ProbScores([]string{"the", "tall", "man"})
fmt.Printf("%v\n", score)
Assert(t, score[0] > score[1], "not good, round 1") // this is good
Assert(t, likely == 0, "not good, round 1")
Assert(t, strict == true, "not strict, round 1")
score, likely, strict = c.ProbScores([]string{"poor", "ugly", "girl"})
fmt.Printf("%v\n", score)
Assert(t, score[0] < score[1]) // this is bad
Assert(t, likely == 1)
Assert(t, strict == true)
score, likely, strict = c.ProbScores([]string{"the", "bad", "man"})
fmt.Printf("%v\n", score)
Assert(t, score[0] == score[1], "not the same") // same
Assert(t, likely == 0, "not good") // first one is picked
Assert(t, strict == false, "not strict")
}
func TestSeenLearned(t *testing.T) {
c := NewClassifier(Good, Bad)
c.Learn([]string{"tall", "handsome", "rich"}, Good)
c.Learn([]string{"bald", "poor", "ugly"}, Bad)
doc1 := []string{"hehe"}
doc2 := []string{}
doc3 := []string{"ayaya", "ppo", "lim", "inf"}
var scores []float64
scores, _, _ = c.LogScores(doc1)
scores, _, _ = c.LogScores(doc2)
scores, _, _ = c.LogScores(doc3)
scores, _, _ = c.ProbScores(doc1)
scores, _, _ = c.ProbScores(doc2)
scores, _, _ = c.ProbScores(doc3)
scores, _, _, _ = c.SafeProbScores(doc1)
scores, _, _, _ = c.SafeProbScores(doc2)
scores, _, _, _ = c.SafeProbScores(doc3)
println(scores)
Assert(t, c.Learned() == 2, "learned")
Assert(t, c.Seen() == 9, "seen")
count := c.WordCount()
Assert(t, count[0] == 3, "counted-good")
Assert(t, count[1] == 3, "counted-bad")
Assert(t, c.Learned() == 2, "learned")
}
func TestInduceUnderflow(t *testing.T) {
c := NewClassifier(Good, Bad) // knows no words
const docSize = 1000
document := make([]string, docSize)
for i := 0; i < docSize; i++ {
document[i] = "word"
}
// should induce overflow, because each word
// will have "defaultProb", which is small
scores, _, _, err := c.SafeProbScores(document)
Assert(t, err == ErrUnderflow, "Underflow error not detected")
println(scores)
}
func TestLogScores(t *testing.T) {
c := NewClassifier(Good, Bad)
c.Learn([]string{"tall", "handsome", "rich"}, Good)
data := c.datas[Good]
Assert(t, data.Total == 3)
Assert(t, data.getWordProb("tall") == float64(1)/float64(3), "tall")
Assert(t, data.getWordProb("rich") == float64(1)/float64(3), "rich")
Assert(t, c.WordCount()[0] == 3)
}
func TestGobs(t *testing.T) {
c := NewClassifier(Good, Bad)
c.Learn([]string{"tall", "handsome", "rich"}, Good)
err := c.WriteToFile("test.ser")
Assert(t, err == nil, "could not write:", err)
d, err := NewClassifierFromFile("test.ser")
Assert(t, err == nil, "could not read:", err)
fmt.Printf("%v\n", d)
scores, _, _ := d.LogScores([]string{"a", "b", "c"})
println(scores)
data := d.datas[Good]
Assert(t, data.Total == 3)
Assert(t, data.getWordProb("tall") == float64(1)/float64(3), "tall")
Assert(t, data.getWordProb("rich") == float64(1)/float64(3), "rich")
Assert(t, d.Learned() == 1)
count := d.WordCount()
Assert(t, count[0] == 3)
Assert(t, count[1] == 0)
Assert(t, d.Seen() == 1)
// remove the file
err = os.Remove("test.ser")
Assert(t, err == nil, "could not remove test file:", err)
}
func TestClassByFile(t *testing.T) {
c := NewClassifier(Good, Bad)
c.Learn([]string{"tall", "handsome", "rich"}, Good)
err := c.WriteClassesToFile(".")
Assert(t, err == nil, "could not write class:", err)
d := NewClassifier(Good, Bad)
err = d.ReadClassFromFile(Good, ".")
Assert(t, err == nil, "could not read:", err)
fmt.Printf("%v\n", d)
scores, _, _ := d.LogScores([]string{"a", "b", "c"})
println(scores)
data := d.datas[Good]
Assert(t, data.Total == 3)
Assert(t, data.getWordProb("tall") == float64(1)/float64(3), "tall")
Assert(t, data.getWordProb("rich") == float64(1)/float64(3), "rich")
Assert(t, d.Learned() == 1, "learned")
count := d.WordCount()
Assert(t, count[0] == 3)
Assert(t, count[1] == 0)
Assert(t, d.Seen() == 1)
// remove the file
err = os.Remove("good")
Assert(t, err == nil, "could not remove test file:", err)
err = os.Remove("bad")
Assert(t, err == nil, "could not remove test file:", err)
}
func TestFreqMatrixConstruction(t *testing.T) {
c := NewClassifier(Good, Bad)
freqs := c.WordFrequencies([]string{"a", "b"})
Assert(t, len(freqs) == 2, "size")
for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
Assert(t, freqs[i][j] == defaultProb, i, j)
}
}
}
func TestTfIdClassifier_SanityChecks(t *testing.T) {
c := NewClassifierTfIdf(Good, Bad)
Assert(t, c.IsTfIdf() == true)
c.Learn([]string{"tall", "handsome", "rich"}, Good)
defer func() {
if err := recover(); err != nil {
// we are good
}
}()
c.LogScores([]string{"a", "b", "c"})
Assert(t, false, "Should have panicked:Need to run ConvertTermsFreqToTfIdf() first..", c)
}
func TestTfIdClassifier_Tf_Checks(t *testing.T) {
c := NewClassifierTfIdf(Good, Bad)
Assert(t, c.IsTfIdf() == true)
c.Learn([]string{"tall", "handsome", "rich"}, Good)
c.Learn([]string{"tall", "blonde"}, Good)
c.Learn([]string{"tall"}, Good)
data := c.datas[Good]
// Total words seen in training.
Assert(t, data.Total == 6)
// Plain old counts for words.
Assert(t, data.Freqs["tall"] == 3)
Assert(t, data.Freqs["blonde"] == 1)
// Check for term frequency's per 'document' (tall)
Assert(t, data.FreqTfs["tall"][0] == float64(0.3333333333333333))
Assert(t, data.FreqTfs["tall"][1] == float64(0.5))
Assert(t, data.FreqTfs["tall"][2] == float64(1))
// Check for term frequency's per 'document' (blonde)
Assert(t, data.FreqTfs["blonde"][0] == float64(0.5))
}
func TestTfIdClassifier_ConvertToTfIdf(t *testing.T) {
c := NewClassifierTfIdf(Good, Bad)
Assert(t, c.IsTfIdf() == true)
c.Learn([]string{"tall", "handsome", "rich"}, Good)
c.Learn([]string{"tall", "blonde"}, Good)
c.Learn([]string{"tall"}, Good)
// Now we convert the TF's to Tf/Idf
// We can only this after we have learned all the documents and classes.
// We can add more learning afterwards but need to call ConvertToTfIdf() again before
// we can predict classes.
c.ConvertTermsFreqToTfIdf()
data := c.datas[Good]
// Tf-Idf after we have converted the tf's
Assert(t, data.Freqs["tall"] == float64(0.5620939930012151))
Assert(t, data.Freqs["blonde"] == float64(0.16440195389316542))
Assert(t, data.Freqs["notseen"] == float64(0))
Assert(t, data.FreqTfs["tall"][0] == float64(0.11664504260744213))
Assert(t, data.FreqTfs["tall"][1] == float64(0.16440195389316542))
Assert(t, data.FreqTfs["tall"][2] == float64(0.28104699650060755))
}
func TestTfIdClassifier_CheckForDoubleConvert(t *testing.T) {
c := NewClassifierTfIdf(Good, Bad)
Assert(t, c.IsTfIdf() == true)
c.Learn([]string{"tall", "handsome", "rich"}, Good)
c.Learn([]string{"tall", "blonde"}, Good)
c.Learn([]string{"tall"}, Good)
// We can only call ConverToTdfIdf once per learning cycle (cumulative counts).
c.ConvertTermsFreqToTfIdf()
defer func() {
if err := recover(); err != nil {
// we are good
}
}()
c.ConvertTermsFreqToTfIdf()
Assert(t, false, "Should have panicked:Can only run ConvertTermsFreqToTfIdf() once after a learning cycle.", c)
}
func TestTfIdClassifier_LogScore(t *testing.T) {
c := NewClassifierTfIdf(Good, Bad)
Assert(t, c.IsTfIdf() == true)
c.Learn([]string{"tall", "handsome", "rich"}, Good)
c.Learn([]string{"tall", "blonde"}, Good)
c.Learn([]string{"tall"}, Good)
c.Learn([]string{"fat"}, Bad)
c.Learn([]string{"short", "poor"}, Bad)
c.ConvertTermsFreqToTfIdf()
score, likely, strict := c.LogScores([]string{"the", "tall", "man"})
Assert(t, score[0] == float64(-53.028113582945196))
Assert(t, score[0] > score[1], "Class 'Good' should be closer to 0 than Class 'Bad' - both will be negative") // this is good
Assert(t, likely == 0, "Class should be 'Good'")
Assert(t, strict == true, "No tie's")
fmt.Printf("%#v", score)
}