这是一个有关商品排放问题的程序:
基本思路就是看顾客是否买了a商品,在买了a 商品的条件下 ,看是否买b 商品, 而这个记录就是通过 rule_valid = defaultdict(int) 这个对象来记录每个买的东西的情况。
所以就有几种情况:
1: 既没买a 也没买b ,当然这种情况就不需要过多解释了,也不用在程序中考虑太多
2:只买了a,没有买b,当然这个是要有的
3:既买了a又买了b
当然需要保存数据的只有后面两种
用一个他:
rule_valid[(i , x)] += 1 #我觉得这个字典超级棒
来保存既买i又买x 的情况
#首先导入数据:
#然后用一个数组来保存每一个可能的买度:
import numpy as np
from collections import defaultdict
导入数据集:
data_file = "affinity_dataset.txt"
X = np.loadtxt( data_file)
rule_valid = defaultdict(int)#存放买a又买b 的
rule_invalid = defaultdict(int)#只卖a的没买b
result_confidence = defaultdict(int) #置信度
result_support = defaultdict(int) #支持度
for sample in X: #遍历每一个顾客买的数据
for i in range( 5 ):#牛奶香蕉。。。
if sample[i] == 0 :#是否买a
continue
#buy_1[i]+=1
#保证不是一个(买了苹果又买苹果)
for x in range(i+1 , 5) :
if sample[x] == 1 :
rule_valid[(i , x)] += 1 #我觉得这个字典超级棒
else:
rule_invalid[( i , x)] += 1
for x2 , x in rule_valid.items() :键,值
print("买的商品: :" , x2 )
c = rule_invalid[x2] #只卖a没买b的情况
print("置信度:" , x /(x + c) )
print("支持度:", x)
#保存置信度和支持度 , 用来排序
result_confidence[x2] = x /(x + c)
result_support[x2] = x
#sorted(dict.items(), key=lambda e:e[1], reverse=True)
#排序
result_confidence_sort = sorted(result_confidence.items(),key= lambda e: e[1], reverse=True )
result_support_sort = sorted(result_support.items() ,key= lambda e: e[1], reverse=True )
print(result_confidence_sort)
print(result_support_sort)
for i in range(5):
print("rule :#{0}".format(i +1)) #名次
print("自信度",result_confidence_sort[i][1])
y = result_confidence_sort[i][0]
print(" 支持度",result_support[y])