簡體   English   中英

AttributeError: 'dict' 對象沒有屬性 'predictors'

[英]AttributeError: 'dict' object has no attribute 'predictors'

我是 python 新手,找不到答案。 參考消息末尾的代碼,我能知道下一行中的“for item, total in totals.items()”部分是什么意思嗎?

rankings = [(total/simSums[item], item) for item, total in totals.items()]

另外,代碼失敗並說

AttributeError: 'dict' 對象沒有屬性 'predictors'

當我將代碼中“item(s)”的所有實例更改為“predictor(s)”時。 為什么呢?

# Return the Pearson correlation coefficient for p1 and p2
def sim_person(prefs, p1, p2):
    # Get the list of shared_items
    si={}
    for item in prefs[p1]:
        if item in prefs[p2]:si[item]=1

    # Find the number of elements 
    n=len(si)

    # if they have no ratings in common, return 0
    if n==0: return 0

    # Add up all the preferences
    sum1 = sum([prefs[p1][it] for it in si])
    sum2 = sum([prefs[p2][it] for it in si])

    # Sum up the squares
    sum1Sq = sum([pow(prefs[p1][it],2) for it in si])
    sum2Sq = sum([pow(prefs[p2][it],2) for it in si])

    # Sum up the products
    pSum = sum([prefs[p1][it]*prefs[p2][it] for it in si])

    # Calculate Person score
    num = pSum - (sum1*sum2/n)
    den = sqrt((sum1Sq - pow(sum1,2)/n)*(sum2Sq - pow(sum2,2)/n))
    if den == 0: return 0

    r = num/den
    return r

# Returns the best matches for person from the prefs dictionary.
# Number of results and similarity function are optional params.
def topMatch(prefs, person, n=5, similarity=sim_person):
    scores = [(similarity(prefs, person, other), other) 
              for other in prefs if other!=person]

    # Sort the list so the highest scores appear at the top
    scores.sort()
    scores.reverse()
    return scores[0:n]

# Gets recommendations for a person by using a weighted average
# of every other user's rankings 
def getRecommendations(prefs, person, similarity=sim_person):
    totals = {}
    simSums = {}
    for other in prefs:
        # don't compare me to myself
        if other == person: continue
        sim = similarity(prefs, person, other)

        # ignore scores of zero of lower
        if sim<=0: continue
        for item in prefs[other]:

            # only score movies I haven't seen yet
            if item not in prefs[person] or prefs[person][item]==0:
                # Similarity * Score
                totals.setdefault(item, 0)
                totals[item]+=prefs[other][item]*sim
                # Sum of similarities
                simSums.setdefault(item, 0)
                simSums[item]+=sim

    # Create the normalized list 
    rankings = [(total/simSums[item], item) for item, total in totals.items()]

    # Return the sorted list 
    rankings.sort()
    rankings.reverse()
    return rankings

dict.items迭代字典的鍵值對。 因此, for key, value in dictionary.items()將遍歷每一對。 這是文檔信息,您可以在官方網頁中查看,或者更簡單,打開 python 控制台並鍵入help(dict.items) 現在,舉個例子:

>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
...   print key, value
...
world 2999
hello 34

AttributeError是當對象不具有您嘗試訪問的屬性時拋出的異常。 dict沒有任何predictors屬性(現在您知道在哪里檢查它:)),因此當您嘗試訪問它時它會抱怨。 就這么簡單。

#Try without dot notation sample_dict = {'name': 'John', 'age': 29} print(sample_dict['name']) # John print(sample_dict['age']) # 29
product_details = {
'name':'mobile',
'company':'samsung'}

訪問 product_details.name 將拋出錯誤“dict object has no attribute 'name'”。 原因是因為我們使用點 (.) 來訪問 dict 項目。

right way is :
product_details['name']  

我們使用點運算符從 python 中的對象訪問值。

dictionary.items() 允許我們遍歷字典中的鍵:值對

for key, value in product_details.items(): 
    print(key,':',value)

對於循環的每次迭代,一個鍵和它的值被分配給這里的變量鍵和值。 這就是 items() 方法的工作原理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM