代码
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics.pairwise import pairwise_distances
import numpy as np
news_df=pd.read_csv('C:/Users/Administrator/Desktop/uci-news-aggregator.csv')
vectorizer=TfidfVectorizer(stop_words='english')
news_vectors=vectorizer.fit_transform(news_df['TITLE'])
def cosine_recommendation(title):
title_vector=vectorizer.transform([title])
cosine_similarities=cosine_similarity(title_vector,news_vectors).flatten()
related_docs_indices=cosine_similarities.argsort()[::-1]
return list(news_df['TITLE'].iloc[related_docs_indices][:10])
#测试案例
test_title='Microsoft releases Windows 10 update'
print('基于 cosine 相似度的推荐结果:',cosine_recommendation(test_title))
结果
数据集
见上述资料