/
main.go
101 lines (88 loc) · 3.04 KB
/
main.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
// 贝叶斯分类器(Naive Bayesian classifier)支持中文文档解析训练和分类,提供HTTP API访问。
package main
import (
"fmt"
"time"
"github.com/safeie/bayesian-classifier/classifier"
)
const (
DefaultProb = 0.5 // 默认概率
DefaultWeight = 1.0 // 默认概率的权重,假定与一个单词相当
Debug = true // 开启调试
HTTP = true // 开启HTTP服务
HTTPPort = ":8812" // HTTP端口
Storage = "file" // 存储引擎,接受 file,redis,目前只支持file
StoragePath = "storage.data" // 文件存储引擎的存储路径
StorageFrequency = "10" // 自动存储的频率, 单位: 秒,0 表示不自动存储
)
func main() {
// 分类器
handler := classifier.NewClassifier(map[string]interface{}{
"defaultProb": DefaultProb,
"defaultWeight": DefaultWeight,
"debug": Debug,
"http": HTTP,
"httpPort": HTTPPort,
"storage": map[string]string{
"adapter": Storage,
"path": StoragePath,
"frequency": StorageFrequency,
},
})
// 训练
handler.Training("这是一篇WEB开发的内容", "WEB")
handler.Training("这是一篇Javascript的技巧", "WEB")
handler.Training("这是一篇养生的内容", "WEB")
handler.Training("这是一篇养生的内容2", "健康")
handler.Training("这是一篇冬天养生食谱", "健康")
handler.Training("坚持做运动就可以减肥", "测试")
// 从txt文件进行训练
classifier.FileTrain("./data", handler)
// 获取训练数据
testWord(handler, "养生", "WEB") // 测试已知分类
testWord(handler, "养生", "XX") // 测试未知分类
testWord(handler, "养生", "") // 查看所有分类
testWord(handler, "不认识", "") // 测试未知单词
testWord(handler, "服务器", "") // 测试未知单词
// 分类测试
testDoc(handler, "养生是什么分类")
testDoc(handler, "API Go")
testDoc(handler, "服务器")
// 暂停
time.Sleep(time.Second * 15)
// 开启了HTTP服务,不能结束进程
if HTTP {
for {
time.Sleep(time.Second)
}
}
}
// 辅助测试:测试单词的频率
func testWord(classifier *classifier.Classifier, word, category string) {
score := classifier.Score(word, category)
if category != "" {
fmt.Printf("单词【%s】在分类【%s】中出现的概率为: \n", word, category)
} else {
fmt.Printf("单词【%s】在分类中出现的概率为: \n", word)
}
printScore(score)
}
// 辅助测试:测试文档的分类
func testDoc(classifier *classifier.Classifier, doc string) {
score := classifier.Categorize(doc)
fmt.Printf("测试文档归类于以下分类的概率为: \n")
fmt.Println("--------------------------")
fmt.Println(doc)
fmt.Println("--------------------------")
printScore(score)
}
// 辅助测试:输出
func printScore(scores []*classifier.ScoreItem) {
if len(scores) == 0 {
fmt.Println("未知单词 Orz!")
}
for k := range scores {
fmt.Println(scores[k].Category, "\t", scores[k].Score)
}
fmt.Println(".")
}