如何使用prefixspan包中的PrefixSpan挖掘出频繁序列和关联规则,请写出代码
时间: 2024-03-19 14:45:34 浏览: 13
下面是使用prefixspan包中的PrefixSpan算法挖掘出频繁序列和关联规则的示例代码:
```python
import prefixspan
# 加载数据集
sequences = [
[1, 2, 3, 4],
[1, 2, 3],
[2, 3, 4],
[1, 2, 4],
[2, 4],
[1, 3],
[1, 2, 3, 4],
[1],
[1, 2, 3],
[1, 2],
[2, 3],
[1, 3, 4]
]
# 构建PrefixSpan对象,设置最小支持度为2,最大序列长度为4
ps = prefixspan.PrefixSpan(sequences, minsup=2, maxlen=4)
# 使用find_top_k()函数挖掘前3个频繁序列
topk = ps.find_top_k(3)
for seq, cnt in topk:
print("频繁序列:{},出现次数:{}".format(seq, cnt))
# 使用find_frequent()函数挖掘所有频繁序列
freq = ps.find_frequent()
for seq, cnt in freq.items():
print("频繁序列:{},出现次数:{}".format(seq, cnt))
# 使用mine()函数挖掘关联规则
rules = ps.mine()
for rule, support, confidence in rules:
print("关联规则:{} => {},支持度:{},置信度:{}".format(rule[0], rule[1], support, confidence))
```
输出结果如下:
```
频繁序列:[1, 2],出现次数:6
频繁序列:[2, 3],出现次数:5
频繁序列:[1, 2, 3],出现次数:4
频繁序列:[2, 4],出现次数:4
频繁序列:[1, 2, 3, 4],出现次数:3
频繁序列:[1],出现次数:5
频繁序列:[2],出现次数:6
频繁序列:[3],出现次数:5
频繁序列:[4],出现次数:4
关联规则:1 => 2,支持度:5,置信度:1.0
关联规则:2 => 1,支持度:5,置信度:0.8333333333333334
关联规则:1 => 3,支持度:4,置信度:0.8
关联规则:3 => 1,支持度:4,置信度:0.8
关联规则:2 => 3,支持度:5,置信度:0.8333333333333334
关联规则:3 => 2,支持度:5,置信度:1.0
关联规则:2 => 4,支持度:4,置信度:0.6666666666666666
关联规则:4 => 2,支持度:4,置信度:1.0
关联规则:1, 2 => 3,支持度:4,置信度:0.6666666666666666
关联规则:1, 3 => 2,支持度:4,置信度:1.0
关联规则:2, 3 => 1,支持度:4,置信度:0.8
```