2016-12-23 32 views
0

我已經使用函數(R中的集羣包)成功運行了圍繞Medoids的分區,現在,我想要使用結果將新觀察歸因於先前定義的簇/冥界。PAM集羣 - 在另一個數據集中使用結果

另一種方法把問題是,鑑於ķ簇/中心點劃分已發現由PAM功能,這是更接近一個附加的觀察,這不是在初始數據集?

x<-matrix(c(1,1.2,0.9,2.3,2,1.8, 
      3.2,4,3.1,3.9,3,4.4),6,2) 
x 
    [,1] [,2] 
[1,] 1.0 3.2 
[2,] 1.2 4.0 
[3,] 0.9 3.1 
[4,] 2.3 3.9 
[5,] 2.0 3.0 
[6,] 1.8 4.4 
pam(x,2) 

觀測1,3和5,和圖2,4和6被聚集在一起,並觀察1和6是中心點劃分:

Medoids: 
    ID   
[1,] 1 1.0 3.2 
[2,] 6 1.8 4.4 
Clustering vector: 
[1] 1 2 1 2 1 2 

現在,向其中簇/ medoidý應歸功於/有關聯?

y<-c(1.5,4.5) 

噢,如果你有幾個解決方案,我的大數據集中的計算時間很重要。

+1

可以計算爲y和以往任何時候都距離小於從位數的距離。 Y將屬於該羣集。 –

+0

您不需要'which.min'和距離計算庫。 **只需自己寫*一行代碼** ** –

回答

2

一般嘗試此k個簇:

k <- 2 # pam with k clusters 
res <- pam(x,k) 

y <- c(1.5,4.5) # new point 

# get the cluster centroid to which the new point is to be assigned to 
# break ties by taking the first medoid in case there are multiple ones 

# non-vectorized function 
get.cluster1 <- function(res, y) which.min(sapply(1:k, function(i) sum((res$medoids[i,]-y)^2))) 

# vectorized function, much faster 
get.cluster2 <- function(res, y) which.min(colSums((t(res$medoids)-y)^2)) 

get.cluster1(res, y) 
#[1] 2 
get.cluster2(res, y) 
#[1] 2 

# comparing the two implementations (the vectorized function takes much les s time) 
library(microbenchmark) 
microbenchmark(get.cluster1(res, y), get.cluster2(res, y)) 

#Unit: microseconds 
#     expr min  lq  mean median  uq  max neval cld 
# get.cluster1(res, y) 31.219 32.075 34.89718 32.930 33.358 135.995 100 b 
# get.cluster2(res, y) 17.107 17.962 19.12527 18.817 19.245 41.483 100 a 

擴展到任意距離函數:

# distance function 
euclidean.func <- function(x, y) sqrt(sum((x-y)^2)) 
manhattan.func <- function(x, y) sum(abs(x-y)) 

get.cluster3 <- function(res, y, dist.func=euclidean.func) which.min(sapply(1:k, function(i) dist.func(res$medoids[i,], y))) 
get.cluster3(res, y) # use Euclidean as default 
#[1] 2 
get.cluster3(res, y, manhattan.func) # use Manhattan distance 
#[1] 2 
+0

請注意,此代碼僅爲歐幾里得距離 - 但您不會使用pam與歐幾里德距離。 –

+0

@ Anony-Mousse我們可以使用任何距離函數來代替歐幾里得。 –

相關問題