八、基于内容的推荐算法。麻辣香锅菜品推荐。读取素材文件hot-spicy pot.csv,分析用户历史行为,推荐用户可能喜欢的菜品。 (1)正确导入模块 (2)读取数据 (3)将菜品的描述构成TF-IDF向量 (5)计算两个菜品的余弦相似度 (6)推荐函数,输出与其最相似的10个菜品 (7)根据菜名及特点进行推荐 (8)建立索引,方便使用菜名进行数据访问
时间: 2023-12-27 17:04:08 浏览: 55
以下是代码实现:
```python
# 导入模块
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# 读取数据
df = pd.read_csv('hot-spicy pot.csv')
# 将菜品的描述构成TF-IDF向量
tfidf = TfidfVectorizer()
tfidf_matrix = tfidf.fit_transform(df['description'])
# 计算两个菜品的余弦相似度
cosine_sim = cosine_similarity(tfidf_matrix)
# 推荐函数,输出与其最相似的10个菜品
def get_recommendations(title, cosine_sim=cosine_sim, df=df, top_k=10):
# 获取菜品的索引
indices = pd.Series(df.index, index=df['name']).drop_duplicates()
idx = indices[title]
# 计算该菜品与所有菜品的相似度,并按相似度排序
sim_scores = list(enumerate(cosine_sim[idx]))
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
# 取出相似度最高的前k个菜品的索引
top_indices = [i[0] for i in sim_scores[1:top_k+1]]
# 返回菜品名和描述
return df.iloc[top_indices][['name', 'description']]
# 根据菜名及特点进行推荐
recommendations = get_recommendations('重庆鸡公煲')
print(recommendations)
# 建立索引,方便使用菜名进行数据访问
df = df.set_index('name')
```
解释:
1. 首先导入需要的模块,包括 pandas、numpy、TfidfVectorizer 和 cosine_similarity。
2. 通过 pd.read_csv() 函数读取 hot-spicy pot.csv 文件,并保存为名为 df 的 DataFrame。
3. 使用 TfidfVectorizer 将每个菜品的描述构建成 TF-IDF 向量,并保存为名为 tfidf_matrix 的稀疏矩阵。
4. 使用 cosine_similarity 计算每两个菜品之间的余弦相似度,并保存为名为 cosine_sim 的矩阵。
5. 定义一个名为 get_recommendations() 的函数,该函数接受一个菜品名作为输入,并返回与该菜品最相似的前 k 个菜品的名称和描述。该函数首先根据菜品名获取菜品的索引,然后计算该菜品与所有菜品的相似度,并按相似度排序。最后,取出相似度最高的前 k 个菜品的索引,并返回它们的名称和描述。
6. 使用 get_recommendations() 函数,以重庆鸡公煲为例,推荐与其最相似的前 10 个菜品,并将结果保存为名为 recommendations 的 DataFrame。
7. 最后,通过 df.set_index() 函数将菜品名称设置为索引,方便使用菜名进行数据访问。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)