forked from muesli/kmeans
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kmeans_test.go
104 lines (89 loc) · 2.17 KB
/
kmeans_test.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
102
103
104
package kmeans
import (
"math/rand"
"testing"
"github.com/tushar-zomato/clusters"
)
const (
randomSeed = int64(42)
)
func TestNewErrors(t *testing.T) {
_, err := NewWithOptions(0.00, false)
if err == nil {
t.Errorf("Expected invalid options to return an error, got nil")
}
_, err = NewWithOptions(1.00, false)
if err == nil {
t.Errorf("Expected invalid options to return an error, got nil")
}
}
func TestPartitioningError(t *testing.T) {
km := New()
d := clusters.Observations{}
if _, err := km.Partition(d, 1); err == nil {
t.Errorf("Expected error partitioning with empty data set, got nil")
return
}
d = clusters.Observations{
clusters.NewObservation(
clusters.Coordinates{
0.1,
0.1,
},
1,
),
}
if _, err := km.Partition(d, 0); err == nil {
t.Errorf("Expected error partitioning with 0 clusters, got nil")
return
}
if _, err := km.Partition(d, 2); err == nil {
t.Errorf("Expected error partitioning with more clusters than data points, got nil")
return
}
}
func TestDimensions(t *testing.T) {
var d clusters.Observations
for x := 0; x < 255; x += 32 {
for y := 0; y < 255; y += 32 {
d = append(d, clusters.NewObservation(
clusters.Coordinates{
float64(x) / 255.0,
float64(y) / 255.0,
},
1,
))
}
}
k := 4
km := New()
clusters, err := km.Partition(d, k)
if err != nil {
t.Errorf("Unexpected error partitioning: %v", err)
return
}
if len(clusters) != k {
t.Errorf("Expected %d clusters, got: %d", k, len(clusters))
}
}
func benchmarkPartition(size, partitions int, b *testing.B) {
rand.Seed(randomSeed)
var d clusters.Observations
for i := 0; i < size; i++ {
d = append(d, clusters.NewObservation(
clusters.Coordinates{
rand.Float64(),
rand.Float64(),
},
1,
))
}
for j := 0; j < b.N; j++ {
km := New()
km.Partition(d, partitions)
}
}
func BenchmarkPartition32Points(b *testing.B) { benchmarkPartition(32, 16, b) }
func BenchmarkPartition512Points(b *testing.B) { benchmarkPartition(512, 16, b) }
func BenchmarkPartition4096Points(b *testing.B) { benchmarkPartition(4096, 16, b) }
func BenchmarkPartition65536Points(b *testing.B) { benchmarkPartition(65536, 16, b) }