forked from JuliaStats/Clustering.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmeans.jl
56 lines (46 loc) · 1.34 KB
/
kmeans.jl
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
# simple program to test the new k-means (not ready yet)
using Base.Test
using Clustering
srand(34568)
m = 3
n = 1000
k = 10
x = rand(m, n)
# non-weighted
r = kmeans(x, k; maxiter=50)
@test isa(r, KmeansResult{Float64})
@test size(r.centers) == (m, k)
@test length(r.assignments) == n
@test all(r.assignments .>= 1) && all(r.assignments .<= k)
@test length(r.costs) == n
@test length(r.counts) == k
@test sum(r.counts) == n
@test r.cweights == @compat(map(Float64, r.counts))
@test_approx_eq sum(r.costs) r.totalcost
# non-weighted (float32)
r = kmeans(@compat(map(Float32, x)), k; maxiter=50)
@test isa(r, KmeansResult{Float32})
@test size(r.centers) == (m, k)
@test length(r.assignments) == n
@test all(r.assignments .>= 1) && all(r.assignments .<= k)
@test length(r.costs) == n
@test length(r.counts) == k
@test sum(r.counts) == n
@test r.cweights == @compat(map(Float64, r.counts))
@test_approx_eq sum(r.costs) r.totalcost
# weighted
w = rand(n)
r = kmeans(x, k; maxiter=50, weights=w)
@test isa(r, KmeansResult{Float64})
@test size(r.centers) == (m, k)
@test length(r.assignments) == n
@test all(r.assignments .>= 1) && all(r.assignments .<= k)
@test length(r.costs) == n
@test length(r.counts) == k
@test sum(r.counts) == n
cw = zeros(k)
for i = 1:n
cw[r.assignments[i]] += w[i]
end
@test_approx_eq r.cweights cw
@test_approx_eq dot(r.costs, w) r.totalcost