-
Notifications
You must be signed in to change notification settings - Fork 14
/
Clustering_hard.jl
426 lines (369 loc) · 15.4 KB
/
Clustering_hard.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
"""
initRepresentatives(X,K;initStrategy,Z₀)
Initialisate the representatives for a K-Mean or K-Medoids algorithm
# Parameters:
* `X`: a (N x D) data to clusterise
* `K`: Number of cluster wonted
* `initStrategy`: Whether to select the initial representative vectors:
* `random`: randomly in the X space
* `grid`: using a grid approach [default]
* `shuffle`: selecting randomly within the available points
* `given`: using a provided set of initial representatives provided in the `Z₀` parameter
* `Z₀`: Provided (K x D) matrix of initial representatives (used only together with the `given` initStrategy) [default: `nothing`]
* `rng`: Random Number Generator (see [`FIXEDSEED`](@ref)) [deafult: `Random.GLOBAL_RNG`]
# Returns:
* A (K x D) matrix of initial representatives
# Example:
```julia
julia> Z₀ = initRepresentatives([1 10.5;1.5 10.8; 1.8 8; 1.7 15; 3.2 40; 3.6 32; 3.6 38],2,initStrategy="given",Z₀=[1.7 15; 3.6 40])
```
"""
function initRepresentatives(X,K;initStrategy="grid",Z₀=nothing,rng = Random.GLOBAL_RNG)
X = makeMatrix(X)
(N,D) = size(X)
# Random choice of initial representative vectors (any point, not just in X!)
minX = minimum(X,dims=1)
maxX = maximum(X,dims=1)
Z = zeros(K,D)
if initStrategy == "random"
for i in 1:K
for j in 1:D
Z[i,j] = rand(rng,Distributions.Uniform(minX[j],maxX[j]))
end
end
elseif initStrategy == "grid"
for d in 1:D
# same "space" for each class on each dimension
Z[:,d] = collect(range(minX[d] + (maxX[d]-minX[d])/(K*2) , stop=maxX[d] - (maxX[d]-minX[d])/(K*2) , length=K))
#ex: collect(range(minX[d], stop=maxX[d], length=K))
#collect(range(s+(e-s)/(K*2), stop=e-(e-s)/(K*2), length=K))
end
elseif initStrategy == "given"
if isnothing(Z₀) error("With the `given` strategy you need to provide the initial set of representatives in the Z₀ parameter.") end
Z₀ = makeMatrix(Z₀)
Z = Z₀
elseif initStrategy == "shuffle"
zIdx = shuffle(rng,1:size(X)[1])[1:K]
Z = X[zIdx, :]
else
error("initStrategy \"$initStrategy\" not implemented")
end
return Z
end
function classAssignation(X,Z,dist)
cIdx = zeros(Int64,size(X,1))
for (i,x) in enumerate(eachrow(X))
cost = Inf
for (k,z) in enumerate(eachrow(Z))
if (dist(x,z) < cost)
cost = dist(x,z)
cIdx[i] = k
end
end
end
return cIdx
end
function updateKMeansRepresentatives!(Z,X,cIdx)
K,D = size(Z)
for j in 1:K
Cⱼ = X[cIdx .== j,:] # Selecting the constituency by boolean selection
if size(Cⱼ)[1] > 0
Z[j,:] = sum(Cⱼ,dims=1) ./ size(Cⱼ)[1]
else
# move toward the center if no costituency
xAvg = mean(X,dims=1)'
Z[j,:] = Z[j,:] .+ ((xAvg - Z[j,:]) .* 0.01)
end
end
end
## Basic K-Means Algorithm (Lecture/segment 13.7 of https://www.edx.org/course/machine-learning-with-python-from-linear-models-to)
"""
kmeans(X,K;dist,initStrategy,Z₀)
Compute K-Mean algorithm to identify K clusters of X using Euclidean distance
# Parameters:
* `X`: a (N x D) data to clusterise
* `K`: Number of cluster wonted
* `dist`: Function to employ as distance (see notes). Default to Euclidean distance.
* `initStrategy`: Whether to select the initial representative vectors:
* `random`: randomly in the X space
* `grid`: using a grid approach [default]
* `shuffle`: selecting randomly within the available points
* `given`: using a provided set of initial representatives provided in the `Z₀` parameter
* `Z₀`: Provided (K x D) matrix of initial representatives (used only together with the `given` initStrategy) [default: `nothing`]
* `rng`: Random Number Generator (see [`FIXEDSEED`](@ref)) [deafult: `Random.GLOBAL_RNG`]
# Returns:
* A tuple of two items, the first one being a vector of size N of ids of the clusters associated to each point and the second one the (K x D) matrix of representatives
# Notes:
* Some returned clusters could be empty
* The `dist` parameter can be:
* Any user defined function accepting two vectors and returning a scalar
* An anonymous function with the same characteristics (e.g. `dist = (x,y) -> norm(x-y)^2`)
* One of the above predefined distances: `l1_distance`, `l2_distance`, `l2²_distance`, `cosine_distance`
# Example:
```julia
julia> (clIdx,Z) = kmeans([1 10.5;1.5 10.8; 1.8 8; 1.7 15; 3.2 40; 3.6 32; 3.3 38; 5.1 -2.3; 5.2 -2.4],3)
```
"""
function kmeans(X,K;dist=(x,y) -> norm(x-y),initStrategy="grid",Z₀=nothing,verbosity=STD,rng = Random.GLOBAL_RNG)
X = makeMatrix(X)
(N,D) = size(X)
# Random choice of initial representative vectors (any point, not just in X!)
minX = minimum(X,dims=1)
maxX = maximum(X,dims=1)
Z₀ = initRepresentatives(X,K,initStrategy=initStrategy,Z₀=Z₀,rng=rng)
Z = Z₀
cIdx_prev = zeros(Int64,N)
# Looping
while true
# Determining the constituency of each cluster
cIdx = classAssignation(X,Z,dist)
# Determining the new representative by each cluster
# for (j,z) in enumerate(eachrow(Z))
updateKMeansRepresentatives!(Z,X,cIdx)
# Checking termination condition: clusters didn't move any more
if cIdx == cIdx_prev
return (cIdx,Z)
else
cIdx_prev = cIdx
end
end
end
function updateKMedoidsRepresentatives!(Z,X,cIdx,dist)
K,D = size(Z)
for j in 1:K
Cⱼ = X[cIdx .== j,:] # Selecting the constituency by boolean selection
nⱼ = size(Cⱼ)[1] # Size of the cluster
if nⱼ == 0 continue end # empty continuency. Let's not do anything. Stil in the next batch other representatives could move away and points could enter this cluster
bestCost = Inf
bestCIdx = 0
for cIdx in 1:nⱼ # candidate index
candidateCost = 0.0
for tIdx in 1:nⱼ # target index
candidateCost += dist(Cⱼ[cIdx,:],Cⱼ[tIdx,:])
end
if candidateCost < bestCost
bestCost = candidateCost
bestCIdx = cIdx
end
end
Z[j,:] = reshape(Cⱼ[bestCIdx,:],1,D)
end
end
## Basic K-Medoids Algorithm (Lecture/segment 14.3 of https://www.edx.org/course/machine-learning-with-python-from-linear-models-to)
"""
kmedoids(X,K;dist,initStrategy,Z₀)
Compute K-Medoids algorithm to identify K clusters of X using distance definition `dist`
# Parameters:
* `X`: a (n x d) data to clusterise
* `K`: Number of cluster wonted
* `dist`: Function to employ as distance (see notes). Default to Euclidean distance.
* `initStrategy`: Whether to select the initial representative vectors:
* `random`: randomly in the X space
* `grid`: using a grid approach
* `shuffle`: selecting randomly within the available points [default]
* `given`: using a provided set of initial representatives provided in the `Z₀` parameter
* `Z₀`: Provided (K x D) matrix of initial representatives (used only together with the `given` initStrategy) [default: `nothing`]
* `rng`: Random Number Generator (see [`FIXEDSEED`](@ref)) [deafult: `Random.GLOBAL_RNG`]
# Returns:
* A tuple of two items, the first one being a vector of size N of ids of the clusters associated to each point and the second one the (K x D) matrix of representatives
# Notes:
* Some returned clusters could be empty
* The `dist` parameter can be:
* Any user defined function accepting two vectors and returning a scalar
* An anonymous function with the same characteristics (e.g. `dist = (x,y) -> norm(x-y)^2`)
* One of the above predefined distances: `l1_distance`, `l2_distance`, `l2²_distance`, `cosine_distance`
# Example:
```julia
julia> (clIdx,Z) = kmedoids([1 10.5;1.5 10.8; 1.8 8; 1.7 15; 3.2 40; 3.6 32; 3.3 38; 5.1 -2.3; 5.2 -2.4],3,initStrategy="grid")
```
"""
function kmedoids(X,K;dist=(x,y) -> norm(x-y),initStrategy="grid",Z₀=nothing, verbosity=STD, rng = Random.GLOBAL_RNG)
X = makeMatrix(X)
(n,d) = size(X)
# Random choice of initial representative vectors
Z₀ = initRepresentatives(X,K,initStrategy=initStrategy,Z₀=Z₀,rng=rng)
Z = Z₀
cIdx_prev = zeros(Int64,n)
# Looping
while true
# Determining the constituency of each cluster
cIdx = classAssignation(X,Z,dist)
# Determining the new representative by each cluster (within the points member)
#for (j,z) in enumerate(eachrow(Z))
updateKMedoidsRepresentatives!(Z,X,cIdx,dist)
# Checking termination condition: clusters didn't move any more
if cIdx == cIdx_prev
return (cIdx,Z)
else
cIdx_prev = cIdx
end
end
end
# Avi v2..
Base.@kwdef mutable struct KMeansMedoidsHyperParametersSet <: BetaMLHyperParametersSet
nClasses::Int64 = 3
dist::Function = (x,y) -> norm(x-y)
initStrategy::String = "Grid"
initialRepresentatives::Union{Nothing,Matrix{Float64}} = nothing
end
#=
Base.@kwdef mutable struct KMedoidsHyperParametersSet <: BetaMLHyperParametersSet
nClasses::Int64 = 3
dist::Function = (x,y) -> norm(x-y)
initStrategy::String = "Grid"
initialRepresentatives::Union{Nothing,Matrix{Float64}} = nothing
end
Base.@kwdef mutable struct KMeansOptionsSet <: BetaMLOptionsSet
verbosity::Verbosity = STD
rng = Random.GLOBAL_RNG
end
Base.@kwdef mutable struct KMedoidsOptionsSet <: BetaMLOptionsSet
verbosity::Verbosity = STD
rng = Random.GLOBAL_RNG
end
=#
Base.@kwdef mutable struct KMeansMedoidsLearnableParameters <: BetaMLLearnableParametersSet
representatives::Union{Nothing,Matrix{Float64}} = nothing
assignments::Vector{Int64} = Int64[]
end
#=
Base.@kwdef mutable struct KMedoidsLearnableParameters <: BetaMLLearnableParametersSet
representatives::Union{Nothing,Matrix{Float64}} = nothing
assignments::Vector{Int64} = Int64[]
end
=#
mutable struct KMeansModel <: BetaMLUnsupervisedModel
hpar::KMeansMedoidsHyperParametersSet
opt::BetaMLDefaultOptionsSet
par::Union{Nothing,KMeansMedoidsLearnableParameters}
fitted::Bool
info::Dict{Symbol,Any}
end
mutable struct KMedoidsModel <: BetaMLUnsupervisedModel
hpar::KMeansMedoidsHyperParametersSet
opt::BetaMLDefaultOptionsSet
par::Union{Nothing,KMeansMedoidsLearnableParameters}
fitted::Bool
info::Dict{Symbol,Any}
end
function KMeansModel(;kwargs...)
m = KMeansModel(KMeansMedoidsHyperParametersSet(),BetaMLDefaultOptionsSet(),KMeansMedoidsLearnableParameters(),false,Dict{Symbol,Any}())
thisobjfields = fieldnames(nonmissingtype(typeof(m)))
for (kw,kwv) in kwargs
for f in thisobjfields
fobj = getproperty(m,f)
if kw in fieldnames(typeof(fobj))
setproperty!(fobj,kw,kwv)
end
end
end
return m
end
function KMedoidsModel(;kwargs...)
m = KMedoidsModel(KMeansMedoidsHyperParametersSet(),BetaMLDefaultOptionsSet(),KMeansMedoidsLearnableParameters(),false,Dict{Symbol,Any}())
thisobjfields = fieldnames(nonmissingtype(typeof(m)))
for (kw,kwv) in kwargs
for f in thisobjfields
fobj = getproperty(m,f)
if kw in fieldnames(typeof(fobj))
setproperty!(fobj,kw,kwv)
end
end
end
return m
end
"""
fit!(m::KMeansModel,x)
"""
function fit!(m::KMeansModel,x)
# Parameter alias..
K = m.hpar.nClasses
dist = m.hpar.dist
initStrategy = m.hpar.initStrategy
initialRepresentatives = m.hpar.initialRepresentatives
verbosity = m.opt.verbosity
rng = m.opt.rng
if m.fitted
# Note that doing this we give lot of importance to the new data, even if this is few records and the model has bee fitted with milions of records.
# So, training 1000 records doesn't give the same output as training 990 records and then training again with 10 records
verbosity >= STD && @warn "Continuing training of a pre-fitted model"
(clIdx,Z) = kmeans(x,K,dist=dist,Z₀=m.par.representatives,initStrategy="given",verbosity=verbosity,rng=rng)
else
(clIdx,Z) = kmeans(x,K,dist=dist,initStrategy=initStrategy,Z₀=initialRepresentatives,verbosity=verbosity,rng=rng)
end
m.par = KMeansMedoidsLearnableParameters(representatives=Z,assignments=clIdx)
m.info[:fittedRecords] = get(m.info,:fittedRecords,0) + size(x,1)
m.info[:dimensions] = size(x,2)
m.fitted=true
return true
end
"""
fit!(m::KMeansModel,x)
"""
function fit!(m::KMedoidsModel,x)
# Parameter alias..
K = m.hpar.nClasses
dist = m.hpar.dist
initStrategy = m.hpar.initStrategy
initialRepresentatives = m.hpar.initialRepresentatives
verbosity = m.opt.verbosity
rng = m.opt.rng
if m.fitted
# Note that doing this we give lot of importance to the new data, even if this is few records and the model has bee fitted with milions of records.
# So, training 1000 records doesn't give the same output as training 990 records and then training again with 10 records
verbosity >= STD && @warn "Continuing training of a pre-fitted model"
(clIdx,Z) = kmedoids(x,K,dist=dist,Z₀=m.par.representatives,initStrategy="given",verbosity=verbosity,rng=rng)
else
(clIdx,Z) = kmedoids(x,K,dist=dist,initStrategy=initStrategy,Z₀=initialRepresentatives,verbosity=verbosity,rng=rng)
end
m.par = KMeansMedoidsLearnableParameters(representatives=Z,assignments=clIdx)
m.info[:fittedRecords] = get(m.info,:fittedRecords,0) + size(x,1)
m.info[:dimensions] = size(x,2)
m.fitted=true
return true
end
function predict(m::Union{KMeansModel,KMedoidsModel})
return m.par.assignments
end
function predict(m::Union{KMeansModel,KMedoidsModel},X)
X = makeMatrix(X)
representatives = m.par.representatives
classes = classAssignation(X,representatives,m.hpar.dist)
return classes
end
function show(io::IO, ::MIME"text/plain", m::KMeansModel)
if m.fitted == false
print(io,"KMeansModel - A K-Means Model (unfitted)")
else
print(io,"KMeansModel - A K-Means Model (fitted on $(m.info[:fittedRecords]) records)")
end
end
function show(io::IO, ::MIME"text/plain", m::KMedoidsModel)
if m.fitted == false
print(io,"KMedoidsModel - A K-Medoids Model (unfitted)")
else
print(io,"KMedoidsModel - A K-Medoids Model (fitted on $(m.info[:fittedRecords]) records)")
end
end
function show(io::IO, m::KMeansModel)
if m.fitted == false
print(io,"KMeansModel - A $(m.hpar.nClasses)-classes K-Means Model (unfitted)")
else
println(io,"KMeansModel - A $(m.info[:dimensions])-dimensions $(m.hpar.nClasses)-classes K-Means Model (fitted on $(m.info[:fittedRecords]) records)")
println(io,m.info)
println(io,"Representatives:")
println(io,m.par.representatives)
end
end
function show(io::IO, m::KMedoidsModel)
if m.fitted == false
print(io,"KMedoidsModel - A $(m.hpar.nClasses)-classes K-Medoids Model (unfitted)")
else
println(io,"KMedoidsModel - A $(m.info[:dimensions])-dimensions $(m.hpar.nClasses)-classes K-Medoids Model (fitted on $(m.info[:fittedRecords]) records)")
println(io,m.info)
println(io,"Distance function used:")
println(io,m.hpar.dist)
println(io,"Representatives:")
println(io,m.par.representatives)
end
end