-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path16-K-Means-Clustering.Rmd
More file actions
181 lines (91 loc) · 1.93 KB
/
Copy path16-K-Means-Clustering.Rmd
File metadata and controls
181 lines (91 loc) · 1.93 KB
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
---
"k-means algoritması (k-means algorithm)"
---
```{r}
protein<-read.table("protein.txt", sep = "\t", header = T)
dim(protein)
```
```{r}
head(protein)
```
```{r}
X<-colnames(protein)[-1]
pmatrix<-scale(protein[,X])
pcenter<-attr(pmatrix,"scale:center")
pscale<-attr(pmatrix, "scale:scale")
attr(pmatrix,"scale:center")<-NULL
attr(pmatrix,"scale:scale")<-NULL
```
```{r}
k<-5
pclusters<-kmeans(pmatrix, k, nstart = 100, iter.max = 100)
summary(pclusters)
```
```{r}
pclusters$centers
```
```{r}
pclusters$size
```
```{r}
groups<-pclusters$cluster
groups
```
```{r}
split(protein, groups)
```
```{r}
library(fpc)
clustering_ch<-kmeansruns(pmatrix, krange=1:10, criterion="ch")
clustering_ch$bestk
```
```{r}
clustering_asw<-kmeansruns(pmatrix, krange=1:10, criterion="asw")
clustering_asw$bestk
```
```{r}
k=5
cboot<-clusterboot(pmatrix, clustermethod = kmeansCBI, runs=100,
iter.max=100, krange=k, seed=1234)
cboot$bootmean
```
```{r}
cboot$bootbrd
```
```{r}
sqr_edist<-function(x,y){sum((x-y)^2)}
assign_cluster<-function(newpt, centers, xcenter=0, xscale=1){
xpt<-(newpt-xcenter)/xscale
dists<-apply(centers,1,FUN=function(c0){sqr_edist(c0,xpt)})
which.min(dists)
}
```
```{r}
mean1<-c(1,2,1)
sd1<-c(1,2,1)
mean2<-c(1,-3,5)
sd2<-c(2,1,2)
mean3<-c(-3,-3,-3)
sd3<-c(1,2,1)
```
```{r}
library(MASS)
clust1<-mvrnorm(100,mu=mean1,Sigma=diag(sd1))
clust2<-mvrnorm(100,mu=mean2,Sigma=diag(sd2))
clust3<-mvrnorm(100,mu=mean3,Sigma=diag(sd3))
toydata<-rbind(clust3, rbind(clust1,clust2))
```
```{r}
tmatrix<-scale(toydata)
tcenter<-attr(tmatrix,"scaled:center")
tscale<-attr(tmatrix,"scaled:scale")
attr(tmatrix,"scale:center")<-NULL
attr(tmatrix,"scale:scale")<-NULL
kbest_t<-3
tclusters<-kmeans(tmatrix, kbest_t, nstart = 100, iter.max=100)
tclusters$size
```
```{r}
assign_cluster(mvrnorm(1,mean3,diag(sd3)),
tclusters$centers,tcenter,tscale)
```