-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathk_means_generating_clusters.go
80 lines (64 loc) · 1.38 KB
/
k_means_generating_clusters.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
package main
import (
"encoding/csv"
"fmt"
"github.com/mash/gokmeans"
"io"
"log"
"os"
"strconv"
)
func main() {
// Open the driver dataset file.
f, err := os.Open("fleet_data.csv")
if err != nil {
log.Fatal(err)
}
defer f.Close()
// Create a new CSV reader.
r := csv.NewReader(f)
r.FieldsPerRecord = 3
// Initialize a slice of gokmeans.Node's to
// hold our input data.
var data []gokmeans.Node
// Loop over the records creating our slice of
// gokmeans.Node's.
for {
// Read in our record and check for errors.
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
// Skip the header.
if record[0] == "Driver_ID" {
continue
}
// Initialize a point.
var point []float64
// Fill in our point.
for i := 1; i < 3; i++ {
// Parse the float value.
val, err := strconv.ParseFloat(record[i], 64)
if err != nil {
log.Fatal(err)
}
// Append this value to our point.
point = append(point, val)
}
// Append our point to the data.
data = append(data, gokmeans.Node{point[0], point[1]})
}
// Generate our clusters with k-means.
success, centroids := gokmeans.Train(data, 2, 50)
if !success {
log.Fatal("Could not generate clusters")
}
// Output the centroids to stdout.
fmt.Println("The centroids for our clusters are:")
for _, centroid := range centroids {
fmt.Println(centroid)
}
}