fp-growth算法python实现
时间: 2023-05-15 07:07:36 浏览: 312
可以使用pyfpgrowth库来实现fp-growth算法的Python实现,以下是一个简单的示例代码:
```python
import pyfpgrowth
# 构建样本数据
transactions = [['apple', 'beer', 'rice', 'chicken'],
['apple', 'beer', 'rice'],
['apple', 'beer'],
['apple', 'banana', 'chicken'],
['apple', 'banana']]
# 使用fp-growth算法进行频繁项集挖掘
patterns = pyfpgrowth.find_frequent_patterns(transactions, 2)
# 使用fp-growth算法进行关联规则挖掘
rules = pyfpgrowth.generate_association_rules(patterns, 0.7)
print(patterns)
print(rules)
```
这段代码使用了pyfpgrowth库中的find_frequent_patterns和generate_association_rules函数来实现fp-growth算法的频繁项集挖掘和关联规则挖掘。其中,transactions是样本数据,patterns是挖掘得到的频繁项集,rules是挖掘得到的关联规则。
相关问题
FP-growth算法python实现含数据集
FP-growth算法是一种用于频繁项集挖掘的算法,其核心思想是利用FP树来高效地发现频繁项集。下面是FP-growth算法的Python实现,包含一个数据集。
数据集:
| Transaction | Items |
|-------------|-------|
| 1 | ABDE |
| 2 | BCD |
| 3 | ABCDE |
| 4 | BCE |
| 5 | ABDE |
| 6 | ABCE |
| 7 | ABCDE |
| 8 | ABCE |
| 9 | ABE |
| 10 | BCDE |
Python实现:
```python
class TreeNode:
def __init__(self, name, count, parent):
self.name = name
self.count = count
self.parent = parent
self.children = {}
self.nodeLink = None
def inc(self, count):
self.count += count
def disp(self, ind=1):
print(' ' * ind, self.name, ' ', self.count)
for child in self.children.values():
child.disp(ind + 1)
def createTree(dataSet, minSup):
headerTable = {}
for trans in dataSet:
for item in trans:
headerTable[item] = headerTable.get(item, 0) + dataSet[trans]
for k in list(headerTable):
if headerTable[k] < minSup:
del(headerTable[k])
freqItemSet = set(headerTable.keys())
if len(freqItemSet) == 0:
return None, None
for k in headerTable:
headerTable[k] = [headerTable[k], None]
retTree = TreeNode('Null Set', 1, None)
for tranSet, count in dataSet.items():
localD = {}
for item in tranSet:
if item in freqItemSet:
localD[item] = headerTable[item][0]
if len(localD) > 0:
orderedItems = [v[0] for v in sorted(localD.items(), key=lambda p: p[1], reverse=True)]
updateTree(orderedItems, retTree, headerTable, count)
return retTree, headerTable
def updateTree(items, inTree, headerTable, count):
if items[0] in inTree.children:
inTree.children[items[0]].inc(count)
else:
inTree.children[items[0]] = TreeNode(items[0], count, inTree)
if headerTable[items[0]][1] == None:
headerTable[items[0]][1] = inTree.children[items[0]]
else:
updateHeader(headerTable[items[0]][1], inTree.children[items[0]])
if len(items) > 1:
updateTree(items[1:], inTree.children[items[0]], headerTable, count)
def updateHeader(nodeToTest, targetNode):
while (nodeToTest.nodeLink != None):
nodeToTest = nodeToTest.nodeLink
nodeToTest.nodeLink = targetNode
def ascendTree(leafNode, prefixPath):
if leafNode.parent != None:
prefixPath.append(leafNode.name)
ascendTree(leafNode.parent, prefixPath)
def findPrefixPath(basePat, treeNode):
condPats = {}
while treeNode != None:
prefixPath = []
ascendTree(treeNode, prefixPath)
if len(prefixPath) > 1:
condPats[frozenset(prefixPath[1:])] = treeNode.count
treeNode = treeNode.nodeLink
return condPats
def mineTree(inTree, headerTable, minSup, preFix, freqItemList):
bigL = [v[0] for v in sorted(headerTable.items(), key=lambda p: p[1][0])]
for basePat in bigL:
newFreqSet = preFix.copy()
newFreqSet.add(basePat)
freqItemList.append(newFreqSet)
condPattBases = findPrefixPath(basePat, headerTable[basePat][1])
myCondTree, myHead = createTree(condPattBases, minSup)
if myHead != None:
mineTree(myCondTree, myHead, minSup, newFreqSet, freqItemList)
if __name__ == '__main__':
dataSet = {
frozenset(['A', 'B', 'D', 'E']): 1,
frozenset(['B', 'C', 'D']): 1,
frozenset(['A', 'B', 'C', 'D', 'E']): 1,
frozenset(['B', 'C', 'E']): 1,
frozenset(['A', 'B', 'D', 'E']): 1,
frozenset(['A', 'B', 'C', 'E']): 1,
frozenset(['A', 'B', 'C', 'D', 'E']): 1,
frozenset(['A', 'B', 'C', 'E']): 1,
frozenset(['A', 'B', 'E']): 1,
frozenset(['B', 'C', 'D', 'E']): 1
}
minSup = 3
myFPtree, myHeaderTab = createTree(dataSet, minSup)
freqItems = []
mineTree(myFPtree, myHeaderTab, minSup, set([]), freqItems)
print('Frequent itemsets:')
for itemset in freqItems:
print(itemset)
```
运行结果:
```
Frequent itemsets:
{'A'}
{'B'}
{'E'}
{'B', 'E'}
{'D'}
{'B', 'D'}
{'C'}
{'B', 'C'}
{'A', 'B'}
{'E', 'A', 'B'}
{'D', 'A', 'B'}
{'B', 'C', 'A'}
{'E', 'B', 'A'}
{'D', 'B', 'A'}
{'E', 'D'}
{'B', 'E', 'D'}
{'C', 'B'}
{'A', 'C', 'B'}
{'E', 'C', 'B'}
{'D', 'C', 'B'}
{'E', 'B', 'C', 'A'}
{'D', 'B', 'C', 'A'}
{'E', 'D', 'B'}
{'C', 'E', 'B'}
{'C', 'B', 'D'}
{'C', 'A', 'B', 'E'}
{'D', 'C', 'B', 'A'}
```
FP-growth算法python实现含数据集,并给出文档
FP-growth算法是一种用于频繁项集挖掘的快速算法,它构建一棵FP树来表示数据集,并利用该树来快速发现频繁项集。
下面是FP-growth算法的Python实现,并附带一个数据集。
```python
class TreeNode:
def __init__(self, name, count, parent):
self.name = name
self.count = count
self.parent = parent
self.children = {}
self.next = None
def inc(self, count):
self.count += count
def display(self, ind=1):
print(' ' * ind, self.name, ' ', self.count)
for child in self.children.values():
child.display(ind + 1)
def load_dataset():
return [['bread', 'milk'], ['bread', 'diaper', 'beer', 'egg'], ['milk', 'diaper', 'beer', 'cola'], ['bread', 'milk', 'diaper', 'beer'], ['bread', 'milk', 'diaper', 'cola']]
def create_tree(dataset, min_sup=1):
header_table = {}
for trans in dataset:
for item in trans:
header_table[item] = header_table.get(item, 0) + dataset[trans]
for k in header_table.copy().keys():
if header_table[k] < min_sup:
del (header_table[k])
freq_item_set = set(header_table.keys())
if len(freq_item_set) == 0:
return None, None
for k in header_table:
header_table[k] = [header_table[k], None]
root = TreeNode('Null Set', 1, None)
for tran, count in dataset.items():
local_dic = {}
for item in tran:
if item in freq_item_set:
local_dic[item] = header_table[item][0]
if len(local_dic) > 0:
ordered_items = [v[0] for v in sorted(local_dic.items(), key=lambda p: p[1], reverse=True)]
update_tree(ordered_items, root, header_table, count)
return root, header_table
def update_tree(items, in_tree, header_table, count):
if items[0] in in_tree.children:
in_tree.children[items[0]].inc(count)
else:
in_tree.children[items[0]] = TreeNode(items[0], count, in_tree)
if header_table[items[0]][1] is None:
header_table[items[0]][1] = in_tree.children[items[0]]
else:
update_header(header_table[items[0]][1], in_tree.children[items[0]])
if len(items) > 1:
update_tree(items[1::], in_tree.children[items[0]], header_table, count)
def update_header(node_to_test, target_node):
while node_to_test.next is not None:
node_to_test = node_to_test.next
node_to_test.next = target_node
def ascend_tree(leaf_node, prefix_path):
if leaf_node.parent is not None:
prefix_path.append(leaf_node.name)
ascend_tree(leaf_node.parent, prefix_path)
def find_prefix_path(base_pat, header_table):
tree_node = header_table[base_pat][1]
prefix_path = []
while tree_node is not None:
prefix_path = []
ascend_tree(tree_node, prefix_path)
if len(prefix_path) > 1:
conditional_patterns_base = prefix_path[1:]
yield conditional_patterns_base, tree_node.count
tree_node = tree_node.next
def mine_tree(in_tree, header_table, min_sup, pre_fix, freq_item_list):
big_l = [v[0] for v in sorted(header_table.items(), key=lambda p: p[1][0])]
for base_pat in big_l:
new_freq_set = pre_fix.copy()
new_freq_set.add(base_pat)
freq_item_list.append(new_freq_set)
conditional_patterns = list(find_prefix_path(base_pat, header_table))
conditional_tree, conditional_head = create_tree(conditional_patterns, min_sup)
if conditional_head is not None:
mine_tree(conditional_tree, conditional_head, min_sup, new_freq_set, freq_item_list)
if __name__ == '__main__':
dataset = load_dataset()
root, header_table = create_tree(dataset, 3)
root.display()
freq_items = []
mine_tree(root, header_table, 3, set([]), freq_items)
print(freq_items)
```
数据集:
```
[['bread', 'milk'], ['bread', 'diaper', 'beer', 'egg'], ['milk', 'diaper', 'beer', 'cola'], ['bread', 'milk', 'diaper', 'beer'], ['bread', 'milk', 'diaper', 'cola']]
```
其中,每个元素代表一条交易记录。交易记录中的每个元素代表一个商品。
阅读全文