2013-05-01 57 views
3

我從來沒有使用R,但現在我需要導入一個稀疏矩陣做關聯規則中的R

我的進口數據是一個稀疏矩陣是這樣的:可以導入稀疏矩陣做R中的關聯規則嗎?

ĴX
。 。 。 。
。 。 。 。
200000000。 。 。

稀疏矩陣大小爲2億×3, 矩陣是200000 X 100000(大數據?)

我想用這個數據做關聯規則在R,
是用'包裝圓點'itemMatrix-class & tidLists-class()?或其他人?

怎麼辦?

我非常喜歡這一點,但不工作:

channel <- odbcConnect("test") 
data<-sqlQuery(channel,"select i,j,x from table") # it's work 
(args <- data.frame(data))     # it's work ,print sparse matrix 
# i j x 
#1 2 3 1 
#2 3 5 1 
#3 3 1 1 
#3 2 5 1 
# .... 
(Aa <- do.call(sparseMatrix, args))   # it's work ,print sparse Matrix of class "dgCMatrix" 
# 200000 X 100000 sparse Matrix of class "dgCMatrix" 
#  1 2 3 4 5.... 
# [1,] . . . . . 
# [2,] . . | . | 
# [3,] | . . . | 
# .... 
rules <- apriori(Aa)       # it's not work 

Error in as(data, "transactions") : 
no method or default for coercing 「dgCMatrix」 to 「transactions」 

可以在先驗函數使用稀疏矩陣?
也許我使用錯誤的包?
我需要稀疏矩陣 - >矩陣 - >關聯規則
稀疏矩陣 - >關聯規則

+0

*這不是工作*但還有什麼?你能提供錯誤信息嗎? – flodel 2013-05-02 00:42:49

+1

as(data,「transactions」)中的錯誤: 沒有方法或強制將「dgCMatrix」強制爲「transactions」的默認方法 – user2340340 2013-05-02 09:08:07

回答

1

進口I,J

library(RODBC) 
library(arulse) 
channel <- odbcConnect("DB", uid="XXXX", pwd="XXXX") 
data<-sqlQuery(channel,"select distinct i as TID,j as item from table") 
trans <- as(split(data[,"item"], data[,"TID"]), "transactions") # add this 
rules <- apriori(trans) 
+1

「split」操作速度令人難以置信,而且效率低下。由於「交易」對象在內部是稀疏矩陣,因此似乎應該有一種直接的方法將「矩陣」對象轉換爲「交易」對象。 – Zach 2013-11-20 19:24:16

0

在內部,arules曾經使用dgcMatrix,但切換到更高效的ngcMatrix(二進制)。如果我們轉換到這一點,我們很酷。

library(tidyverse) 
library(arules) 

data = data.frame(ID = sample(LETTERS[1:3], 20, T), item = sample(letters[1:5], 20, T), stringsAsFactors = F) 

data %>% 
    unique %>% 
    xtabs(~ item + ID, data = ., sparse = T) -> 
    m 

head(m) 
#> 3 x 5 sparse Matrix of class "dgCMatrix" 
#> a b c d e 
#> A . 1 1 1 1 
#> B 1 . 1 1 1 
#> C . 1 1 1 . 

apriori(m) 
#> Error in as(data, "transactions"): no method or default for coercing "dgCMatrix" to "transactions" 

這是我們期望的錯誤 - 但如果我們轉換爲另一種稀疏矩陣(非常快) -

m1 <- as(m, "ngCMatrix") 

apriori(m1) 
#> Apriori 
#> 
#> Parameter specification: 
#> confidence minval smax arem aval originalSupport maxtime support minlen 
#>   0.8 0.1 1 none FALSE   TRUE  5  0.1  1 
#> maxlen target ext 
#>  10 rules FALSE 
#> 
#> Algorithmic control: 
#> filter tree heap memopt load sort verbose 
#>  0.1 TRUE TRUE FALSE TRUE 2 TRUE 
#> 
#> Absolute minimum support count: 0 
#> 
#> set item appearances ...[0 item(s)] done [0.00s]. 
#> set transactions ...[3 item(s), 5 transaction(s)] done [0.00s]. 
#> sorting and recoding items ... [3 item(s)] done [0.00s]. 
#> creating transaction tree ... done [0.00s]. 
#> checking subsets of size 1 2 3 done [0.00s]. 
#> writing ... [4 rule(s)] done [0.00s]. 
#> creating S4 object ... done [0.00s]. 
#> set of 4 rules 

它所有的作品。