-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex9_1_5.R
executable file
·62 lines (51 loc) · 1.49 KB
/
ex9_1_5.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
50
51
52
53
54
55
56
57
58
59
60
61
62
# exercise 9.1.5
rm(list=ls())
source("setup.R")
# Load data
library(R.matlab)
dat <- readMat(file.path('Data', 'wildfaces.mat'))
X <- dat$X
N <- dim(X)[1]
M <- dim(X)[2]
# Image resolution and number of colors
x = 40;
y = 40;
c = 3;
## K-means clustering
# Maximum number of clusters
K = 10;
# Run k-means (This will take a while to run on a large data set)
res <- kmeans(X, K);
i <- res$cluster
Xc <- res$centers
## Plot results
# Number of images to plot
L = 5;
# Get some random image indices
j = sample(x=1:N, size=L)
graphics.off()
# Plot centroids
n1 = ceiling(sqrt(K/2)); n2 = ceiling(K/n1);
par(mfrow=c(n1, n2), mar=c(0,0,2,0), xaxt='n', yaxt='n')
for(k in 1:K){
centroid <- Xc[k,]
dim(centroid) <- c(x, y, c)
plot(c(1, x), c(1, y), type = "n", xlab="", ylab="", main=paste("Centroid of class", k))
image <- as.raster(centroid)
rasterImage(image, 1, 1, x, y, interpolate=FALSE)
}
# Plot random images and corresponding centroids
dev.new()
par(mfrow=c(L,2), mar=c(0,0,2,0), xaxt='n', yaxt='n')
for(l in 1:L){
centroid <- X[j[l],]
dim(centroid) <- c(x, y, c)
plot(c(1, x), c(1, y), type = "n", xlab="", ylab="", main=paste("Example image from class", i[j[l]]))
image <- as.raster(centroid)
rasterImage(image, 1, 1, x, y, interpolate=FALSE)
centroid <- Xc[i[j[l]],]
dim(centroid) <- c(x, y, c)
plot(c(1, x), c(1, y), type = "n", xlab="", ylab="", main=paste("Centroid of class", i[j[l]]))
image <- as.raster(centroid)
rasterImage(image, 1, 1, x, y, interpolate=FALSE)
}