聚类吗,试试kmeans,基础R自带
用自带的iris 数据集举例,该集合包含3个鸢尾花种类的四个属性(花瓣萼片的长宽啥的)
head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
按花瓣长宽作图这样:
library(dplyr)
library(ggplot2)
iris %>%
ggplot(aes(x=Petal.Length, y= Petal.Width, color=Species))+
geom_point()
然后我们可以用Kmeans,对四个属性进行聚类:kmeans需要指定聚类数,nstart则是随机选取中心的次数。
聚类之后同样作图,用颜色标注聚类结果。
## kmeans clustering
km_cluster <- kmeans(iris[,1:4],centers=3,nstart=100)
## data used for plotting
iris_c <- iris
iris_c$cluster <- as.factor(km_cluster$cluster)
## plotting
gg <- ggplot(data=iris_c,aes(x=Petal.Length, y= Petal.Width, color=cluster))+
geom_point()
print(gg)
四维数据不容易作图所以这里只画了花瓣的长宽两维,不过对比cluster的结果和实际Species可以看出分类还是挺准确的,大概捕捉到了数据间的关系。
其他聚类的算法也都可以考虑( •̀ ω •́ )y不妨先拿kmeans试试