for sample in X: for permiss in range(4): if sample[permiss]==0: continue n[permiss]+=1 for c in range(4): if permiss==c: continue if sample[c]==1: v[(permiss,c)]+=1#两者均为1时加一 else: i[(permiss,c)]+=1#两者不同时为1
support=v #permiss=1 #c=3 #print(" -Support:{0}".format(support[(permiss,c)])) confidence=defaultdict(float) ''' for permiss,c in v.keys(): rule=(permiss,c) confidence[rule]=v[rule]/n[permiss] print(confidence[rule]) ''' def print_rule(permiss,c,support,confidence,features): permiss_name=features[permiss] c_name=features[c] print("Rule if a people buy {0} they will also buy {1}".format(permiss_name,c_name))
print(support)#内涵键值对 sorted_support=sorted(support.items(),key=itemgetter(1),reverse=True) #输出支持度最高的五个规则 for index in range(5): print(" Rule #{0}".format(index+1)) permiss,c=sorted_support[index][0] print_rule(permiss,c,support,confidence,features) #输出置信度最高的规则 sorted_confidence=sorted(support.items(),key=itemgetter(1),reverse=True) for index in sorted_confidence: permiss,c=sorted_confidence[index][0] print_rule(permiss,c,support,confidence,features)