import pandas as pd
from apriori_new import * #導(dǎo)入自行編寫的apriori函數(shù)
import time #導(dǎo)入時間庫用來計(jì)算用時
import re
import random
import pandas as pd
# 自定義關(guān)聯(lián)規(guī)則算法
def connect_string(x, ms):
x = list(map(lambda i: sorted(i.split(ms)), x))
l = len(x[0])
r = []
# 生成二項(xiàng)集
for i in range(len(x)):
for j in range(i, len(x)):
# if x[i][l-1] != x[j][l-1]:
if x[i][:l - 1] == x[j][:l - 1] and x[i][l - 1] != x[j][
l - 1]: # 判斷數(shù)字和字母異同,初次取字母數(shù)字不全相同(即不同癥狀(字母),或同一證型程度不同(數(shù)字))
r.append(x[i][:l - 1] + sorted([x[j][l - 1], x[i][l - 1]]))
return r
# 尋找關(guān)聯(lián)規(guī)則的函數(shù)
def find_rule(d, support, confidence, ms=u'--'):
result = pd.DataFrame(index=['support', 'confidence']) # 定義輸出結(jié)果
support_series = 1.0 * d.sum() / len(d) # 支持度序列
column = list(support_series[support_series > support].index) # 初步根據(jù)支持度篩選,符合條件支持度,共 276個index證型
k = 0
while len(column) > 1: # 隨著項(xiàng)集元素增多 可計(jì)算的column(滿足條件支持度的index)會被窮盡,隨著證型增多,之間的關(guān)系會越來越不明顯,(同時發(fā)生可能性是小概率了)
k = k + 1
print(u'\n正在進(jìn)行第%s次搜索...' % k)
column = connect_string(column, ms)
print(u'數(shù)目:%s...' % len(column))
sf = lambda i: d[i].prod(axis=1, numeric_only=True) # 新一批支持度的計(jì)算函數(shù)
len(d)
# 創(chuàng)建連接數(shù)據(jù),這一步耗時、耗內(nèi)存最嚴(yán)重。當(dāng)數(shù)據(jù)集較大時,可以考慮并行運(yùn)算優(yōu)化。
# 依次對column每個元素(如[['A1', 'A2'], ['A1', 'A3']]中的['A1', 'A2'])運(yùn)算,計(jì)算data_model_中對應(yīng)該行的乘積,930個,若['A1', 'A2']二者同時發(fā)生為1則此行積為1
d_2 = pd.DataFrame(list(map(sf, column)),index=[ms.join(i) for i in column]).T # list(map(sf,column)) 276X930 index 276
support_series_2 = 1.0 * d_2[[ms.join(i) for i in column]].sum() / len(d) # 計(jì)算連接后的支持度
column = list(support_series_2[support_series_2 > support].index) # 新一輪支持度篩選
support_series = support_series.append(support_series_2)
column2 = []
for i in column: # 遍歷可能的推理,如{A,B,C}究竟是A+B-->C還是B+C-->A還是C+A-->B?
i = i.split(ms) # 由'A1--B1' 轉(zhuǎn)化為 ['A1', 'B1']
for j in range(len(i)): #
column2.append(i[:j] + i[j + 1:] + i[j:j + 1])
cofidence_series = pd.Series(index=[ms.join(i) for i in column2]) # 定義置信度序列
for i in column2: # 計(jì)算置信度序列 如i為['B1', 'A1']
# i置信度計(jì)算:i的支持度除以第一個證型的支持度,表示第一個發(fā)生第二個發(fā)生的概率
cofidence_series[ms.join(i)] = support_series[ms.join(sorted(i))] / support_series[ms.join(i[:len(i) - 1])]
for i in cofidence_series[cofidence_series > confidence].index: # 置信度篩選
result[i] = 0.0 # B1--A1 0.330409 A1--B1 0.470833,絕大部分是要剔除掉的,初次全剔除
result[i]['confidence'] = cofidence_series[i]
result[i]['support'] = support_series[ms.join(sorted(i.split(ms)))]
result = result.T.sort_values(by=['confidence', 'support'],ascending=False) # 結(jié)果整理,輸出,先按confidence升序,再在confidence內(nèi)部按support升序,默認(rèn)升序,此處降序
return result
關(guān)聯(lián)規(guī)則應(yīng)用舉例
sku_list = [
'0000001','0000002','0000003','0000004','0000005',
'0000006','0000007','0000008','0000009','0000010',
'0000011','0000012','0000013','0000014','0000015',
'0000016','0000017','0000018','0000019','0000020',
'A0000001','A0000002','A0000003','A0000004','A0000005',
'A0000006','A0000007','A0000008','A0000009','A0000010',
'A0000011','A0000012','A0000013','A0000014','A0000015',
'A0000016','A0000017','A0000018','A0000019','A0000020',
]
# 隨機(jī)抽取數(shù)據(jù)生成列表
mat = [ random.sample(sku_list, random.randint(2,5)) for i in range(100)]
data = pd.DataFrame(mat,columns=["A","B","C","D","E"])
data = pd.get_dummies(data) # 轉(zhuǎn)換類別變量矩陣
data = data.fillna(0)