美文网首页呆鸟的Python数据分析我爱编程
Python 极简关联分析(购物篮分析)

Python 极简关联分析(购物篮分析)

作者: fycoopery | 来源:发表于2018-03-18 17:35 被阅读513次

关联分析,也称购物篮分析,本文目的:

基于订单表,用最少的python代码完成数据整合及关联分析

文中所用数据下载地址:

链接:https://pan.baidu.com/s/1GPKpw4oFJL-4ua1VuMW6yA
密码:ub6e

使用Python Anaconda集成数据分析环境,下载mlxtend机器学习包。包挺好,文档不太完善。

闲话少说,开始吧:

Step 1. 载入包

import pandas as pd
from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import association_rules

Step 2. 读取原始数据包

df = pd.read_excel('./Online Retail.xlsx')
df.head()
image.png

Step 3. 数据预处理——选定样本

df['Description'] = df['Description'].str.strip()
df.dropna(axis=0, subset=['InvoiceNo'], inplace=True)
df['InvoiceNo'] = df['InvoiceNo'].astype('str')
df = df[~df['InvoiceNo'].str.contains('C')]

描述Description字段去除首尾空格,删除发票ID"InvoiceNo"为空的数据记录,将发票ID"InvoiceNo"字段转为字符型,删除发票ID"InvoiceNo"不包含“C”的记录

Step 4. 数据预处理——处理为购物篮数据集

方法一:使用pivot_table函数
import numpy as np
basket = df[df['Country'] =="France"].pivot_table(columns = "Description",index="InvoiceNo",
              values="Quantity",aggfunc=np.sum).fillna(0)
basket.head(20)
方法二:groupby后unstack
basket2 = (df[df['Country'] =="Germany"]
          .groupby(['InvoiceNo', 'Description'])['Quantity']
          .sum().unstack().reset_index().fillna(0)
          .set_index('InvoiceNo'))

basket选择法国地区数据,basket2为德国地区数据,不要忘记fillna(0),将空值转为0,算法包需要。
用到的都是pandas数据整合基础功能,参考网址:
http://pandas.pydata.org/pandas-docs/stable/10min.html

整合后数据差不多长这样:


image.png

列名为商品名称,每一行为一个订单。

Step 5. 将购物数量转为0/1变量

0:此订单未购买包含列名

1:此订单购买了列名商品

def encode_units(x):
    if x <= 0:
        return 0
    if x >= 1:
        return 1


basket_sets = basket.applymap(encode_units)
basket_sets.drop('POSTAGE', inplace=True, axis=1)

使用dataframe的applymap函数,将encode_units在basket中的每个单元格执行并返回

删除购物篮中的邮费项(POSTAGE)

Step 6. 使用算法包进行关联规则运算

frequent_itemsets = apriori(basket_sets2, min_support=0.05, use_colnames=True)
rules = association_rules(frequent_itemsets, metric="lift", min_threshold=1)

frequent_itemsets 为频繁项集:

image.png

Support列为支持度,即 项集发生频率/总订单量

rules为最终关联规则结果表:

image.png

antecedants前项集,consequents后项集,support支持度,confidence置信度,lift提升度。

参考:http://www.360doc.com/content/15/0611/19/25802092_477451393.shtml

Final Step. 结果检视

rules[ (rules['lift'] >= 6) &
       (rules['confidence'] >= 0.8) ]\
.sort_values("lift",ascending = False)

选取置信度(confidence)大于0.8且提升度(lift)大于5的规则,按lift降序排序

image.png

结论参考理论知识,自行解读 :)
欢迎交流,谢谢。

参考资料:http://pbpython.com/market-basket-analysis.html

相关文章

网友评论

  • 00c68b8b3bff:您好,数据集没有了,可否发一份到我的邮箱1650752408@qq.com,谢谢给常感谢
    00c68b8b3bff:不用了,谢谢,在你给的英文资料里找到了

本文标题:Python 极简关联分析(购物篮分析)

本文链接:https://www.haomeiwen.com/subject/qzneqftx.html