2016-11-27 67 views
3

我的目標是使用由R包arules生成的規則來預測每個事務(每個事務有1個主題)的topic,其中每個事務是一組文件。我有一套訓練集trans.train(用於創建規則)和測試集trans.test(我想預測「主題」)。我也希望能夠測試這些預測(規則右側的百分比是正確的話題)。將從R中的arules生成的規則應用到新事務中

我能夠確保每條規則的右側是一個主題(如topic = earn),左側是文檔中的任何其他單詞。所以我所有的規則有以下形式:

{word1,...,wordN} -> {topic=topic1} 

我已經整理規則,並希望將其應用到trans.test,使置信度最高的規則預測的右手邊,但我無法弄清楚如何根據文檔做到這一點。

有沒有關於我如何實現這一點的任何想法?我已經看到了arulesCBA包,但它實現了一個更復雜的算法,而我只想使用最高置信度規則作爲我的topic的預測值。產生交易

代碼:

library(arules) 
#load data into R 
filename = "C:/Users/sterl_000/Desktop/lab2file.csv" 
data = read.csv(filename,header=TRUE,sep="\t") 
#Get the number of columns in the matrix 
col = dim(data)[2] 
#Turn into logical matrix 
data[,2:col]=(data[,2:col]>0) 

#define % of training and test set 
train_pct = 0.8 
bound <- floor((nrow(data)*train_pct))  
#randomly permute rows 
data <- data[sample(nrow(data)), ] 
#get training data  
data.train <- data[1:bound, ] 
#get test data    
data.test <- data[(bound+1):nrow(data),] 

#Turn into transaction format 
trans.train = as(data.train,"transactions") 
trans.test = as(data.test,"transactions") 
#Create list of unique topics in 'topic=earn' format 
#Allows us to specify only the topic label as the right hand side 
uni_topics = paste0('topic=',unique(data[,1])) 

#Get assocation rules 
rules = apriori(trans.train, 
    parameter=list(support = 0.02,target= "rules", confidence = 0.5), 
    appearance = list(rhs = uni_topics,default='lhs')) 

#Sort association rules by confidence 
rules = sort(rules,by="confidence") 

#Predict the right hand side, topic= in trans.train based on the sorted rules 

一個例子交易:

> inspect(trans.train[3]) 

    items   transactionID 
[1] {topic=coffee,    
    current,     
    meet,      
    group,      
    statement,     
    quota,      
    organ,      
    brazil,      
    import,      
    around,      
    five,      
    intern,      
    produc,      
    coffe,      
    institut,     
    reduc,      
    intent,      
    consid}    8760 

一個例子規則:

> inspect(rules[1]) 
    lhs  rhs   support confidence lift  
[1] {qtli} => {topic=earn} 0.03761135 1   2.871171 

回答

1

我懷疑單詞和簡單的信心,關聯規則度量是預測文檔主題的理想選擇。

這就是說,嘗試使用is.subset函數。我無法在沒有.csv文件的情況下重現您的示例,但下面的代碼應根據最高可信度爲您提供trans.train[3]的預測主題。

# sort rules by conf (you already did that but for the sake of completeness) 
rules<-sort(rules, decreasing=TRUE, by="confidence") 

# find all rules whose lhs matches the training example 
rulesMatch <- is.subset([email protected],trans.train[3]) 

# subset all applicable rules 
applicable <- rules[rulesMatch==TRUE] 

# the first rule has the highest confidence since they are sorted 
prediction <- applicable[1] 
inspect([email protected]) 
+1

這很好,謝謝你的簡單解決方案。對於你的第一點,我正在研究如何將關聯規則與更優化的分類器(決策樹等)進行比較,因爲它能夠考慮預測變量之間的鏈接/依賴關係。正如預期的準確度(對於這個應用程序)更糟,但運行時間非常快! – Magic8ball

1

在它即將發佈的R包arulesCBA支持這種類型的功能,你應該還能再需要它的未來。

在當前的開發版本中,arulesCBA有一個名爲CBA_ruleset的函數,它接受一組有序的規則並返回一個CBA類對象。