概念理解: 推荐:在数据挖掘中,推荐包括相似推荐及系统过滤推荐。 1,相似推荐:指当用户表现出对某人或某物的兴趣是,为他推荐与之相类似的人,或者物,他的核心是,人以群分,物以类聚 2,协同过滤推荐:指利用已有用户群过去的行为和意见,预测当前用户最有可能喜欢那些东西。 余弦相似度: 求两者之间的夹角,得出对应的余弦值,该值可以用来表示两个向量的相似性,夹角越小,余弦值越大,方向更吻合,则越相似。
python中sklearn计算特征之间的距离 sklearn.metrics库中的pairsise_distances。 pairsise_distances(textvector,metric=’consin’)
案例代码:
import pandas,bumpy,codecs,os,jieba from sklearn.metrics import pairwise_distances # 创建语料库 corpos=pandas.DataFrame(columns=['filepath','content']) for root,dirs,files in os.walk('文件夹路径'):#储存文章的文件夹 for name in files: filepath=root+'/'+name f=codecs.open(filepath,'r','utf-8') content=f.read() f.close() corpos.loc[len(corpos)+1]=[filepath,content.strip()] #分词filepaths=[]segments=[]for i in range(len(corpos)): file=corpos.loc[i].filepath segs=jieba.cut(corpos.loc[i].content) for seg in segs: if len(seg.strip())>1: filepaths.append(file) segments.append(seg) #创建数据框储存数据 segmentsDF=pandas.DataFrame({'filepath':filepaths,'segment':segments}#去杂词stopWords=pandas.read_table('文档路径')fsegments=segmentsDF[~segmentDF.segments.isin(stopwords.stopword)]#按文章进行词频的统计seg_group=fsegments.groupby(['filepath','segment'])['segment'].agg({'count':bumpy.size}).reset_index().sort(columns='segment',ascending=False)seg_group=seg_group[seg_group.count>1]#进行文本向量计算,其中index为行,columns为列textvector=seg_group.pivot_table(values='count',index='filepath',columns='segment',fill_values=0,aggfunc=[numpy.size])from sklearn.metrics import pairwise_distancesdistance_matrix=pairwise_distance(textvector,metric='cosine')df_distance=pandas.DataFrame(distance_matrix)# 匹配结果series排序用order(ascending=True)升序,dataframe 用sort(columns=)。或者sort_index(axis=,ascending=)for i in range(len(corpos)): tagis=textvector.index[df_distance.loc[:,i].order(ascending=True)[1:6].index] PRint(text vector.index[i]+'相似文章') print('/n'.join(tagis)) print('/n')新闻热点
疑难解答