【问题标题】:How to plot clusters with a matrix?如何用矩阵绘制集群?
【发布时间】:2014-06-28 02:34:52
【问题描述】:

我有一个文档数据集,我将其转换为矩阵并运行 k-means 聚类,如何绘制图表以显示带有矩阵的聚类?

k<-5
kmeansResult<-kmeans(m3,k)
plot(m3, col = kmeansResult$cluster)
points(kmeansResult$centers, col = 1:5, pch = 8, cex = 5)

【问题讨论】:

  • 查看这篇关于集群的优秀帖子 (stackoverflow.com/questions/15376075/…)
  • 你能提供一个可重现的例子吗?您的数据或其中的一部分。
  • 你的屏幕有多少尺寸?你的数据集有多少?
  • dim(m3) [1] 10829 199

标签: r cluster-analysis data-mining


【解决方案1】:

正如在 cmets 中提到的,问题是您的数据集可能有 > 2 个维度(超过 2 个变量),而您的图被限制为 2 个(或者可能是 3 个)维度。所以需要某种降维。典型的方法是对原始数据进行主成分分析,然后绘制前两台 PC,按集群组织。因此,这里有三种在 R 中执行此操作的方法,以 mtcars 数据集为例。

df     <- mtcars[,c(1,3,4,5,6,7)]      # subset of mtcars dataset
set.seed(1)                            # for reproducible example
km <- kmeans(df,centers=3)             # k-means, 3 clusters
# using package cluster
library(cluster)
clusplot(df,km$cluster)

# using package ade4
library(ade4)
pca    <-prcomp(df, scale.=T, retx=T)  # principal components analysis
plot.df <- cbind(pca$x[,1], pca$x[,2]) # first and second PC
s.class(plot.df, factor(km$cluster))

# ggplot solution
pca    <-prcomp(df, scale.=T, retx=T)  # principal components analysis
# gg: data frame of PC1 and PC2 scores with corresponding cluster
gg <- data.frame(cluster=factor(km$cluster), x=scores$PC1, y=scores$PC2)
# calculate cluster centroid locations
centroids <- aggregate(cbind(x,y)~cluster,data=gg,mean)
# merge centroid locations into ggplot dataframe
gg <- merge(gg,centroids,by="cluster",suffixes=c("",".centroid"))
# calculate 95% confidence ellipses
library(ellipse)
conf.rgn  <- do.call(rbind,lapply(1:3,function(i)
  cbind(cluster=i,ellipse(cov(gg[gg$cluster==i,2:3]),centre=as.matrix(centroids[i,2:3])))))
conf.rgn  <- data.frame(conf.rgn)
conf.rgn$cluster <- factor(conf.rgn$cluster)
# plot cluster map
library(ggplot2)
ggplot(gg, aes(x,y, color=cluster))+
  geom_point(size=3) +
  geom_point(data=centroids, size=4) +
  geom_segment(aes(x=x.centroid, y=y.centroid, xend=x, yend=y))+
  geom_path(data=conf.rgn)

请注意,这三个选项都给出了不同的省略号!这是因为它们的定义不同。 clusplot(...) 默认情况下会生成“最小体积椭圆”,它具有正确的中心和方向,但大小刚好足以包含集群中的所有点。 s.plot(...) 根据可在调用参数中设置的比例因子生成椭圆。 ggplot(...) 解决方案生成的椭圆是每个集群的 95% 置信区域(假设每个集群中的点服从二元正态分布)。从中可以看出,集群明显重叠;也就是说,有几个点可能属于多个集群。这给出了更真实的数据表示,IMO,这是我喜欢它的原因之一,尽管它显然需要更多的工作。

【讨论】:

  • 我尝试使用您的第二种方法,并将结果附在问题中。 4个簇好像都挤在一起了,我可以放大吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-25
  • 2021-10-10
  • 2019-11-23
  • 1970-01-01
  • 2016-06-04
相关资源
最近更新 更多