微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

关联规则挖掘及R算法实现

原文地址:http://blog.csdn.net/sunbow0/article/details/41962185

关联规则挖掘及R算法实现

关联规则挖掘发现大量数据中项集之间有趣的关联或相关联系。如果两项或多项属性之间存在关联,那么其中一项的属性就可以依据其他属性值进行预测。它在数据挖掘中是一个重要的课题,最近几年已被业界所广泛研究。

关联规则挖掘的一个典型例子是购物篮分析。关联规则研究有助于发现交易数据库中不同商品(项)之间的联系,找出顾客购买行为模式,如购买了某一商品对购买其他商品的影响。分析结果可以应用于商品货架布局、货存安排以及根据购买模式对用户进行分类

最著名的关联规则是Apriori算法。关联规则挖掘问题可以分为两个子问题:第一步是找出事务数据库中所有大于等于用户指定的最小支持度的数据项集,也就是频繁项集;第二步是利用频繁项集生成所需要的关联规则,根据用户设定的最小置信度进行取舍,最后得到强关联规则。识别或发现所有频繁项目集市关联规则发现算法的核心。

1、关联规则的基本描述

1.1项与项集

这是一个集合的概念,在一篮子商品中的一件消费品即为一项(Item),则若干项的集合为项集,如{啤酒,尿布}构成一个二元项集。

1.2关联规则

一般记为的形式,X为先决条件,Y为相应的关联结果,用于表示数据内隐含的关联性。如:表示购买了尿布的消费者往往也会购买啤酒。

关联性强度如何,由三个概念——支持度、置信度、提升度来控制和评价。

 例:有10000个消费者购买了商品,其中购买尿布1000个,购买啤酒2000个,购买面包500个,同时购买尿布和面包800个,同时购买尿布和面包100个。

1.3支持度(Support)

支持度是指在所有项集中{X,Y}出现的可能性,即项集中同时含有X和Y的概率:

该指标作为建立强关联规则的第一个门槛,衡量了所考察关联规则在“量”上的多少。通过设定最小阈值(minsup),剔除“出镜率”较低的无意义规则,保留出现较为频繁的项集所隐含的规则。

设定最小阈值为5%,由于{尿布,啤酒}的支持度为800/10000=8%,满足基本输了要求,成为频繁项集,保留规则;而{尿布,面包}的支持度为100/10000=1%,被剔除。

1.4置信度(Confidence)

置信度表示在先决条件X发生的条件下,关联结果Y发生的概率:

这是生成强关联规则的第二个门槛,衡量了所考察的关联规则在“质”上的可靠性。相似的,我们需要对置信度设定最小阈值(mincon)来实现进一步筛选。

具体的,当设定置信度的最小阈值为70%时,置信度为800/1000=80%,而的置信度为800/2000=40%,被剔除。

1.5提升度(lift)

提升度表示在含有X的条件下同时含有Y的可能性与没有X这个条件下项集中含有Y的可能性之比:公式为confidence(artichok => cracker)/support(cracker) = 80%/50% = 1.6。该指标与置信度同样衡量规则的可靠性,可以看作是置信度的一种互补指标。

2、Apriori算法

2.1 Apriori算法基本思想

Apriori算法基本思想是通过对数据库的多次扫描来计算项集的支持度,发现所有的频繁项集从而生成关联规则。Apriori算法对数据集进行多次扫描。第一次扫描得到频繁1-项集的集合L1,第k(k>1)次扫描首先利用第(k-l)次扫描的结果Lk来产生候选k-项集的集合Ck,然后再扫描的过程中确定Ck中元素的支持度,最后再每一次扫描结束时计算频繁k-项集的集合Lk,算法当候选k-项集的集合Ck为空时结束。

2.2 Apriori算法产生频繁项集的过程

产生频繁项集的过程主要分为连接和剪枝两步:

①连接步。为找Lk,通过Lk-1与自身作连接产生候选k-项集的集合Ck。设和是Lk-1中的项集。记表示的第j个项。Apriori假定事务或项集中的项按字典次序排序。对于(k-1)项集,意味将项排序,使<  <…<。如果Lk-1的元素和的前(k-2)个对应项相等,则和可连接。即,如果(=)∩(=)∩…∩(=)∩(<)时,和可连接。条件<仅仅是保证不重复。连接和产生的结果项集为(,,…,,)。

②剪枝步。Apriori算法的性质可知,频繁k-项集的任何子集必须是频繁项集。由连接生成的集合Ck需要进行验证,去除不满足支持度的非频繁k-项集。

2.3 Apriori算法的主要步骤

①扫描全部数据,产生候选1-项集的集合C1

②根据最小支持度,由候选1-项集的集合C1产生频繁1-项集的集合L1

③对k>1,重复执行步骤④、⑤、⑥;④由Lk执行连接和剪枝操作,产生候选(k+l)-项集的集合Ck+1

⑤根据最小支持度,由候选(k+l)-项集的集合Ck+1,产生频繁(k+1)-项集的集合Lk+1

⑥若L≠Φ,则k=k+1,跳往步骤④;否则,跳往步骤⑦;⑦根据最小置信度,由频繁项集产生强关联规则,结束。

2.4 Apriori算法的举例

下图是一个数据库的事务列表,在数据库中有9笔交易,即|D|=9。每笔交易都用不同的TID作代表,交易中的项按字典序存放,下面描述一下Apriori算法寻找D中频繁项集的过程。

 

事务

商品ID的列表

T100

I1,I2,I5

T200

I2,I4

T300

I2,I3

T400

I1,I2,I4

T500

I1,I3

T600

I2,I3

T700

I1,I3

T800

I1,I2,I3,I5

T900

I1,I2,I3

设最小支持度计数为2,即min_ sup=2,利用Apriori算法产生候选项集及频繁项集的过程如下所示:

第一次扫描:

扫描数据库D获得每个候选项的计数:


由于最小事务支持数为2,没有删除任何项目。可以确定频繁1-项集的集合L1,它由具有最小支持度的候选1-项集组成。


第二次扫描:

为发现频繁2项集的集合L2,算法使用L1∞L1产生候选2项集的集合C2。在剪枝步没有候选从C2删除,因为这些候选的每个子集也是频繁的。


第三次扫描:

L2∞L2产生候选3项集的集合C3


候选3项集C3的产生详细地列表如下:

(a) 连接C3=L2∞L2

={{I1,I2},{I1,I3},{I1,I5},{I2,I3},{I2,I4},{I2,I5}} ∞

{{I1,I2},{I1,I3},{I1,I5},{I2,I3},{I2,I4},{I2,I5}}

={{I1,I2,I3},{I1,I2,I5},{I1,I3,I5},{I2,I3,I4},{I2,I3,I5},{I2,I4,I5}}

(b) 使用Apriori性质剪枝:频繁项集的所有非空子集也必须是频繁的。例{I1,I3,I5}的2项子集是{I1,I3},{I1,I5}和{I3,I5}。{I3,I5}不是L2的元素,因而不是频繁的。因此,从C3删除{I1,I3,I5}

(c) 这样,剪枝C3={{I1,I2,I3},{I1,I2,I5}}

第四次扫描:

算法使用L3∞L3产生候选4-项集的集合C4。L3∞L3={{I1,I2,I3,I5}},根据Apriori性质,因为它的子集{I2,I3,I5}不是频繁的,所以这个项集被删除。这样C4= Φ,因此算法终止,找出了所有的频繁项集。

 

2.5 实例2

  

 

3、用R语言进行关联分析

3.1 关联算法工具包

3.1.1 算法包:library(arules)

arules

Mining Association Rules and Frequent Itemsets

该包为关联规则及频繁项集的挖掘工具包

3.1.2 主要方法函数

1)  apriori

apriori

Mining Associations with Apriori

Apriori关联挖掘算法

 

apriori(data,parameter = NULL,appearance = NULL,control = NULL)

data:数据

parameter:设置参数,认情况下parameter=list(supp=0.1,conf=0.8,maxlen=10,minlen=1,target=”rules”)

supp:支持度(support)

conf:置信度(confidence)

maxlen,minlen:每个项集所含项数的最大最小值

target:“rules”或“frequentitemsets”(输出关联规则或者频繁项集)

使用实例:

例1:

rules <-apriori(click_detail,parameter =list(supp=0.01,conf=0.5,target="rules"))

 #求关联规则,支持度为1%,置信度为50%的关联规则。

例2:

rules.better <-apriori(titanic.raw,     parameter=list(minlen=20.0050.8),     appearance= list(rhs=c("Survived=No"="lhs"= list(verbose=F))

# appearance指定了右件必需是Survived项的两种情况,左件可以包含其它项集。minlen=2指定了项集中包含2个以上的项。算法处理的过程被压缩(简化)是通过verbose=F设置

 2)  eclat

eclat

Mining Associations with Eclat

Eclat关联挖掘算法

 eclat(data,control =NULL)

target:"frequent itemsets"、"maximally frequent itemsets"、"closedfrequent itemsets"

 使用实例:

frequentsets=eclat(Groceries,parameter=list(support=0.05,maxlen=10))  #求频繁项集  

3)  inspect

inspect

display Associations and Transactions in Readable Form

查看数据集或者结果集

 

inspect(x,...)

x:数据

...:额外参数

 

使用实例:

inspect(frequentsets[1:10])    #察看求得的频繁项集  
inspect(sort(frequentsets,by="support")[1:10])    #根据支持度对求得的频繁项集排序并察看(等价于inspect(sort(frequentsets)[1:10])
 
4)  subset

subset

Subsetting Itemsets,Rules and Transactions
求满足一定条件的子集/规则的筛选
用subset做规则的筛选,取"右手边"含有whole milk且lift大于1.2的规则 sub.rules=subset(rules,subset = rhs %in% "whole milk" &lift > 1.2)
 
subset(x,subset,...)
x:要取子集的对象
subset:条件逻辑表达式
 

x=subset(rules,subset=rhs%in%"whole milk"&lift>=1.2)    #求所需要的关联规则子集 ,其条件是在右件中包含milk并且提升度lift大于等于1.2的子集; 

5)  transactions
 

transactions

Binary Incidence Matrix for Transactions

交易数据集        

将数据转换为arules关联规则方法apriori/eclat方法可以处理的数据形式.交易数据。 

## example 1: creating transactions form a list

a_list <- list(
      c("a","b","c"),
      c("c","e"),"d","e")
      )
## set transaction names
names(a_list) <- paste("Tr",c(1:5),sep = "")
a_list
## coerce into transactions
trans <- as(a_list,"transactions")
## analyze transactions
summary(trans)
image(trans)
## example 2: creating transactions from a matrix
a_matrix <- matrix(
      c(1,1,255)">        1,255)">        0,1),ncol = 5)
## set dim names
dimnames(a_matrix) <-  list(
        c("a","c",255)">        paste("Tr",sep = ""))
a_matrix
## coerce
trans2 <-  as(a_matrix,255)">trans2
inspect(trans2)
## example 3: creating transactions from data.frame
a_df <- data.frame(
        age = as.factor(c(6,8,7,6,9,5)),255)">        grade = as.factor(c(1,3,4,1)))  
## note: all attributes have to be factors
a_df
trans3 <- as(a_df,"transactions") 
image(trans3)
## example 4: Creating from data.frame with NA
a_df2 <- sample(c(LETTERS[1:5],NA),10,TRUE)
a_df2 <- data.frame(X = a_df2,Y = sample(a_df2))
a_df2
trans3 <- as(a_df2,255)">trans3
as(trans3,"data.frame")
## example 5: creating transactions from a data.frame with 
## transaction IDs and items 
a_df3 <- data.frame(TID = c(1,2,3),item=c("a","a","b"))
a_df3
trans4 <- as(split(a_df3[,"item"],a_df3[,"TID"]),255)">trans4
LIST(trans4)
6)  itemFrequencyPlot 
itemFrequencyPlot 
Creating a Item Frequencies/Support Bar Plot

画频繁项的图 

使用实例: 

itemFrequencyPlot(x,...) 

## the followingexample compares the item frequencies

## of people witha large income (Boxes) with the average in the data set

Adult.largeIncome<- Adult[Adult %in%

               "income=large"] 

## simple plot

itemFrequencyPlot(Adult.largeIncome)

## plot with theaverages of the population plotted as a line

## (for first 72variables/items)

itemFrequencyPlot(Adult.largeIncome[,1:72],

               population = Adult[,1:72]) 

## plot lift ratio(frequency in x / frequency in population)

## for items witha support of 20% in the population

itemFrequencyPlot(Adult.largeIncome,51); font-family:Arial; font-size:14px; line-height:26px">         population = Adult,support = 0.2,51); font-family:Arial; font-size:14px; line-height:26px">                lift = TRUE,horiz = TRUE)

7)  write

 

write

Writes transactions or associations to disk

数据/结果保存

 write(x,file ="",...)

 使用实例:

 ## write theformated transactions to screen (basket format)

write(head(Epub))

 ## write theformated transactions to screen (single format)

write(head(Epub),format="single")

 ## write the formatedresult to file in CSV format

write(Epub,file ="data.csv",format="single",quote=TRUE,51); font-family:Arial; font-size:14px; line-height:26px">     sep = ",",col.names = NA)

 ## write rules inCSV format

rules <-apriori(Epub,parameter=list(support=0.0005,conf=0.8))

write(rules,file= "data.csv",sep = ",51); font-family:Arial; font-size:14px; line-height:26px">  unlink("data.csv")# tidy up

3.1.3 扩展方法包(arulesViz):

参照此帖子:

http://www.klshu.com/1202.html

http://www.klshu.com/1175.html  

3.2 关联规则R语言Demo

3.2.1 关联挖掘流程

#0、 加载包

library(arules)

library("arulesViz") 

# 1、加载数据

x <- readLines("user2items.csv")

x <- readLines("retail.dat")

读取csv、txt、dat等文件,需要对数据格式进行处理

如果数据量大,采用下面方法

con <- file("e:/data.txt","r")
line=readLines(con,n=1)
while( length(line) != 0 ) {
     
数据处理…….    line=readLines(con,239)">}
close(con) 

# 2、数据转换transactions格式的交易数据

trans<- as(data,"transactions") 

# 3、查看数据

inspect(trans[1:5]) 

# 4、频繁项集挖掘

frequentsets<- eclat(trans,parameter=list(support=0.005,minlen=2))#方法1

frequentsets2<-

apriori(trans,parameter=list(supp=0.005,minlen=2,target="frequentitemsets"))#方法

#5、求关联规则

rules <- apriori(trans,confidence=0.4,minlen=2)) 

#6、指定规则筛选

sub.rules2=subset(rules,subset = rhs %pin% "2" &lift > 10) 

#7、画图

plot(rules) 

#8、文件保存

df.rules=as(rules,"data.frame")

write.csv(df.rules,"GeroRules.csv")

先将数据转换成frame格式,然后写入文件。 

3.2.2 关联挖掘实现

setwd("E:\\Rwork\\fpg")

library(arules) 

#1、读入数据及格式处理

data <- list()

x <-readLines("user2items.csv")

for(n in 1:length(x)){data[n]<-strsplit(x[n],")}

#x <- readLines("retail.dat")

#for(n in 1:length(x)){data[n]<-strsplit(x[n],"\\s")} 

#2、数据转换成transactions格式

trans <-as(data,51); font-family:Arial; font-size:14px; line-height:26px"> #3、数据查看

inspect(trans[1:5]) 

#4、频繁项集挖掘

frequentsets <-eclat(trans,51); font-family:Arial; font-size:14px; line-height:26px"> inspect(sort(frequentsets,by="support")[1:10])#排序后查看 

frequentsets2 <-apriori(trans,target="frequentitemsets"))#方法2

inspect(sort(frequentsets2,51); font-family:Arial; font-size:14px; line-height:26px"> #这里如果支持度选的比较大,也许没有10这么多,这里就不能写[1:10].

#inspect(frequentsets[1:10])#查看频繁项集

#多选几次支持度阈值,更好的发现频繁模式。 

#5、求关联规则

rules <-apriori(trans,minlen=2))

inspect(sort(rules,by="support")[1:5])#排序后查看

summary(rules) 

#6、指定规则筛选

sub.rules=subset(rules,subset = rhs %in%"29099" &lift > 10)

inspect(sort(sub.rules,by="support"))#排序后查看

sub.rules2=subset(rules,subset = rhs %pin%"2" &lift > 10)

inspect(sort(sub.rules2,by="support"))#排序后查看 

#7、画图

library("arulesViz")

plot(rules) 

#8、文件保存

df.rules=as(rules,51); font-family:Arial; font-size:14px; line-height:26px"> write.csv(df.rules,"GeroRules.csv") 

3.2.3 主要参数设置

1)原始文件读入及数据转换

主要采用readLines方法、字符分割办法,以及as(a_matrix,"transactions")方法。 

2)关联挖掘参数

Parameter的支持度、置信度、项集长度;

Appearance的限定条件; 

3)指定规则筛选结果

Subset参数设置规则; 

4)结果展示及保存文件

Plot参数设置;write.csv函数写入文件 

5)arules包方法

Arules是一个成熟的关联及频繁项集的挖掘算法工具包,其Arules方法比较丰富,将近有100个方法,具体查R的帮助文档。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐