# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .r
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: R 3.6
#     language: R
#     name: ir36
# ---

# # Clustering

# +
getData <- function(N=30) {
    x1 <- c(
        rnorm(N, mean=2.5, sd=2.5),
        rnorm(N, mean=10.5, sd=2.5)
    )
    x2 <- c(
        rnorm(N, mean=2.5, sd=2.5),
        rnorm(N, mean=10.5, sd=2.5)
    )
    y <- c(rep(0, N), rep(1, N))
    X <- data.frame(x1=x1, x2=x2)
    return(list(X=X, y=y))
}

D = getData()
# -

# ## K-means

m <- kmeans(D$X, 2)

print(m)

print(m$totss)

# +
options(repr.plot.width=5, repr.plot.height=5)

plot(D$X, col=m$cluster)
points(m$centers, col=1:2, pch=8, cex=2)

# +
library('cluster')

options(repr.plot.width=5, repr.plot.height=5)

clusplot(D$X, m$cluster, color=TRUE, shade=TRUE, labels=2, lines=0)

# +
library('fpc')

options(repr.plot.width=5, repr.plot.height=5)
plotcluster(D$X, m$cluster)
# -

# ## Ward hierarchical clustering

d <- dist(D$X, method='euclidean')
m <- hclust(d, method='ward.D2')

print(m)

# +
options(repr.plot.width=10, repr.plot.height=8)

plot(m)
# -

# ## Model based

# +
library('mclust')

m <- Mclust(D$X)
# -

print(summary(m))

plot(m)

# ## Comparing clustering solutions

# +
m1 <- kmeans(D$X, 2)
m2 <- Mclust(D$X)

d <- dist(D$X, method='euclidean')

s <- cluster.stats(d, m1$cluster, m2$cluster)
print(s)
# -

# ## Silhouette score

s <- silhouette(m1$cluster, d)
print(summary(s))

plot(s, col=c('red', 'blue'))

StarcoderdataJupyterScriptsDedupFiltered