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