【问题标题】:spatial clustering in R (simple example)R中的空间聚类(简单示例)
【发布时间】:2015-04-24 16:40:43
【问题描述】:

我有这个简单的data.frame

 lat<-c(1,2,3,10,11,12,20,21,22,23)
 lon<-c(5,6,7,30,31,32,50,51,52,53)
 data=data.frame(lat,lon)

想法是根据距离找到空间聚类

首先,我绘制地图(经度,纬度):

plot(data$lon,data$lat)

很明显,我有三个基于点位置之间距离的聚类。

为此,我在 R 中尝试过这段代码:

d= as.matrix(dist(cbind(data$lon,data$lat))) #Creat distance matrix
d=ifelse(d<5,d,0) #keep only distance < 5
d=as.dist(d)
hc<-hclust(d) # hierarchical clustering
plot(hc)
data$clust <- cutree(hc,k=3) # cut the dendrogram to generate 3 clusters

这给出了:

现在我尝试绘制相同的点,但使用集群中的颜色

plot(data$x,data$y, col=c("red","blue","green")[data$clust],pch=19)

这里是结果

这不是我想要的。

其实我也想找这样的剧情

感谢您的帮助。

【问题讨论】:

  • 我不太清楚你为什么要以这种方式聚集距离......如果你使用hc &lt;- hclust(dist(data)); clust &lt;- cutree(hc, 3),它会按预期工作。

标签: r geospatial spatial hierarchical-clustering


【解决方案1】:

这是一种不同的方法。首先,它假设坐标是 WGS-84 而不是 UTM(平面)。然后它使用层次聚类将给定半径内的所有邻居聚类到同一个聚类(方法=single,采用“朋友的朋友”聚类策略)。

为了计算距离矩阵,我使用包fields 中的rdist.earth 方法。这个包的默认地球半径是 6378.388(赤道半径),这可能不是人们想要的,所以我把它改成了 6371。有关更多信息,请参阅this article

library(fields)
lon = c(31.621785, 31.641773, 31.617269, 31.583895, 31.603284)
lat = c(30.901118, 31.245008, 31.163886, 30.25058, 30.262378)
threshold.in.km <- 40
coors <- data.frame(lon,lat)

#distance matrix
dist.in.km.matrix <- rdist.earth(coors,miles = F,R=6371)

#clustering
fit <- hclust(as.dist(dist.in.km.matrix), method = "single")
clusters <- cutree(fit,h = threshold.in.km)

plot(lon, lat, col = clusters, pch = 20)

如果您不知道集群的数量(如 k-means 选项),这可能是一个很好的解决方案,并且与 minPts = 1 的 dbscan 选项有些相关。

---编辑---

用原始数据:

lat<-c(1,2,3,10,11,12,20,21,22,23)
lon<-c(5,6,7,30,31,32,50,51,52,53)
data=data.frame(lat,lon)

dist <- rdist.earth(data,miles = F,R=6371) #dist <- dist(data) if data is UTM
fit <- hclust(as.dist(dist), method = "single")
clusters <- cutree(fit,h = 1000) #h = 2 if data is UTM
plot(lon, lat, col = clusters, pch = 20)

【讨论】:

  • 我发现您的回答非常有帮助,您能否也为 k-means 方法添加相同的内容?
  • @user3875610 向 k-means 的转换不是很直观,因为不能使用距离矩阵作为 k-means 的输入(它不能仅用距离计算均值)。此外,在这个用例中,您通常不知道集群的数量,并且您更喜欢使用基于密度的方法,例如 hclust 或 dbscan。话虽如此,如果您想使用 k-medoids(类似于 kmeans),请查看此答案:stats.stackexchange.com/questions/32925/…
【解决方案2】:

由于您有要聚类的空间数据,所以DBSCAN 最适合您的数据。 您可以使用 Rfpc 提供的dbscan() 函数进行此聚类。

library(fpc)

lat<-c(1,2,3,10,11,12,20,21,22,23)
lon<-c(5,6,7,30,31,32,50,51,52,53)

DBSCAN <- dbscan(cbind(lat, lon), eps = 1.5, MinPts = 3)
plot(lon, lat, col = DBSCAN$cluster, pch = 20)

【讨论】:

  • 你是如何得到/猜测eps参数的?
【解决方案3】:

这样的事情怎么样:

lat<-c(1,2,3,10,11,12,20,21,22,23)
lon<-c(5,6,7,30,31,32,50,51,52,53)

km <- kmeans(cbind(lat, lon), centers = 3)
plot(lon, lat, col = km$cluster, pch = 20)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-18
    • 2016-11-25
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    相关资源
    最近更新 更多