python 实现数据降维推荐系统(附Python源码)

来源:互联网 发布:自助建站域名 编辑:程序博客网 时间:2024/06/08 02:04

主成分分析原理:请点击PCA查看

#!usr/bin/env python#_*_ coding:utf-8 _*_import pandas as pdimport numpy as npimport matplotlib.pyplot as plt#如果一个旅游网站里面有100000个注册用户,以及100个注册酒店,网站有用户通过本网站点击酒店页面的#记录数据信息A=Aij   100000*100  Aij表示第i个用户点击j酒店的次数#Q1:如何评价酒店之间的相似度#Q2:给定一个酒店,请找出与它最相似的其他几个酒店#Q3:如何要给酒店分类,有什么办法?#prepare data set,suppose there are 5 types of hotels  纬度评分generatorNum=5     #5hotelNum=100               #100customerNum=100000  #100000#10000用户个对五个纬度的侧重点的评分generators=np.random.randint(5,size=(customerNum,generatorNum))print(generators)#酒店在各个纬度为评分hotelcomp=np.random.random(size=(generatorNum,hotelNum))-0.5# 0.5出现负值print(hotelcomp)#.dot矩阵运算,生成顾客对酒店评分hotelRating=pd.DataFrame(generators.dot(hotelcomp),index=['c%.6d'%i for i in range(customerNum)],columns=['hotel_%.3d'%j for j in range(100)]).astype(int)#data z-score公式def normalize(s):    if s.std()>1e-6:        #**乘方,就散标准分数z-score,用来算离数据中心的偏差的,https://www.zhihu.com/question/21600637        return(s-s.mean())*s.std()**(-1)    else:        return (s-s.mean())#如何评价酒店之间的相似度?#data to z-scorehotelRating_norm=hotelRating.apply(normalize)print('hotelRating_norm\n{}'.format(hotelRating_norm))print(type(hotelRating_norm))#计算协方差hotelRating_norm_corr=hotelRating_norm.cov()print('hotelRating_norm_corr\n{}'.format(hotelRating_norm_corr))#SVD,即奇异值分解u,s,v=np.linalg.svd(hotelRating_norm_corr)#碎石图确定分类,测试时是5print('u\n{}'.format(u))print(s)plt.plot(s,'o')plt.title("singular value spectrum")plt.show()

这里写图片描述

#截取SVD纬度u_short = u[:,:5]v_short = v[:5,:]s_short = s[:5]print('u,s,v,short{}'.format(u_short,v_short,s_short))#numpy.diag()创建一个对角矩阵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())#get the top components ,np.power数组的元素分别求n次方top_component=hotelRating_norm.dot(u_short).dot(np.diag(np.power(s_short,-0.5)))#classfication of each hotelhotel_ind = 3rating = hotelRating_norm.loc[:,'hotel_%.3d'%hotel_ind]print ("classification of the %dth hotel"%hotel_ind,top_component.T.dot(rating)/customerNum)

结果
这里写图片描述

阅读全文
0 0
原创粉丝点击