PCA前言
众所周知,PCA 的主要目的是降维,同时也可以起到分类的作用。当数据维度很大的时候,如果相信大部分变量之间存在线性关系,那么我们就希望降低维数,用较少的变量来抓住大部分的信息。(一般来讲做PCA 之前要做normalization 使得变量中心为0,而且方差为1.)比较广泛应用于图像识别,文档处理,推荐系统等。
PCA应用举例
推荐系统
如果一个旅游网站里面有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
本文分享自 机器学习算法与Python学习 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体分享计划 ,欢迎热爱写作的你一起参与!