python库中如何调用FP-growth
时间: 2023-07-04 13:19:34 浏览: 88
Python中可以使用`mlxtend`库中的`fpgrowth`函数调用FP-growth算法,该函数可以根据给定的最小支持度和数据集来构建频繁项集树,然后从该树中挖掘频繁项集。具体来说,以下是使用`mlxtend.frequent_patterns.fpgrowth()`函数调用FP-growth算法来挖掘频繁项集的示例代码:
```python
from mlxtend.frequent_patterns import fpgrowth
import pandas as pd
# 创建数据集
data = [['Milk', 'Onion', 'Nutmeg', 'Kidney Beans', 'Eggs', 'Yogurt'],
['Dill', 'Onion', 'Nutmeg', 'Kidney Beans', 'Eggs', 'Yogurt'],
['Milk', 'Apple', 'Kidney Beans', 'Eggs'],
['Milk', 'Unicorn', 'Corn', 'Kidney Beans', 'Yogurt'],
['Corn', 'Onion', 'Onion', 'Kidney Beans', 'Ice cream', 'Eggs']]
# 将数据集转换为一个布尔矩阵
df = pd.DataFrame(data)
df = pd.get_dummies(df.apply(pd.Series).stack()).sum(level=0)
# 调用FP-growth算法挖掘频繁项集
frequent_itemsets = fpgrowth(df, min_support=0.6)
# 输出频繁项集
print(frequent_itemsets)
```
在上面的例子中,我们首先创建了一个包含几个交易的数据集,然后将其转换为一个布尔矩阵,其中每个元素代表一个项是否在该交易中出现。然后,我们调用`mlxtend.frequent_patterns.fpgrowth()`函数来挖掘频繁项集,其中`df`是我们转换过的布尔矩阵,`min_support`是指定的最小支持度。函数返回一个包含频繁项集的DataFrame对象,其中每一行代表一个频繁项集,列名是频繁项集的项。