大資料分析 - 關聯規則



I = i1, i2, ..., in是一組n個稱為專案的二元屬性。設D = t1, t2, ..., tm是一組稱為資料庫的事務。D中的每個事務都有一個唯一的事務ID,幷包含I中專案的子集。規則定義為X ⇒ Y的形式蘊涵,其中X, Y ⊆ I且X ∩ Y = ∅。

專案集X和Y分別稱為規則的前件(左手側或LHS)和後件(右手側或RHS)。

為了說明這些概念,我們使用超市領域的一個小例子。專案集為I = {牛奶,麵包,黃油,啤酒},包含專案的 小型資料庫如下表所示。

事務ID 專案
1 牛奶,麵包
2 麵包,黃油
3 啤酒
4 牛奶,麵包,黃油
5 麵包,黃油

超市的一個示例規則可以是{牛奶,麵包} ⇒ {黃油},這意味著如果購買牛奶和麵包,顧客也會購買黃油。為了從所有可能的規則集中選擇有趣的規則,可以使用對各種顯著性和興趣度量的約束。最著名的約束是對支援度和置信度的最小閾值。

專案集X的支援度supp(X)定義為資料集中包含該專案集的事務的比例。在表1的示例資料庫中,專案集{牛奶,麵包}的支援度為2/5 = 0.4,因為它出現在40%的事務中(5個事務中的2個)。尋找頻繁專案集可以看作是無監督學習問題的簡化。

規則的置信度定義為conf(X ⇒ Y ) = supp(X ∪ Y )/supp(X)。例如,規則{牛奶,麵包} ⇒ {黃油}在表1的資料庫中的置信度為0.2/0.4 = 0.5,這意味著對於包含牛奶和麵包的50%的事務,該規則是正確的。置信度可以解釋為機率P(Y|X)的估計值,即在事務也包含LHS的條件下,在事務中找到規則RHS的機率。

在位於bda/part3/apriori.R中的指令碼中,可以找到實現Apriori演算法的程式碼。

# Load the library for doing association rules
# install.packages(’arules’) 
library(arules)  

# Data preprocessing 
data("AdultUCI") 
AdultUCI[1:2,]  
AdultUCI[["fnlwgt"]] <- NULL 
AdultUCI[["education-num"]] <- NULL  

AdultUCI[[ "age"]] <- ordered(cut(AdultUCI[[ "age"]], c(15,25,45,65,100)), 
   labels = c("Young", "Middle-aged", "Senior", "Old")) 
AdultUCI[[ "hours-per-week"]] <- ordered(cut(AdultUCI[[ "hours-per-week"]], 
   c(0,25,40,60,168)), labels = c("Part-time", "Full-time", "Over-time", "Workaholic")) 
AdultUCI[[ "capital-gain"]] <- ordered(cut(AdultUCI[[ "capital-gain"]], 
   c(-Inf,0,median(AdultUCI[[ "capital-gain"]][AdultUCI[[ "capitalgain"]]>0]),Inf)), 
   labels = c("None", "Low", "High")) 
AdultUCI[[ "capital-loss"]] <- ordered(cut(AdultUCI[[ "capital-loss"]], 
   c(-Inf,0, median(AdultUCI[[ "capital-loss"]][AdultUCI[[ "capitalloss"]]>0]),Inf)), 
   labels = c("none", "low", "high"))

為了使用Apriori演算法生成規則,我們需要建立一個事務矩陣。以下程式碼顯示瞭如何在R中執行此操作。

# Convert the data into a transactions format
Adult <- as(AdultUCI, "transactions") 
Adult 
# transactions in sparse format with 
# 48842 transactions (rows) and 
# 115 items (columns)  

summary(Adult)  
# Plot frequent item-sets 
itemFrequencyPlot(Adult, support = 0.1, cex.names = 0.8)  

# generate rules 
min_support = 0.01 
confidence = 0.6 
rules <- apriori(Adult, parameter = list(support = min_support, confidence = confidence))

rules 
inspect(rules[100:110, ]) 
# lhs                             rhs                      support     confidence  lift
# {occupation = Farming-fishing} => {sex = Male}        0.02856148  0.9362416   1.4005486
# {occupation = Farming-fishing} => {race = White}      0.02831579  0.9281879   1.0855456
# {occupation = Farming-fishing} => {native-country     0.02671881  0.8758389   0.9759474
                                       = United-States} 
廣告
© . All rights reserved.