在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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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