Apriori算法学习笔记(三)
Apriori算法的Python实现
from __future__ import print_function
import pandas as pd
def find_freq_set(x, ms):
x = list(map(lambda i: sorted(i.split(ms)), x))
l = len(x[0])
r = []
for i in range(len(x)):
for j in range(i, len(x)):
if x[i][:l - 1] == x[j][:l - 1] and x[i][l - 1] != x[j][l - 1]:
r.append(x[i][:l - 1] + sorted([x[j][l - 1], x[i][l - 1]]))
return r
def find_rule(data, support, confidence, ms=u'--'):
result = pd.DataFrame(index=['support', 'confidence'])
support_series = 1.0 * data.sum() / len(data)
column = list(support_series[support_series > support].index)
k = 0
while len(column) > 1:
k = k + 1
column = find_freq_set(column, ms)
sf = lambda i: data[i].prod(axis=1, numeric_only=True)
data_2 = pd.DataFrame(list(map(sf, column)), index=[ms.join(i) for i in column]).T
support_series_2 = 1.0 * data_2[[ms.join(i) for i in column]].sum() / len(data)
column = list(support_series_2[support_series_2 > support].index)
support_series = support_series.append(support_series_2)
column2 = []
for i in column:
i = i.split(ms)
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:
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
result[i]['confidence'] = cofidence_series[i]
result[i]['support'] = support_series[ms.join(sorted(i.split(ms)))]
result = result.T.sort(['confidence', 'support'], ascending=False)
return result