PCA实现一个简单的酒店推荐系统(附Python源码)

浏览: 1996

image.png

众所周知,PCA 的主要目的是降维,同时也可以起到分类的作用。当数据维度很大的时候,如果相信大部分变量之间存在线性关系,那么我们就希望降低维数,用较少的变量来抓住大部分的信息。(一般来讲做PCA 之前要做normalization 使得变量中心为0,而且方差为1.)比较广泛应用于图像识别,文档处理,推荐系统等。

image.png

推荐系统

如果一个旅游网站里面有10000000 个注册用户,以及100 个注册酒店. 网站有用户通过本网站点击酒店页面的记录信息.A = [Aij ]10000000100,Aij 表示第i 个用户点击j 酒店的次数.

问题:

如何评价酒店之间的相似度?

给定一个酒店,请找出与它最相似的其他几个酒店?

如果要给酒店分类,有什么办法?

生成100000x100的用户-酒店行为数据

import pandas as pd
import numpy as np
#prepare data set, suppose there are 5 types of hotels
generatorNum=5
hotelNum=100
customerNum=100000

generators = np.random.randint(5, size=(customerNum, generatorNum))
hotelComp=np.random.random(size=(generatorNum, hotelNum)) - 0.5
hotelRating = pd.DataFrame(generators.dot(hotelComp),index=['c%.6d'%i for i in range(100000)]
,columns = ['hotel_%.3d'%j for j in range(100)]).astype(int)

def normalize(s):
if s.std()>1e-6:
return (s-s.mean())*s.std()**(-1)
else:
return (s-s.mean())

hotelRating数据如下所示。


hotelRating_norm = hotelRating.apply(normalize)

hotelRating_norm_corr = hotelRating_norm.cov()

hotelRating_norm_corr如下所示。


u,s,v = np.linalg.svd(hotelRating_norm_corr)
In [9]:
import matplotlib.pyplot as plt
plt.plot(s,'o')
plt.title("singular value spectrum")
plt.show()
In [10]:
u_short = u[:,:5]
v_short = v[:5,:]
s_short = s[:5]

hotelRating_norm_corr_rebuild = pd.DataFrame(u_short.dot(np.diag(s_short).dot(v_short))
,index=hotelRating_norm_corr.index
,columns=hotelRating_norm_corr.keys())
In [11]:
#get the top components
top_components = hotelRating_norm.dot(u_short).dot(np.diag(np.power(s_short,-0.5)))
In [12]:
#classfication of each hotel
hotel_ind = 30
rating = hotelRating_norm.loc[:,'hotel_%.3d'%hotel_ind]
print "classification of the %dth hotel"%hotel_ind
top_components.T.dot(rating)/customerNum


classification of the 30th hotel

0    0.136138
1    0.179586
2   -0.071347
3   -0.384475
4    0.647324

推荐 0
本文由 郭昱良 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

1 个评论

代码注释下更好

要回复文章请先登录注册