设 I = i 1 ,i 2 ,...,i n 是一组n二进制属性称为项目.设 D = t 1 ,t 2 ,...,t m 是一组称为数据库. D中的每个事务都有一个唯一的事务ID,并包含I中项目的子集.规则被定义为X&rArr形式的含义; Y在哪里X,Y⊆我和X∩ Y =∅.
项目组(对于短项目集合)X和Y称为先行(左手边或LHS)和后续(右手边)或规则的RHS.
为了说明这些概念,我们使用超市域中的一个小例子.这组项目是I = {牛奶,面包,黄油,啤酒},下表中显示了一个包含这些项目的小数据库.
交易ID | 项目 |
---|---|
1 | 牛奶,面包 |
2 | 面包,黄油 |
3 | 啤酒 |
4 | 牛奶,面包,黄油 |
5 | 面包,黄油 |
一个例子超市的规则可以是{milk,bread}⇒ {butter}意思是如果买了牛奶和面包,顾客也会买黄油.为了从所有可能规则的集合中选择有趣的规则,可以使用对各种重要性和兴趣度量的约束.最着名的约束是支持和置信度的最小阈值.
项目集X的支持supp(X)被定义为包含数据集的数据集中的事务的比例.项目集.在表1中的示例数据库中,项目集{milk,bread}具有2/5 = 0.4的支持,因为它发生在所有事务的40%中(5个事务中的2个).找到频繁的项目集可以看作是无监督学习问题的简化.
规则的置信度定义为conf(X⇒ Y)= supp(X∪ Y)/栓剂(X).例如,规则{milk,bread}⇒ {butter}在表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 formatAdult <- 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}