-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclassifier.go
209 lines (160 loc) · 4.06 KB
/
classifier.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
package mockingbird
import (
"bytes"
"encoding/gob"
"log"
"math"
"github.com/gonum/matrix/mat64"
)
type Prediction struct {
Label int
Language string
Score float64
}
type Classifier interface {
Fit()
Predict()
}
type NaiveBayes struct {
params nbParams
}
type nbParams struct {
TokensTotal int
LangsTotal int
LangsCount map[int]int
TokensTotalPerLang map[int]int
TokenCountPerLang map[int](map[int]int)
}
func NewNaiveBayes() *NaiveBayes {
return &NaiveBayes{}
}
func (nb *NaiveBayes) Fit(X, y *mat64.Dense) {
nSamples, nFeatures := X.Dims()
tokensTotal := 0
langsTotal, _ := y.Dims()
langsCount := histogram(y.Col(nil, 0))
tokensTotalPerLang := map[int]int{}
tokenCountPerLang := map[int](map[int]int){}
for i := 0; i < nSamples; i++ {
langIdx := int(y.At(i, 0))
for j := 0; j < nFeatures; j++ {
tokensTotal += int(X.At(i, j))
tokensTotalPerLang[langIdx] += int(X.At(i, j))
if _, ok := tokenCountPerLang[langIdx]; !ok {
tokenCountPerLang[langIdx] = map[int]int{}
}
tokenCountPerLang[langIdx][j] += int(X.At(i, j))
}
}
params := nbParams{
TokensTotal: tokensTotal,
LangsTotal: langsTotal,
LangsCount: langsCount,
TokensTotalPerLang: tokensTotalPerLang,
TokenCountPerLang: tokenCountPerLang,
}
nb.params = params
}
func (nb *NaiveBayes) GetParams() (
tokensTotal int,
langsTotal int,
langsCount map[int]int,
tokensTotalPerLang map[int]int,
tokenCountPerLang map[int](map[int]int)) {
tokensTotal = nb.params.TokensTotal
langsTotal = nb.params.LangsTotal
langsCount = nb.params.LangsCount
tokensTotalPerLang = nb.params.TokensTotalPerLang
tokenCountPerLang = nb.params.TokenCountPerLang
return
}
func (nb *NaiveBayes) ToGob() string {
var output bytes.Buffer
params := nb.params
enc := gob.NewEncoder(&output)
err := enc.Encode(params)
if err != nil {
log.Fatal("encode error:", err)
}
return output.String()
}
func NewNaiveBayesFromGob(gobStr string) *NaiveBayes {
var params nbParams
input := bytes.NewBufferString(gobStr)
dec := gob.NewDecoder(input)
err := dec.Decode(¶ms)
if err != nil {
log.Fatal(err)
}
nb := NewNaiveBayes()
nb.params = params
return nb
}
func (nb *NaiveBayes) Predict(X *mat64.Dense) []Prediction {
nSamples, _ := X.Dims()
prediction := []Prediction{}
for i := 0; i < nSamples; i++ {
scores := map[int]float64{}
for langIdx, _ := range nb.params.LangsCount {
scores[langIdx] = nb.tokensProba(X.Row(nil, i), langIdx) + nb.langProba(langIdx)
}
bestScore := scores[0]
bestLangIdx := 0
for langIdx, score := range scores {
if score > bestScore {
bestScore = score
bestLangIdx = langIdx
}
}
prediction = append(prediction, Prediction{
Label: bestLangIdx,
Language: "TODO: PENDING",
Score: bestScore,
})
}
return prediction
}
func (nb *NaiveBayes) tokensProba(dataArr []float64, langIdx int) float64 {
result := 0.0
for tokenIdx, nTokens := range dataArr {
// Equivalent to:
// for i = 0 to nTokens
// result += log(tokenProba(tokenIdx, langIdx))
result = result + math.Log(
math.Pow(nb.tokenProba(tokenIdx, langIdx), nTokens))
}
return result
}
func (nb *NaiveBayes) tokenProba(tokenIdx int, langIdx int) float64 {
tokenCount, ok := nb.params.TokenCountPerLang[langIdx][tokenIdx]
proba := 0.0
if tokenCount > 0 && ok {
proba = float64(tokenCount) / float64(nb.params.TokensTotalPerLang[langIdx])
} else {
proba = 1.0 / float64(nb.params.TokensTotal)
}
return proba
}
func (nb *NaiveBayes) langProba(langIdx int) float64 {
return math.Log(float64(nb.params.LangsCount[langIdx]) / float64(nb.params.LangsTotal))
}
func histogram(dataArr []float64) map[int]int {
results := map[int]int{}
for _, val := range dataArr {
results[int(val)] += 1
}
return results
}
func uniqVals(data_arr []float64) []float64 {
results := map[float64]bool{}
for _, val := range data_arr {
if _, ok := results[val]; !ok {
results[val] = true
}
}
uniqResults := []float64{}
for k := range results {
uniqResults = append(uniqResults, k)
}
return uniqResults
}