數據分析與挖掘 - R語言:K-means聚類算法


一個簡單的例子!
環境:CentOS6.5
Hadoop集群、Hive、R、RHive,具體安裝及調試方法見博客內文檔。

 

1、分析題目
--有一個用戶點擊數據樣本(husercollect)
--按用戶訪問的時間(時)統計
--要求:分析時間和點擊次數的聚類情況


2、數據准備

--創建臨時表
DROP TABLE if exists tmp.t2_collect;
CREATE TABLE tmp.t2_collect(
    h int,
    cnt int
) COMMENT '用戶點擊數據臨時表';

--插入臨時表
insert overwrite table tmp.t2_collect
--分組
select a1.h, count(1) as cnt from(
    --取出時
    select hour(createtime) as h from bdm.husercollect
)a1
group by a1.h;


3、評估K值

#!/usr/bin/Rscript
library(RHive)
rhive.connect(host ='192.168.107.82')
data <- rhive.query('select h,cnt from tmp.t2_collect limit 6000')
x <- data$h
y <- data$cnt

--組合成數據框
df <- data.frame(x, y)
--添加列名
colnames(df) <- c("hour", "cnt")

--cluster.stats函數需要使用fpc庫
library(fpc)

--k取2到8評估K
K <- 2:8
--每次迭代30次,避免局部最優
round <- 30
rst <- sapply(K, function(i){  
    print(paste("K=",i))
    mean(sapply(1:round,function(r){
        print(paste("Round",r))
        result <- kmeans(df, i)
        stats <- cluster.stats(dist(df), result$cluster)
        stats$avg.silwidth
    }))
})

--加載圖形庫
library(Cairo)
png("k-points-pic.png", width=800, height=600)
plot(K, rst, type='l', main='outline & R relation', ylab='outline coefficient')

dev.off()
rhive.close()

評估結果:


由上圖可見當K=3時,輪廓系數最大。


4、聚類分析

#!/usr/bin/Rscript
library(RHive)
rhive.connect(host ='192.168.107.82')
data <- rhive.query('select h,cnt from tmp.t2_collect limit 6000')
x <- data$h
y <- data$cnt

--組合成數據框
df <- data.frame(x, y)
--添加列名
colnames(df) <- c("hour", "cnt")

--Kmeans
kc <- kmeans(df, 3);

--具體分類情況
--fitted(kc);

library(Cairo)
png("k-means-pic.png", width=800, height=600)
plot(df[c("hour", "cnt")], col = kc$cluster, pch = 8);
points(kc$centers[,c("hour", "cnt")], col = 1:3, pch = 8, cex=2);

dev.off()
rhive.close()

聚類結果:

至此,一個簡單的K-means聚類算法實例完成!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM