考虑如下的用户对影片的打分,由嵌套字典定义:
critics = {'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
'The Night Listener': 3.0},
'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,
'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,
'You, Me and Dupree': 3.5},
'Michael Phillips': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,
'Superman Returns': 3.5, 'The Night Listener': 4.0},
'Claudia Puig': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0,
'The Night Listener': 4.5, 'Superman Returns': 4.0,
'You, Me and Dupree': 2.5},
'Mick LaSalle': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0,
'You, Me and Dupree': 2.0},
'Jack Matthews': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5},
'Toby': {'Snakes on a Plane': 4.5, 'You, Me and Dupree': 1.0, 'Superman Returns': 4.0}}
我们知道如何为指定人员寻找品味相近者,通过欧氏距离或者皮尔逊相关度系数。假如我们想了解哪些商品之间是彼此接近的,又该如何做呢。这一现实应用即是,各大电商网站的“浏览该商品的用户同时购买了”诸如此类的推荐。
我们通过查看哪些人喜欢某一特定物品,如同某个人喜欢哪些商品一样,然后像定义用户之间的相似度一样,定义商品之间的相似度。
def transformPrefs(prefs):
result = {}
for p in prefs:
for item in prefs[p]:
result.setdefault(item, {})
result[item][p] = prefs[p][item]
# 活脱脱一个转置
return result