data = [['西红柿', '排骨', '鸡蛋'], ['西红柿', '茄子'], ['鸡蛋', '袜子'], ['西红柿', '排骨', '茄子'], ['西红柿', '排骨', '袜子', '酸奶'], ['鸡蛋', '茄子', '酸奶'], ['排骨', '鸡蛋', '茄子'], ['土豆', '鸡蛋', '袜子'], ['西红柿', '排骨', '鞋子', '土豆']] # 获取所有可能出现的物品 items=['土豆','排骨','茄子','袜子','西红柿','酸奶','鞋子','鸡蛋'] # 构建布尔矩阵 matrix = [] for d in data: row = [] for item in items: if item in d: row.append(1) else: row.append(0) matrix.append(row) # 输出布尔矩阵 print('ID', end='\t') for item in items: print(item, end='\t') print() for i in range(len(data)): print('I' + str(i+1), end='\t') for j in range(len(items)): print(matrix[i][j], end='\t') print() # 计算关联规则 rules = [('西红柿','排骨'), ('排骨','西红柿'), ('袜子','鸡蛋'), ('茄子','排骨'), ('茄子','西红柿'), ('茄子','鸡蛋')] # 计算支持度 def support(itemset, data): count = 0 for d in data: if all(item in d for item in itemset): count += 1 return count / len(data) # 计算置信度 def confidence(rule, data): antecedent = rule[0] consequent = rule[1] antecedent_count = 0 rule_count = 0 for d in data: if all(item in d for item in antecedent): antecedent_count += 1 if all(item in d for item in rule): rule_count += 1 if antecedent_count == 0: return 0 return rule_count / antecedent_count # 输出支持度和置信度 for rule in rules: print(f"Rule: {rule} \t Support: {support(rule, data):.4f} \t Confidence: {confidence(rule, data):.4f}")为什么这个代码置信度输出都是零,怎么改
时间: 2023-08-20 11:30:31 浏览: 56
在这个代码中,置信度输出为零的原因是因为在计算置信度时,被除数和除数都是整数,因此结果也是整数,而不是浮点数。因此,可以通过将被除数或除数转换为浮点数来解决这个问题。可以像这样修改代码:
```python
def confidence(rule, data):
antecedent = rule[0]
consequent = rule[1]
antecedent_count = 0
rule_count = 0
for d in data:
if all(item in d for item in antecedent):
antecedent_count += 1
if all(item in d for item in rule):
rule_count += 1
if antecedent_count == 0:
return 0
return float(rule_count) / antecedent_count
```
这里使用了`float()`函数将`rule_count`转换为浮点数,从而使结果为浮点数。这样可以正确地输出置信度。
阅读全文