-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathkMeans.jl
223 lines (180 loc) · 5.5 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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#Partition a dataset into K clusters.
#Finds clusters by repeatedly assigning each data point to the cluster with
#the nearest centroid and iterating until the assignments converge (meaning
#they don't change during an iteration) or the maximum number of iterations
#is reached.
#Parameters
#----------
#K : int
# The number of clusters into which the dataset is partitioned.
#max_iters: int
# The maximum iterations of assigning points to the nearest cluster.
# Short-circuited by the assignments converging on their own.
#init: str, default 'random'
# The name of the method used to initialize the first clustering.
#
# 'random' - Randomly select values from the dataset as the K centroids.
# '++' - Select a random first centroid from the dataset, then select
# K - 1 more centroids by choosing values from the dataset with a
# probability distribution proportional to the squared distance
# from each point's closest existing cluster. Attempts to create
# larger distances between initial clusters to improve convergence
# rates and avoid degenerate cases.
type Kmeans
clusters::Dict{Integer,Matrix}
clu_ind::Dict{Integer,Vector}
k::Integer
X::Matrix
max_iter::Integer
centroid::Matrix
init::String
end
function Kmeans(;
clusters::Dict{Integer,Matrix} = Dict{Integer,Matrix}(),
k::Integer = 2,
X::Matrix = zeros(2,2),
max_iter::Integer = 150,
centroid::Matrix = zeros(2,2),
init::String = "++",
clu_ind::Dict{Integer,Vector} = Dict{Integer,Vector}())
return Kmeans(clusters, clu_ind, k, X, max_iter, centroid , init)
end
function train!(model::Kmeans, X::Matrix)
model.X = X
end
function predict!(model::Kmeans)
initialize_centroid(model)
for i in 1:model.max_iter
centroid_old = copy(model.centroid)
assign_clusters!(model)
update_centroid!(model)
if is_converged(centroid_old, model.centroid)
break
end
end
end
function update_centroid!(model)
for i = 1:model.k
if !haskey(model.clusters, i)
r = 0
for i = 1:model.k
if haskey(model.clusters, i)
r = i
end
end
model.clusters[i] = model.clusters[r]
end
model.centroid[i,:] = mean(model.clusters[i],1)
end
end
function assign_clusters!(model::Kmeans)
n = size(model.X,1)
model.clusters = Dict{Integer,Matrix}()
model.clu_ind = Dict{Integer,Vector}()
for i = 1:n
dist = zeros(model.k)
for j = 1:length(dist)
dist[j] = norm(model.centroid[j,:]-model.X[i,:])
end
clu = indmin(dist)
if haskey(model.clusters,clu)
model.clusters[clu] = vcat(model.clusters[clu], model.X[i,:]')
model.clu_ind[clu] = vcat(model.clu_ind[clu], i)
else
model.clusters[clu] = model.X[i,:]'
model.clu_ind[clu] = [i]
end
end
end
function initialize_centroid(model::Kmeans)
model.centroid = zeros(model.k, size(model.X,2))
if model.init == "random"
model.centroid = model.X[randperm(size(model.X,1))[1:model.k],:]
elseif model.init == "++"
model.centroid[1,:] = model.X[rand(1:size(model.X,1)),:]
for i = 2:model.k
model.centroid[i,:] = find_next_centroid(model,i-1)
end
else
error("you must provide a initial type")
end
end
function find_next_centroid(model, num)
mean_cent = vec(mean(model.centroid[1:num,:],1))
n_sample = size(model.X,1)
res = zeros(n_sample)
for i = 1:n_sample
res[i] = norm(model.X[i,:]-mean_cent)
end
prob = res/sum(res)
cum = cumsum(prob, 1)
r = rand()
x_sel = model.X[cum .> r,:]
x_sel = x_sel[1,:]
return x_sel
end
function is_converged(x::Matrix,
y::Matrix)
return norm(x-y) == 0
end
function plot_in_2d(model::Kmeans)
y_ = []
for i = 1:model.k
push!(y_,model.clu_ind[i])
end
y_ = reduce(vcat,y_)
len = size(model.X, 2)
x_ = zeros(size(y_,1),len)
for i = 1:size(x_,1)
x_[i,:] = model.X[y_[i],:]
end
# if not 2d perform PCA
#PCA
if size(x_, 2) > 2
pca_model = PCA()
train!(pca_model, x_)
x_ = transform(pca_model, x_)
x_ = x_[:, 1:2]
end
x_sep = x_[:,1]
y_sep = x_[:,2]
num_ = zeros(model.k)
for i = 1:model.k
num_[i] = size(model.clusters[i],1)
end
num_ = convert(Array{Int,1},num_)
rep = zeros(sum(num_))
for i = 1:model.k
for j = 1:num_[i]
j = convert(Int,j)
if i == 1
rep[j] = i
else
kk = i-1
rep[sum(num_[1:kk])+j] = i
end
end
end
df = DataFrame(x = x_sep,y = y_sep , cluster = rep)
println("Computing finished")
println("Drawing the plot.....Please Wait(Actually Gadfly is quite slow in drawing the first plot)")
Gadfly.plot(df, x = "x", y = "y", color = "cluster",Geom.point)
end
function test_kmeans_speed()
X, y = make_blo()
clu = length(unique(y))
@show clu
model = Kmeans(k=clu)
train!(model,X)
predict!(model)
plot_in_2d(model)
end
function test_kmeans_random()
X, y = make_blo()
clu = length(unique(y))
@show clu
model = Kmeans(k=clu,init="random")
train!(model,X)
predict!(model)
plot_in_2d(model)
end