5.3、聚类之DBSCAN聚类实例

实例一、对鸢尾花数据进行DBSCAN聚类分类

#1、加载数据
data(iris)

#2、聚类
library(fpc)
model_dbscan <- dbscan(iris[, 1:4], 1.5, 5, scale=T, showplot = T, method = "raw")

#画出来明显不对??把距离调小了一点
model_dbscan <- dbscan(iris[, 1:4], 0.42, 5, showplot = T, method = "raw")

str(model_dbscan)
## List of 4
##  $ cluster: num [1:150] 1 1 1 1 1 1 1 1 1 1 ...
##  $ eps    : num 0.42
##  $ MinPts : num 5
##  $ isseed : logi [1:150] TRUE TRUE TRUE TRUE TRUE TRUE ...
##  - attr(*, "class")= chr "dbscan"
#从结果可以看出,模型不是很理想
table(model_dbscan$cluster, iris[, 5])
##    
##     setosa versicolor virginica
##   0      2         10        17
##   1     48          0         0
##   2      0         37         0
##   3      0          3        33
#从上可知:第一列从1到3为识别出来的3个聚类簇,0表示噪声数据或离群点,即不属于任何簇的对象。

#3、绘制聚类图:使用fpc包中的plotcluster()函数,数据将被投影到不同的簇中
plotcluster(iris[, 1:4], model_dbscan$cluster)

实例二、k-means与DBSCAN聚合非球形簇

#1、创建数据
x1 <- seq(0, pi, length.out = 100)
y1 <- sin(x1) + 0.1*rnorm(100)
x2 <- 1.5 + seq(0, pi, length.out = 100)
y2 <- cos(x2) + 0.1*rnorm(100)

data <- data.frame(c(x1, x2), c(y1, y2))
names(data) <- c("x", "y")

#2、用k-means聚类
model_kmeans <- kmeans(data, centers = 2, nstart = 10)

#绘制聚类后的图形
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 3.2.3
p <- ggplot(data, aes(x, y))
p + geom_point(size=2.5, aes(colour=factor(model_kmeans$cluster))) + theme(legend.position="top")

#3、使用fpc包中的DBSCAN函数进行密度聚类
model_dbscan <- dbscan(data, eps = 0.6, MinPts = 4)
p + geom_point(size=2.5, aes(colour=factor(model_dbscan$cluster))) + theme(legend.position="top")

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值