-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlogistic_regression.go
99 lines (75 loc) · 1.93 KB
/
logistic_regression.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
package mockingbird
import (
"github.com/gonum/matrix/mat64"
"github.com/lazywei/liblinear"
)
// type Prediction struct {
// Label int
// Language string
// Score float64
// }
type LogisticRegression struct {
model *liblinear.Model
}
func NewLogisticRegression() *LogisticRegression {
return &LogisticRegression{}
}
func NewLogisticRegressionFromModel(filepath string) *LogisticRegression {
model := liblinear.LoadModel(filepath)
return &LogisticRegression{model: model}
}
func (lr *LogisticRegression) Fit(X, y *mat64.Dense) {
model := liblinear.Train(X, y, 1, &liblinear.Parameter{
Eps: 0.01, C: 1, P: 0.1,
SolverType: liblinear.L2R_LR,
})
lr.model = model
}
func (lr *LogisticRegression) Predict(X *mat64.Dense) []Prediction {
nSamples, _ := X.Dims()
prediction := []Prediction{}
for i := 0; i < nSamples; i++ {
scores := liblinear.PredictProba(lr.model, X)
_, nClasses := scores.Dims()
bestScore := scores.At(i, 0)
bestLangIdx := 0
for langIdx := 0; langIdx < nClasses; langIdx++ {
score := scores.At(i, langIdx)
if score > bestScore {
bestScore = score
bestLangIdx = langIdx
}
}
prediction = append(prediction, Prediction{
Label: bestLangIdx,
Language: "TODO: PENDING",
Score: bestScore,
})
}
return prediction
}
func (lr *LogisticRegression) SaveModel(filepath string) {
liblinear.SaveModel(lr.model, filepath)
}
// 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
// }