机器学习(ML,machine learning)是人工智能(AI,artificial intelligence)的子领域。将数据传递给算法,算法推断这些数据的属性相关的信息,进而预测未来有可能出现的其他数据。 算法之间会有明显的不同,所有算法各有所长,适应于不同类型的问题。决策树:可以直观的理解机器执行的推导过程。神经网络:像一个黑箱,给出结果,但是结果背后的推导过程非常困难。
ML算法对大量模式归纳,如果不同,新模式则会被误解。相比之下,人类可以借鉴文化知识和经验,同时识别相似信息。
谷歌成功的利用大量的用户数据,用户点击广告,信息被收集,使得广告投放更有效。 市场预测:Hollywood Stock Exchange,可以用来进行设计影片和影星的模拟股票交易。价格通过群体行为来确定。
Making Recommendations
本章内容:讲解如何根据群体偏好为人们提供推荐,告诉如何构筑一个系统,寻找相同品味的人,并根据喜好自动给出推荐。当选择变多,通过询问一小群人来确定我们想要的东西,变得不切实际,所以引入协作型过滤(collaborative filtering)。 协作型过滤:对一群人进行搜索,找出与我们品味相近的一小群人,将他们偏爱的内容进行考察,然后组合起来构造一个经过排名的推荐列表,确定与我们品味相近的人。eg:大众点评,美团等等的推荐算法。
第一件事,寻找一种表达不同人及其偏好的方法,最简单的方法,使用一个嵌套的字典。
加入如下代码,构建一个数据集: # A dictionary of movie critics and their ratings of a small # set of movies 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}}上述代码一定注意空格,python中空格的意义 上述建立了一个影评者对电影的评分情况,1-5的评分。 若是在线购物,可用1代表购买,0代表未购买。若是故事投票,-1,0,1可分别代表“不喜欢”、“未投票”、“喜欢”。
使用命令行对字典进行查询和修改 c:\code\collective\chapter2>python >>from recommendations import critics >>critics['Lisa Rose']['Lady in the Water'] 2.5 >>critics['Toby'] {'Snakes on a Plane' : 4.5,'Superman Returns' : 4.0, 'You,Me and Dupree':1.0}注意字典的调用方式,使用中括号,分层调用。
本章介绍两套计算相似度评价值的体系:欧几里得距离和皮尔逊相关度。
以评价的物品为坐标轴,将参与评价的人绘制在图上,考察彼此的距离远近。如图所示: 在偏好空间中的人的分布,两个点距离越近,偏好越相似。可适用于多项评分的情况。求两点的距离,代码块:
>>from math import sqrt >>sqrt(pow(4.5-4,2) + pow(1-2,2)) 1.11803修改计算方式,使得偏好越相近,值越大,函数值+1,然后取倒数。返回介于0-1之间的值。
0.4721359``` 加入代码块: # Returns a distance-based similarity score for person1 and person2 def sim_distance(prefs,person1,person2): # Get the list of shared_items si={} for item in prefs[person1]: if item in prefs[person2]: si[item]=1 # if they have no ratings in common, return 0 if len(si)==0: return 0 # Add up the squares of all the differences sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2) for item in prefs[person1] if item in prefs[person2]]) return 1/(1+sum_of_squares)