####聚类####
##随机产生三个簇点
c1<-cbind(rnorm(
100,
2,
1),rnorm(
100,
2,
2))
c2<-cbind(rnorm(
80,
3,
1),rnorm(
80,
20,
1))
c3<-cbind(rnorm(
60,
15,
1),rnorm(
60,
25,
1))
v=rbind(c1,c2,c3)
v
plot(v)
cl=kmeans(v,
3)
cl
cl$iter
cl$withinss
plot(v, col = cl$cluster)
cbind(v,cl$cluster)
points(cl$centers, col =
1:
2, pch =
8, cex =
2)
data(USArrests)
USArrests
plot(USArrests)
cl = kmeans(scale(USArrests),
4)
cl
dist(v)
plot(hclust(dist(v),method =
'single'))
plot(hclust(dist(v),method =
'single'),hang = -
1)
hc<-plot(hclust(dist(v),method =
'ward.D2'))
cutree(hc,k=
3)
attach(iris) #为了使用数据集的名称
names(iris)
Species
iris1=iris[,-
5]
iris1
k =
1:
15
ss = NULL
for(i in
1:
15){
ss[i] = kmeans(scale(iris1),i)$tot.withnss/(kmeans(scale(iris1),i)$totss)
}
plot(ss,k,type =
'l')
hc1 <- hclust(dist(cent)^
2, method =
"cen", members = table(memb))
opar <- par(mfrow = c(
1,
2))
plot(hc, labels = FALSE, hang = -
1, main =
"Original Tree")
plot(hc1, labels = FALSE, hang = -
1, main =
"Re-start from 3 clusters")
par(opar)
#2. 练习:随机生成三个簇点:
c1<-cbind(rnorm(
30,
2,
1),rnorm(
30,
2,
1))
c2<-cbind(rnorm(
30,
3,
1),rnorm(
30,
20,
1))
c3<-cbind(rnorm(
30,
15,
1),rnorm(
30,
25,
1))
v1=cbind(c1,c2,c3)
#####3. 数据集用的是iris
#第一步:对数据集进行初步统计分析
#检查数据的维度
dim(iris)
#显示数据集中的列名
names(iris)
#显示数据集的内部结构
str(iris)
#显示数据集的属性
attributes(iris)
#$names –就是数据集的列名
#$row.names –每行数据的标号
#$class –表示类别
#查看数据集的前五项数据情况
iris[
1:
5,]
#查看数据集中属性Sepal.Length前10行数据
iris[
1:
10,
"Sepal.Length"]
#同上
iris$Sepal.Length[
1:
10]
#显示数据集中每个变量的分布情况
summary(iris)
#####显示iris数据集列Species中各个值出现频次
table(iris$Species)
#根据列Species画出饼图
pie(table(iris$Species))
#算出列Sepal.Length的所有值的方差
var(iris$Sepal.Length)
#算出列iris$Sepal.Length和iris$Petal.Length的协方差
cov(iris$Sepal.Length, iris$Petal.Length)
#算出列iris$Sepal.Length和iris$Petal.Length的相关系数, 从结果看这两个值是强相关。
cor(iris$Sepal.Length, iris$Petal.Length)
#画出列iris$Sepal.Length分布柱状图
hist(iris$Sepal.Length)
#画出列iris$Sepal.Length的密度函数图
plot(density(iris$Sepal.Length))
#画出列iris$Sepal.Length和iris$Sepal.Width的散点图
plot(iris$Sepal.Length, iris$Sepal.Width)
#绘出矩阵各列的散布图
plot(iris)
#OR
pairs(iris)
#第二步:进行Kmean聚类分析