-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathk_means.R
49 lines (36 loc) · 1.02 KB
/
k_means.R
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
run_kmeans <- function(X,how.choose.k = F){
# plotta i dati per avere un'idea su che k scegliere per l'algoritmo
# k-means
x11()
plot(X)
# leggi in input il numero di cluster
k <- readinteger()
# runna k-means
result.k <- kmeans(X, centers=k)
x11()
plot(X, col = result.k$cluster+1)
if(how.choose.k){
b <- w <- NULL
for(k in 1:10){
result <- kmeans(X, k)
w <- c(w, sum(result$wit))
b <- c(b, result$bet)
}
x11()
matplot(1:10, b/(w+b), pch='', xlab='clusters', ylab='between/tot', main='Choice of k', ylim=c(0,1))
lines(1:10, b/(w+b), type='b', lwd=2)
x11()
matplot(1:10, w/(w+b), pch='', xlab='clusters', ylab='within/tot', main='Choice of k', ylim=c(0,1))
lines(1:10, w/(w+b), type='b', lwd=2)
}
return(result.k)
}
readinteger <- function()
{
n <- readline(prompt="Enter an integer: ")
if(!grepl("^[0-9]+$",n))
{
return(readinteger())
}
return(as.integer(n))
}