關(guān)聯(lián)分析摘悴,也稱購物籃分析聂渊,本文目的:
基于訂單表檐涝,用最少的python代碼完成數(shù)據(jù)整合及關(guān)聯(lián)分析
文中所用數(shù)據(jù)下載地址:
鏈接:https://pan.baidu.com/s/1GPKpw4oFJL-4ua1VuMW6yA
密碼:ub6e
使用Python Anaconda集成數(shù)據(jù)分析環(huán)境架馋,下載mlxtend機(jī)器學(xué)習(xí)包窟她。包挺好,文檔不太完善漂问。
閑話少說赖瞒,開始吧:
Step 1. 載入包
import pandas as pd
from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import association_rules
Step 2. 讀取原始數(shù)據(jù)包
df = pd.read_excel('./Online Retail.xlsx')
df.head()
Step 3. 數(shù)據(jù)預(yù)處理——選定樣本
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字段去除首尾空格,刪除發(fā)票ID"InvoiceNo"為空的數(shù)據(jù)記錄蚤假,將發(fā)票ID"InvoiceNo"字段轉(zhuǎn)為字符型栏饮,刪除發(fā)票ID"InvoiceNo"不包含“C”的記錄
Step 4. 數(shù)據(jù)預(yù)處理——處理為購物籃數(shù)據(jù)集
方法一:使用pivot_table函數(shù)
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選擇法國(guó)地區(qū)數(shù)據(jù),basket2為德國(guó)地區(qū)數(shù)據(jù)磷仰,不要忘記fillna(0)袍嬉,將空值轉(zhuǎn)為0,算法包需要灶平。
用到的都是pandas數(shù)據(jù)整合基礎(chǔ)功能伺通,參考網(wǎng)址:
http://pandas.pydata.org/pandas-docs/stable/10min.html
整合后數(shù)據(jù)差不多長(zhǎng)這樣:
列名為商品名稱,每一行為一個(gè)訂單逢享。
Step 5. 將購物數(shù)量轉(zhuǎn)為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函數(shù)罐监,將encode_units在basket中的每個(gè)單元格執(zhí)行并返回
刪除購物籃中的郵費(fèi)項(xiàng)(POSTAGE)
Step 6. 使用算法包進(jìn)行關(guān)聯(lián)規(guī)則運(yùn)算
frequent_itemsets = apriori(basket_sets2, min_support=0.05, use_colnames=True)
rules = association_rules(frequent_itemsets, metric="lift", min_threshold=1)
frequent_itemsets 為頻繁項(xiàng)集:
Support列為支持度,即 項(xiàng)集發(fā)生頻率/總訂單量
rules為最終關(guān)聯(lián)規(guī)則結(jié)果表:
antecedants前項(xiàng)集瞒爬,consequents后項(xiàng)集弓柱,support支持度,confidence置信度侧但,lift提升度矢空。
參考:http://www.360doc.com/content/15/0611/19/25802092_477451393.shtml
Final Step. 結(jié)果檢視
rules[ (rules['lift'] >= 6) &
(rules['confidence'] >= 0.8) ]\
.sort_values("lift",ascending = False)
選取置信度(confidence)大于0.8且提升度(lift)大于5的規(guī)則,按lift降序排序
結(jié)論參考理論知識(shí)禀横,自行解讀 :)
歡迎交流屁药,謝謝。