-
Notifications
You must be signed in to change notification settings - Fork 9
/
encoding.go
66 lines (49 loc) · 1.12 KB
/
encoding.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
package multibayes
import (
"encoding/json"
"io/ioutil"
)
type jsonableClassifier struct {
Matrix *sparseMatrix `json:"matrix"`
}
func (c *Classifier) MarshalJSON() ([]byte, error) {
return json.Marshal(&jsonableClassifier{c.Matrix})
}
func (c *Classifier) UnmarshalJSON(buf []byte) error {
j := jsonableClassifier{}
err := json.Unmarshal(buf, &j)
if err != nil {
return nil
}
*c = *NewClassifier()
c.Matrix = j.Matrix
return nil
}
// Initialize a new classifier from a JSON byte slice.
func NewClassifierFromJSON(buf []byte) (*Classifier, error) {
classifier := &Classifier{}
err := classifier.UnmarshalJSON(buf)
if err != nil {
return nil, err
}
return classifier, nil
}
func LoadClassifierFromFile(filename string) (*Classifier, error) {
buf, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return NewClassifierFromJSON(buf)
}
func (s *sparseColumn) MarshalJSON() ([]byte, error) {
return json.Marshal(s.Data)
}
func (s *sparseColumn) UnmarshalJSON(buf []byte) error {
var data []int
err := json.Unmarshal(buf, &data)
if err != nil {
return err
}
s.Data = data
return nil
}