深度之眼推荐系统1V多项目小班

74 阅读2分钟

深度之眼推荐系统1V多项目小班

核心代码,注释必读

// download:3w ukoou com

推荐系统是一种利用历史用户行为数据对未来可能感兴趣的商品或内容进行预测的技术。本文将介绍如何使用Python和机器学习算法构建一个基于协同过滤的推荐系统,并提供具体代码实现。

数据准备

我们将使用MovieLens数据集,它包含了用户对电影评分的数据。该数据集可以从这里下载得到。下载后,我们需要导入以下两个文件:

  • ratings.csv:包含用户对电影的所有评分
  • movies.csv:包含电影的信息

首先,我们需要导入必要的库:

python复制代码
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split

然后,我们可以读取ratings.csv和movies.csv文件并将它们合并:

python复制代码
# 读取数据
ratings = pd.read_csv('ratings.csv')
movies = pd.read_csv('movies.csv')

# 合并数据
df = pd.merge(ratings, movies, on='movieId')

接下来,我们将根据评分数据创建一个用户-电影矩阵:

python复制代码
# 创建用户-电影矩阵
matrix = df.pivot_table(index='userId', columns='title', values='rating')

协同过滤算法

协同过滤算法是一种常用的推荐算法,它基于用户历史行为数据发现用户之间的相似性,从而推荐给用户可能感兴趣的内容。这里我们将使用基于用户的协同过滤算法。具体来说,我们需要计算用户之间的相似性,并根据相似性为每个用户推荐电影。

我们将使用余弦相似度作为相似性度量方法。其实现方法如下:

python复制代码
# 计算余弦相似度
def similarity(user1, user2):
    # 获取两个用户都评价过的电影
    movies = []
    for movie in matrix.columns:
        if not np.isnan(matrix.loc[user1, movie]) and not np.isnan(matrix.loc[user2, movie]):
            movies.append(movie)
    # 如果两个用户没有共同评价过任何电影,则相似度为0
    if len(movies) == 0:
        return 0
    # 计算余弦相似度
    vector1 = [matrix.loc[user1, movie] for movie in movies]
    vector2 = [matrix.loc[user2, movie] for movie in movies]
    return np.dot(vector1, vector2) / (np.linalg.norm(vector1) * np.linalg.norm(vector2))

然后,我们可以根据相似度为每个用户推荐电影:

python复制代码
# 为用户推荐电影
def recommend(user):
    # 查找相似度最高的用户
    sim_users = sorted([(similarity(user, other), other) for other in matrix.index if other != user], reverse=True)
    # 获取该用户没有评价过的电影
    movies = [movie for movie in matrix.columns if np.isnan(matrix.loc[user, movie])]
    # 计算每部电影的推荐度
    scores = []
    for movie in movies:
        score = 0
        for sim, other in sim_users:
            if not np.isnan(matrix.loc[other, movie]):
                score += sim * matrix.loc[other, movie]
        scores.append((score, movie))
    # 根据推荐度排序并返回推荐结果
    return sorted(scores, reverse=True)

测试模型

我们可以使用测试集评估模型的性能。这里,我们将随机选择一些用户,并从他们之前没有评价过的电影中进行推荐。

python复制代码
# 划分训练集和测试集
train_data, test_data = train_test_split(df, test_size=0.2, random_state=0)

# 构建用户-电影矩阵
train_matrix = train_data.pivot_table(index='userId',