You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apyori无法输出含多元素的关联规则问题求助

解决Apyori关联规则多前置项显示问题

原代码的核心问题是错误拆分了关联规则的项集结构,没有区分前置项集和后置项。Apyori返回的结果里,item[2][0]包含完整规则信息:

  • item[2][0][0]:前置项集(即关联规则的左半部分)
  • item[2][0][1]:后置项(规则的右半部分)
  • item[2][0][2]:置信度
  • item[2][0][3]:提升度
  • item[1]:支持度

以下是修改后的完整代码,解决多前置项显示问题:

import pandas as pd  
from apyori import apriori

movie_data = pd.read_csv(r"C:\Users\XY\Desktop\movie_dataset.csv", header = None)
num_records = len(movie_data)

records = []  
for i in range(0, num_records):  
    records.append([str(movie_data.values[i,j]) for j in range(0, 20)])

# 清理空值
for idx in range(len(records)):
    while 'nan' in records[idx]:
        records[idx].remove('nan')

association_rules = apriori(records, min_support=0.0053, min_confidence=0.20, min_lift=3, min_length=2)
association_results = list(association_rules) 

results = []
for item in association_results:
    support = round(item[1], 5)
    # 遍历项集对应的所有关联规则
    for rule in item[2]:
        # 拼接多元素前置项为字符串
        base_items = ', '.join([str(x) for x in rule[0]])
        # 提取后置项
        add_item = str(rule[1][0])
        confidence = round(rule[2], 5)
        lift = round(rule[3], 5)
        
        results.append((base_items, add_item, support, confidence, lift))
    
labels = ['When bought','Likely bought as well','Support','Confidence','Lift']
movie_suggestion = pd.DataFrame.from_records(results, columns = labels)

print(movie_suggestion)

关键修改点:

  1. 用', '.join()将多元素前置项拼接成字符串,解决单元素显示问题
  2. 遍历item[2]中的每个规则,确保捕获项集对应的所有关联组合
  3. 用round()统一数值精度,避免过长小数
  4. 简化空值清理的循环逻辑

输出示例:

When boughtLikely bought as wellSupportConfidenceLift
5Moana, Tomb RiderSpiderman 30.005330.232550.23255

内容的提问来源于stack exchange,提问作者regflori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 03:15:40