python - TypeError: 'dict_items' 对象在运行 if 语句以入围项目时不可下标
问题描述
我正在使用下面的函数来运行先验算法并计算所有项目集的支持度和置信度。该函数使用字典对象来存储项目的所有值及其相应的支持度和置信度。
在运行 if 语句以选择最小支持值为 0.15 且置信度为 0.6 的项目后,我在 dict_items 对象不可下标下方收到错误消息。
for key, value in largeSet.items()[1:]:
TypeError: 'dict_items' object is not subscriptable
def runApriori(data_iter, minSupport, minConfidence):
"""
run the apriori algorithm. data_iter is a record iterator
Return both:
- items (tuple, support)
- rules ((pretuple, posttuple), confidence)
"""
itemSet, transactionList = getItemSetTransactionList(data_iter)
freqSet = defaultdict(int)
largeSet = dict()
# Global dictionary which stores (key=n-itemSets,value=support)
# which satisfy minSupport
assocRules = dict()
# Dictionary which stores Association Rules
oneCSet = returnItemsWithMinSupport(itemSet,
transactionList,
minSupport,
freqSet)
currentLSet = oneCSet
k = 2
while(currentLSet != set([])):
largeSet[k-1] = currentLSet
currentLSet = joinSet(currentLSet, k)
currentCSet = returnItemsWithMinSupport(currentLSet,
transactionList,
minSupport,
freqSet)
currentLSet = currentCSet
k = k + 1
def getSupport(item):
"""local function which Returns the support of an item"""
return float(freqSet[item])/len(transactionList)
toRetItems = []
for key, value in largeSet.items():
toRetItems.extend([(tuple(item), getSupport(item))
for item in value])
toRetRules = []
for key, value in largeSet.items()[1:]:
for item in value:
_subsets = map(frozenset, [x for x in subsets(item)])
for element in _subsets:
remain = item.difference(element)
if len(remain) > 0:
confidence = getSupport(item)/getSupport(element)
if confidence >= minConfidence:
toRetRules.append(((tuple(element), tuple(remain)),
confidence))
return toRetItems, toRetRules
if __name__ == "__main__":
inFile = ''
minSupport = 0.15
minConfidence = 0.6
items, rules = runApriori(inFile, minSupport, minConfidence)
printResults(items, rules)
解决方案
在 CPython 3.6(以及任何 Python 解释器的 3.7)之前,dict
s 没有可靠的顺序,因此假设第一项是您想要跳过的项是一个坏主意。
也就是说,如果您使用的是 3.6+,并且您知道要跳过第一个元素,则可以使用它itertools.islice
来安全地执行此操作,更改:
for key, value in largeSet.items()[1:]:
至:
# At top of file
from itertools import islice
for key, value in islice(largeSet.items(), 1, None):
推荐阅读
- sql-server - SQL中的成员资格计算逻辑
- c++ - 我对 Delphi 中的动态虚拟通道有点卡住了
- mysql - 更新时在同一张表上执行触发器
- python - 如何让用户选择他们想要加载的按钮
- c++ - 如何评估使用 Omnet++ 和 Crypto++ 进行数字签名的时间?
- typescript - TypeScript 中是否有严格的类型检查?
- python - 如何修复 ConnectionRefusedError: [WinError 10061] 目标机器主动拒绝它?(Django 电子邮件)
- angularjs - Angularjs:当表中该列的值为空时,如何显示 td 为空
- sql - 如何修复 RegCreateKeyEx() 返回错误 5,“访问被拒绝。” 在 SQL Server 2017 中
- reactjs - 如何修复“未找到模块:无法解析‘反应’”?