forked from eaigner/shield
-
Notifications
You must be signed in to change notification settings - Fork 1
/
shield.go
212 lines (184 loc) · 4.4 KB
/
shield.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
package shield
import (
"log"
"math"
)
const defaultProb float64 = 1e-11
type shield struct {
tokenizer Tokenizer
store Store
}
func New(t Tokenizer, s Store) Shield {
return &shield{
tokenizer: t,
store: s,
}
}
func (sh *shield) Learn(class, text string) (err error) {
return sh.increment(class, text, 1)
}
func (sh *shield) BulkLearn(sets []Set) (err error) {
return sh.bulkIncrement(sets, 1)
}
func (sh *shield) Forget(class, text string) (err error) {
return sh.increment(class, text, -1)
}
func (sh *shield) increment(class, text string, sign int64) (err error) {
if len(class) == 0 {
panic("invalid class")
}
if len(text) == 0 {
panic("invalid text")
}
return sh.bulkIncrement([]Set{Set{Class: class, Text: text}}, sign)
}
func (sh *shield) bulkIncrement(sets []Set, sign int64) (err error) {
if len(sets) == 0 {
panic("invalid data set")
}
m := make(map[string]map[string]int64)
for _, set := range sets {
tokens := sh.tokenizer.Tokenize(set.Text)
for k, _ := range tokens {
tokens[k] *= sign
}
if w, ok := m[set.Class]; ok {
for word, count := range tokens {
w[word] += count
}
} else {
m[set.Class] = tokens
}
}
for class, words := range m {
// Sitnan patch: Do not consider words if count is less than 2
for word, d := range words {
if d < 2 {
delete(m[class], word)
}
}
if err = sh.store.AddClass(class); err != nil {
log.Println(err)
return
}
}
log.Println("Total word with freq sent to Redis is: ", len(m))
return sh.store.IncrementClassWordCounts(m)
}
func getKeys(m map[string]int64) []string {
keys := make([]string, 0, len(m))
for k, _ := range m {
keys = append(keys, k)
}
return keys
}
func (s *shield) Score(text string) (scores map[string]float64, err error) {
// Tokenize text
wordFreqs := s.tokenizer.Tokenize(text)
if len(wordFreqs) < 2 {
return
}
words := getKeys(wordFreqs)
// Get total class word counts
totals, err := s.store.TotalClassWordCounts()
if err != nil {
return
}
classes := getKeys(totals)
// Get word frequencies for each class
classFreqs := make(map[string]map[string]int64)
for _, class := range classes {
freqs, err2 := s.store.ClassWordCounts(class, words)
if err2 != nil {
err = err2
return
}
classFreqs[class] = freqs
}
/*
// Calculate log scores for each class
logScores := make(map[string]float64, len(classes))
for _, class := range classes {
freqs := classFreqs[class]
total := totals[class]
// Because this classifier is not biased, we don't use prior probabilities
score := float64(0)
for _, word := range words {
// Compute the probability that this word belongs to that class
wordProb := float64(freqs[word]) / float64(total)
if wordProb == 0 {
wordProb = defaultProb
}
score += math.Log(wordProb)
}
logScores[class] = score
}
*/
/*****************************************************/
//** SITNAN modification to handle zero prob **/
// Calculate log scores for each class
logScores := make(map[string]float64, len(classes))
hasData := false
for _, class := range classes {
freqs := classFreqs[class]
total := totals[class]
// Because this classifier is not biased, we don't use prior probabilities
score := float64(0)
for _, word := range words {
// Compute the probability that this word belongs to that class
wordProb := float64(freqs[word]) / float64(total)
if wordProb == 0 {
wordProb = defaultProb
} else {
hasData = true
}
score += math.Log(wordProb)
}
logScores[class] = score
}
scores = make(map[string]float64, len(classes))
if !hasData {
scores["unknown"] = 1
return
}
/*****************************************************/
// Normalize the scores
var min = math.MaxFloat64
var max = -math.MaxFloat64
for _, score := range logScores {
if score > max {
max = score
}
if score < min {
min = score
}
}
r := max - min
scores = make(map[string]float64, len(classes))
for class, score := range logScores {
if r == 0 {
scores[class] = 1
} else {
scores[class] = (score - min) / r
}
}
return
}
func (s *shield) Classify(text string) (class string, err error) {
scores, err := s.Score(text)
if err != nil {
//log.Println(err)
return
}
// Select class with highes prob
var score float64
for k, v := range scores {
if v > score {
class, score = k, v
}
}
return
}
func (sh *shield) Reset() error {
return sh.store.Reset()
}