在Python pandas中实现Apriori算法的最佳方法

在pandas中实现Apriori算法的最佳方法是什么?我目前在使用for循环提取模式时遇到了困难。从for循环开始的部分都不起作用。是否有在pandas中使用向量化方法来实现这一点的方法?

import pandas as pdimport numpy as nptrans=pd.read_table('output.txt', header=None,index_col=0)def apriori(trans, support=4):    ts=pd.get_dummies(trans.unstack().dropna()).groupby(level=1).sum()    #用户输入    collen, rowlen  =ts.shape    #项目最大长度    tssum=ts.sum(axis=1)    maxlen=tssum.loc[tssum.idxmax()]    items=list(ts.columns)    results=[]    #遍历项目    for c in  range(1, maxlen):        #生成模式        pattern=[]        for n in  len(pattern):            #计算支持度            pattern=['supp']=pattern.sum/rowlen            #按支持度级别过滤            Condit=pattern['supp']> support            pattern=pattern[Condit]            results.append(pattern)   return resultsresults =apriori(trans)print results

当我插入支持度为3的数据时

        a  b  c  d  e0                    11      1  1  1  0  0666     1  0  0  1  110101   0  1  1  1  01010    1  1  1  1  0414147  0  1  1  0  010101   1  1  0  1  01242    0  0  0  1  1101     1  1  1  1  0411     0  0  1  1  1444     1  1  1  0  0

输出应该类似于

   Pattern   support    a         6    b         7    c         7    d         7    e         3    a,b       5    a,c       4    a,d       4

回答:

假设我理解了你的需求,也许

from itertools import combinationsdef get_support(df):    pp = []    for cnum in range(1, len(df.columns)+1):        for cols in combinations(df, cnum):            s = df[list(cols)].all(axis=1).sum()            pp.append([",".join(cols), s])    sdf = pd.DataFrame(pp, columns=["Pattern", "Support"])    return sdf

可以帮助你开始:

>>> s = get_support(df)>>> s[s.Support >= 3]   Pattern  Support0        a        61        b        72        c        73        d        74        e        35      a,b        56      a,c        47      a,d        49      b,c        610     b,d        412     c,d        414     d,e        315   a,b,c        416   a,b,d        321   b,c,d        3[15 rows x 2 columns]

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注