-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
90 lines (71 loc) · 1.77 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
package main
import (
"encoding/csv"
"flag"
"fmt"
"os"
"github.com/nfisher/dtgo/data"
"github.com/nfisher/dtgo/decisiontree"
)
func Exec(inputFile string) {
rows, err := readCSV(inputFile)
if err != nil {
fmt.Println("Unable to read CSV:", err.Error())
return
}
d := data.New(rows[0], 0.20)
err = data.Coerce(rows, d)
if err != nil {
fmt.Println("Unable to coerce CSV:", err.Error())
return
}
decisionTree(d)
}
func decisionTree(d *data.TrainingAppender) {
training, testData := d.Data()
tree := decisiontree.Train(training, d.Header())
decisiontree.Print(tree, "")
fmt.Println("========================================================================")
fmt.Println("training size:", len(training), "test size:", len(testData))
for _, td := range testData {
actual := td[len(td)-1]
prediction := decisiontree.PredictionMap(decisiontree.Classify(td, tree).Predictions)
keys := make([]string, 0, len(prediction))
if len(prediction) > 1 {
fmt.Printf("Actual: %s, Predicted: %s, From: %v\n", actual, prediction, td)
continue
}
for k := range prediction {
keys = append(keys, k)
}
predicted := keys[0]
if actual != predicted {
fmt.Printf("Actual: %s, Predicted: %s, From: %v\n", actual, keys[0], td)
continue
}
fmt.Println("Predicted:", actual)
}
}
func readCSV(inputFile string) ([][]string, error) {
r, err := os.Open(inputFile)
if err != nil {
return nil, err
}
defer r.Close()
rows, err := csv.NewReader(r).ReadAll()
if err != nil {
return nil, err
}
return rows, nil
}
func main() {
var inputFile string
flag.StringVar(&inputFile, "input", "", "input csv file for training")
flag.Parse()
if inputFile == "" {
fmt.Println("An input filename must be provided.")
flag.Usage()
return
}
Exec(inputFile)
}