99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁(yè)精彩閱讀R語(yǔ)言的三種聚類方法
R語(yǔ)言的三種聚類方法
2018-01-28
收藏

R語(yǔ)言的三種聚類方法

摘要: 層次聚類 kmeans dbscan筆記

一、距離和相似系數(shù)

r語(yǔ)言中使用dist(x, method = “euclidean”,diag = FALSE, upper = FALSE, p = 2) 來(lái)計(jì)算距離。其中x是樣本矩陣或者數(shù)據(jù)框。method表示計(jì)算哪種距離。method的取值有:

euclidean                歐幾里德距離,就是平方再開方。

maximum                切比雪夫距離

manhattan            絕對(duì)值距離

canberra                Lance 距離

minkowski            明科夫斯基距離,使用時(shí)要指定p值

binary                    定性變量距離.

定性變量距離: 記m個(gè)項(xiàng)目里面的 0:0配對(duì)數(shù)為m0 ,1:1配對(duì)數(shù)為m1,不能配對(duì)數(shù)為m2,距離=m1/(m1+m2);

diag 為TRUE的時(shí)候給出對(duì)角線上的距離。upper為TURE的時(shí)候給出上三角矩陣上的值。

r語(yǔ)言中使用scale(x, center = TRUE, scale = TRUE) 對(duì)數(shù)據(jù)矩陣做中心化和標(biāo)準(zhǔn)化變換。

如只中心化 scale(x,scale=F) ,

r語(yǔ)言中使用sweep(x, MARGIN, STATS, FUN=”-“, …) 對(duì)矩陣進(jìn)行運(yùn)算。MARGIN為1,表示行的方向上進(jìn)行運(yùn)算,為2表示列的方向上運(yùn)算。STATS是運(yùn)算的參數(shù)。FUN為運(yùn)算函數(shù),默認(rèn)是減法。下面利用sweep對(duì)矩陣x進(jìn)行極差標(biāo)準(zhǔn)化變換

>center <- sweep(x, 2, apply(x, 2, mean)) #在列的方向上減去均值。
>R <- apply(x, 2, max) - apply(x,2,min)   #算出極差,即列上的最大值-最小值
>x_star <- sweep(center, 2, R, "/")        #把減去均值后的矩陣在列的方向上除以極差向量

    center <- sweep(x, 2, apply(x, 2, min)) #極差正規(guī)化變換
    R <- apply(x, 2, max) - apply(x,2,min)
    x_star <- sweep(center, 2, R, "/")

有時(shí)候我們不是對(duì)樣本進(jìn)行分類,而是對(duì)變量進(jìn)行分類。這時(shí)候,我們不計(jì)算距離,而是計(jì)算變量間的相似系數(shù)。常用的有夾角和相關(guān)系數(shù)。

r語(yǔ)言計(jì)算兩向量的夾角余弦:

y <- scale(x, center = F, scale = T)/sqrt(nrow(x)-1)
C <- t(y) %*% y

相關(guān)系數(shù)用cor函數(shù)

二、層次聚類

層次聚類法。先計(jì)算樣本之間的距離。每次將距離最近的點(diǎn)合并到同一個(gè)類。然后,再計(jì)算類與類之間的距離,將距離最近的類合并為一個(gè)大類。不停的合并,直到合成了一個(gè)類。其中類與類的距離的計(jì)算方法有:最短距離法,最長(zhǎng)距離法,中間距離法,類平均法等。比如最短距離法,將類與類的距離定義為類與類之間樣本的最段距離。。。

r語(yǔ)言中使用hclust(d, method = “complete”, members=NULL) 來(lái)進(jìn)行層次聚類。

其中d為距離矩陣。

method表示類的合并方法,有:

single            最短距離法

complete        最長(zhǎng)距離法

median        中間距離法

mcquitty        相似法

average        類平均法

centroid        重心法

ward            離差平方和法

> x <- c(1,2,6,8,11)      #試用一下
> dim(x) <- c(5,1)
> d <- dist(x)
> hc1 <- hclust(d,"single")
> plot(hc1)
> plot(hc1,hang=-1,type="tirangle")             #hang小于0時(shí),樹將從底部畫起。
#type = c("rectangle", "triangle"),默認(rèn)樹形圖是方形的。另一個(gè)是三角形。
#horiz  TRUE 表示豎著放,F(xiàn)ALSE表示橫著放。

> z <- scan()
1: 1.000 0.846 0.805 0.859 0.473 0.398 0.301 0.382
9: 0.846 1.000 0.881 0.826 0.376 0.326 0.277 0.277
17: 0.805 0.881 1.000 0.801 0.380 0.319 0.237 0.345
25: 0.859 0.826 0.801 1.000 0.436 0.329 0.327 0.365
33: 0.473 0.376 0.380 0.436 1.000 0.762 0.730 0.629
41: 0.398 0.326 0.319 0.329 0.762 1.000 0.583 0.577
49: 0.301 0.277 0.237 0.327 0.730 0.583 1.000 0.539
57: 0.382 0.415 0.345 0.365 0.629 0.577 0.539 1.000
65:
Read 64 items
> names
[1] "shengao"    "shoubi"     "shangzhi"   "xiazhi"     "tizhong"
[6] "jingwei"    "xiongwei"   "xiongkuang"
> r <- matrix(z,nrow=8,dimnames=list(names,names))
> d <- as.dist(1-r)
> hc <- hclust(d)
> plot(hc)

然后可以用rect.hclust(tree, k = NULL, which = NULL, x = NULL, h = NULL,border = 2, cluster = NULL)來(lái)確定類的個(gè)數(shù)。 tree就是求出來(lái)的對(duì)象。k為分類的個(gè)數(shù),h為類間距離的閾值。border是畫出來(lái)的顏色,用來(lái)分類的。

> plot(hc)
> rect.hclust(hc,k=2)
> rect.hclust(hc,h=0.5)

    result=cutree(model,k=3) 該函數(shù)可以用來(lái)提取每個(gè)樣本的所屬類別

三、動(dòng)態(tài)聚類 kmeans

層次聚類,在類形成之后就不再改變。而且數(shù)據(jù)比較大的時(shí)候更占內(nèi)存。
動(dòng)態(tài)聚類,先抽幾個(gè)點(diǎn),把周圍的點(diǎn)聚集起來(lái)。然后算每個(gè)類的重心或平均值什么的,以算出來(lái)的結(jié)果為分類點(diǎn),不斷的重復(fù)。直到分類的結(jié)果收斂為止。r語(yǔ)言中主要使用kmeans(x, centers, iter.max = 10, nstart = 1,algorithm =c(“Hartigan-Wong”, “Lloyd”,”Forgy”, “MacQueen”))來(lái)進(jìn)行聚類。centers是初始類的個(gè)數(shù)或者初始類的中心。iter.max是最大迭代次數(shù)。nstart是當(dāng)centers是數(shù)字的時(shí)候,隨機(jī)集合的個(gè)數(shù)。algorithm是算法,默認(rèn)是第一個(gè)。

> newiris <- iris
> model <- kmeans(scale(newiris[1:4]),3)
> model
K-means clustering with 3 clusters of sizes 50, 47, 53
Cluster means:
  Sepal.Length Sepal.Width Petal.Length Petal.Width
1  -1.01119138  0.85041372   -1.3006301  -1.2507035
2   1.13217737  0.08812645    0.9928284   1.0141287
3  -0.05005221 -0.88042696    0.3465767   0.2805873
Clustering vector:
  [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 [38] 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 3 3 3 2 3 3 3 3 3 3 3 3 2 3 3 3 3 2 3 3 3
 [75] 3 2 2 2 3 3 3 3 3 3 3 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 2 3 2 2 2 2 3 2 2 2 2
[112] 2 2 3 3 2 2 2 2 3 2 3 2 3 2 2 3 2 2 2 2 2 2 3 3 2 2 2 3 2 2 2 3 2 2 2 3 2
[149] 2 3
Within cluster sum of squares by cluster:
[1] 47.35062 47.45019 44.08754
 (between_SS / total_SS =  76.7 %)
Available components:
[1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
[6] "betweenss"    "size"         "iter"         "ifault"
> table(iris$Species,kc$cluster)
Error in table(iris$Species, kc$cluster) : object 'kc' not found
> table(iris$Species,model$cluster)   #比較一下
              1  2  3
  setosa     50  0  0
  versicolor  0 11 39
  virginica   0 36 14
> plot(newiris[c("Sepal.Length","Sepal.Width")],col=model$cluster) #畫出聚類圖

四、DBSCAN

動(dòng)態(tài)聚類往往聚出來(lái)的類有點(diǎn)圓形或者橢圓形?;诿芏葤呙璧乃惴軌蚪鉀Q這個(gè)問(wèn)題。思路就是定一個(gè)距離半徑,定最少有多少個(gè)點(diǎn),然后把可以到達(dá)的點(diǎn)都連起來(lái),判定為同類。在r中的實(shí)現(xiàn)

dbscan(data, eps, MinPts, scale, method, seeds, showplot, countmode)

其中eps是距離的半徑,minpts是最少多少個(gè)點(diǎn)。 scale是否標(biāo)準(zhǔn)化(我猜) ,method 有三個(gè)值raw,dist,hybird,分別表示,數(shù)據(jù)是原始數(shù)據(jù)避免計(jì)算距離矩陣,數(shù)據(jù)就是距離矩陣,數(shù)據(jù)是原始數(shù)據(jù)但計(jì)算部分距離矩陣。showplot畫不畫圖,0不畫,1和2都畫。countmode,可以填個(gè)向量,用來(lái)顯示計(jì)算進(jìn)度。用鳶尾花試一試

> install.packages("fpc", dependencies=T)
> library(fpc)
> newiris <- iris[1:4]
> model <- dbscan(newiris,1.5,5,scale=T,showplot=T,method="raw")# 畫出來(lái)明顯不對(duì) 把距離調(diào)小了一點(diǎn)
> model <- dbscan(newiris,0.5,5,scale=T,showplot=T,method="raw")
> model #還是不太理想……
dbscan Pts=150 MinPts=5 eps=0.5
        0  1  2
border 34  5 18
seed    0 40 53
total  34 45 71

數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }