apriori算法代码python_Apriori算法原理及Python代码

一、Apriori算法原理

参考:Python --深入浅出Apriori关联分析算法(一)​www.cnblogs.com4313898a8ae40d91130a538e74b17296.png

二、在Python中使用Apriori算法

查看Apriori算法的帮助文档:

from mlxtend.frequent_patterns import apriori

help(apriori)

Help on function apriori in module mlxtend.frequent_patterns.apriori:

apriori(df, min_support=0.5, use_colnames=False, max_len=None, verbose=0, low_memory=False)

Get frequent itemsets from a one-hot DataFrame

Parameters

-----------

df : pandas DataFrame

pandas DataFrame the encoded format. Also supports

DataFrames with sparse data;

Please note that the old pandas SparseDataFrame format

is no longer supported in mlxtend >= 0.17.2.

The allowed values are either 0/1 or True/False.

For example,

#apriori算法对输入数据类型有特殊要求!

#需要是数据框格式,并且数据要进行one-hot编码转换,转换后商品名称为列名,值为True或False。

#每一行记录代表一个顾客一次购物记录。

#第0条记录为[Apple,Beer,Chicken,Rice],第1条记录为[Apple,Beer,Rice],以此类推。

```

Apple Bananas Beer Chicken Milk Rice

0 True False True True False True

1 True False True False False True

2 True False True False False False

3 True True False False False False

4 False False True True True True

5 False False True False True True

6 False False True False True False

7 True True False False False False

```

min_support : float (default: 0.5)#最小支持度

A float between 0 and 1 for minumum support of the itemsets returned.

The support is computed as the fraction

`transactions_where_item(s)_occur / total_transactions`.

use_colnames : bool (default: False)

#设置为True,则返回的关联规则、频繁项集会使用商品名称,而不是商品所在列的索引值

If `True`, uses the DataFrames' column names in the returned DataFrame

instead of column indices.

max_len : int (default: None)

Maximum length of the itemsets generated. If `None` (default) all

possible itemsets lengths (under the apriori condition) are evaluated.

verbose : int (default: 0)

Shows the number of iterations if >= 1 and `low_memory` is `True`. If

>=1 and `low_memory` is `False`, shows the number of combinations.

low_memory : bool (default: False)

If `True`, uses an iterator to search for combinations above

`min_support`.

Note that while `low_memory=True` should only be used for large dataset

if memory resources are limited, because this implementation is approx.

3-6x slower than the default.

Returns

-----------

pandas DataFrame with columns ['support', 'itemsets'] of all itemsets

that are >= `min_support` and < than `max_len`

(if `max_len` is not None).

Each itemset in the 'itemsets' column is of type `frozenset`,

which is a Python built-in type that behaves similarly to

sets except that it is immutable.

练习数据集:

提取码: 6mbg

部分数据截图:

导入数据:

import pandas as pd

path = 'C:\\Users\\Cara\\Desktop\\store_data.csv'

records = pd.read_csv(path,header=None,encoding='utf-8')

print(records)

结果如下:

使用TransactionEncoder对交易数据进行one-hot编码:

先查看TransactionEncoder的帮助文档:

from mlxtend.preprocessing import TransactionEncoder

... help(TransactionEncoder)

...

Help on class TransactionEncoder in module mlxtend.preprocessing.transactionencoder:

class TransactionEncoder(sklearn.base.BaseEstimator, sklearn.base.TransformerMixin)

| Encoder class for transaction data in Python lists

|

| Parameters

| ------------<

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Apriori算法是一种常用的关联规则挖掘算法,它可以用来发现数据集中的频繁项集。Apriori算法的基本思想是通过迭代的方式,逐层筛选出频繁项集。 Apriori算法原理: 1. 对数据集中的每个项进行计数,得到每个项的支持度; 2. 根据支持度,得到满足最小支持度要求的频繁项集; 3. 根据频繁项集,生成候选项集; 4. 根据候选项集,计算支持度,得到满足最小支持度要求的频繁项集; 5. 重复步骤3~4,直到没有满足最小支持度要求的频繁项集为止。 下面是Apriori算法Python代码实现: ```python # 计算支持度 def support_count(data, itemset, min_support): count = 0 for d in data: if set(itemset).issubset(set(d)): count += 1 support = float(count) / len(data) return support >= min_support, count # 生成候选项集 def candidate_itemsets(itemsets, k): candidate = [] for i in range(len(itemsets)): for j in range(i + 1, len(itemsets)): l1 = list(itemsets[i])[:k - 2] l2 = list(itemsets[j])[:k - 2] l1.sort() l2.sort() if l1 == l2: candidate.append(itemsets[i] | itemsets[j]) return candidate # Apriori算法主函数 def apriori(data, min_support): itemsets = [] for d in data: for item in d: if not {item} in itemsets: itemsets.append({item}) itemsets.sort() freq_itemsets = [] k = 2 while True: candidate = candidate_itemsets(itemsets, k) freq_itemset = [] for c in candidate: is_freq, count = support_count(data, c, min_support) if is_freq: freq_itemset.append((c, count)) freq_itemsets += freq_itemset if len(freq_itemset) == 0: break itemsets = [f[0] for f in freq_itemset] k += 1 return freq_itemsets ``` 以上是Apriori算法Python代码实现,使用时只需要传入数据集和最小支持度即可得到频繁项集。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值