首先当然要配置r语言环境变量什么的
D:\R-3.5.1\bin\x64;
D:\R-3.5.1\bin\x64\R.dll;
D:\R-3.5.1;
D:\ProgramData\Anaconda3\Lib\site-packages\rpy2;
本来用python也可以实现关联规则,虽然没包,但是可视化挺麻烦的
View Code
之后还是用r吧,要下载rpy2,见https://www.cnblogs.com/caiyishuai/p/9520214.html
还要下载两个R的包
import rpy2.robjects as robjects
b=('''
install.packages("arules")
install.packages("arulesViz")
''')
robjects.r(b)
然后就是主代码了
import rpy2.robjects as robjects
a=('''Encoding("UTF-8")
setwd("F:/goverment/Aprior")
all_data<-read.csv("F:/goverment/Aprior/NewData.csv",header = T,#将数据转化为因子型
colClasses=c("factor","factor","factor","factor","factor","factor","factor","factor","factor","factor","factor","factor"))
library(arules)
rule=apriori(data=all_data[,c(1,4,5,6,7,8,9,10,12)], parameter = list(support=0.05,confidence=0.7,minlen=2,maxlen=10))
''')
robjects.r(a)
robjects.r('''
rule.subset<-subset(rule,lift>1)
#inspect(rule.subset)
rules.sorted<-sort(rule.subset,by="lift")
subset.matrix<-is.subset(rules.sorted,rules.sorted)
lower.tri(subset.matrix,diag=T)
subset.matrix[lower.tri(subset.matrix,diag = T)]<-NA
redundant<-colSums(subset.matrix,na.rm = T)>=1 #这五条就是去冗余(感兴趣可以去网上搜),我虽然这里写了,但我没有去冗余,我的去了以后一个规则都没了
which(redundant)
rules.pruned<-rules.sorted[!redundant]
#inspect(rules.pruned) #输出去冗余后的规则
''')
c=('''
library(arulesViz)#掉包
jpeg(file="plot1.jpg")
#inspect(rule.subset)
plt<-plot(rule.subset,shading = "lift")#画散点图
dev.off()
subrules<-head(sort(rule.subset,by="lift"),50)
#jpeg(file="plot2.jpg")
plot(subrules,method = "graph")#画图
#dev.off()
rule.sorted <- sort(rule.subset, decreasing=TRUE, by="lift") #按提升度排序
rules.write<-as(rule.sorted,"data.frame") #将规则转化为data类型
write.csv(rules.write,"F:/goverment/Aprior/NewRules.csv",fileEncoding="UTF-8")
''')
robjects.r(c)
#取出保存的规则,放到一个列表中
from pandas import read_csv
data_set = read_csv("F:/goverment/Aprior/NewRules.csv")
data = data_set.values[:, :]
rul = []
for line in data:
ls = []
for j in line:
try :
j=float(j)
if j>0 and j<=1:
j=str(round(j*100,2))+"%"
ls.append(j)
else:
ls.append(round(j,2))
except:
ls.append(j)
rul.append(ls)
for line in rul:
print(line)