1. 数据集

本博客用Movielens-1m数据集的ratings.dat作为推荐数据来训练MF推荐模型。第一列是用户id(user_id)、第二列是物品id(item_id)、第三列是用户对物品的评分(score)、第四列是时间戳(timestamp)。
在这里插入图片描述

在Movielens-1m数据集中,注意ratings.dat是用::作为分隔符的。。

2. 代码

import numpy as np
from tqdm import tqdm

def loadData(dataset_path, split="::"):
    '''
    加载数据
    :param dataset_path: 数据文件地址
    :return: 以用户id排序为主,同时按用户评分时间序列化的数据列表
    '''
    data_item_list = []
    # 一条数据项(data_item)内所包含的信息按顺序展示为:
    # userId::movieId::rating::timestamp (ml-1m)
    for data_item in open(dataset_path):
        # data_item_list存储的是元组类型的数据项:[(6040, 858, 4, 956703932), (1, 593, 3, 1112484661), ...]
        temp_tuple = list(data_item.strip().split(split)[:4])  # 分隔符,ml-1m上是"::",ml-20m上是","
        temp_tuple[0] = int(temp_tuple[0])  # 用户ID
        temp_tuple[1] = int(temp_tuple[1])  # 物品ID
        temp_tuple[2] = int(temp_tuple[2])  # 物品评分,ml-1m上评分是int,ml-20m上评分是float
        temp_tuple[3] = int(temp_tuple[3])  # 时间戳
        data_item_list.append(tuple(temp_tuple))
    # 根据该数据项产生的时间(timestamp:tup[3])和该数据项的用户id(userId:tup[0])对data_item_list进行排序
    data_item_list = sorted(data_item_list, key=lambda tup: tup[3])
    data_item_list = sorted(data_item_list, key=lambda tup: tup[0])
    return data_item_list  # 所返回的data_item_list是以用户id排序为主,同时按用户评分时间序列化的

def getUIMat(data):
    # 构造U-I评分矩阵
    user_list = [i[0] for i in data]
    item_list = [i[1] for i in data]
    UI_matrix = np.zeros((max(user_list) + 1, max(item_list) + 1))
    # 遍历历史数据,令uimat[u][i] = r
    for each_interaction in tqdm(data, total=len(data)):
        UI_matrix[each_interaction[0]][each_interaction[1]] = each_interaction[2]
    return UI_matrix

class MF():
    def __init__(self, R, K, alpha, beta, iterations):
        """
        执行矩阵分解,预测矩阵中的0项。
        参数
        - R (ndarray)   : user-item 评分矩阵
        - K (int)       : 隐特征维度
        - alpha (float) : 学习率
        - beta (float)  : 正则化参数
        """

        self.R = R
        self.num_users, self.num_items = R.shape
        self.K = K
        self.alpha = alpha
        self.beta = beta
        self.iterations = iterations

    def train(self):
        # 初始化用户和项目隐特征矩阵
        self.P = np.random.normal(scale=1./self.K, size=(self.num_users, self.K))
        self.Q = np.random.normal(scale=1./self.K, size=(self.num_items, self.K))

        # 初始化 biases
        self.b_u = np.zeros(self.num_users)
        self.b_i = np.zeros(self.num_items)
        self.b = np.mean(self.R[np.where(self.R != 0)])

        # 构建训练样本
        self.samples = [
            (i, j, self.R[i, j])
            for i in range(self.num_users)
            for j in range(self.num_items)
            if self.R[i, j] > 0
        ]

        # 迭代进行随机梯度下降
        training_process = []
        for i in tqdm(range(self.iterations), total=self.iterations):
            np.random.shuffle(self.samples)
            self.sgd()
            mse = self.mse()
            training_process.append((i, mse))
            # 每完成10%的训练迭代,就输出一次损失
            if (i == 0) or ((i+1) % (self.iterations / 10) == 0):
                print("Iteration: %d ; error = %.4f" % (i+1, mse))

        return training_process

    def mse(self):
        """
        均方误差损失
        """
        xs, ys = self.R.nonzero()
        predicted = self.full_matrix()
        error = 0
        for x, y in zip(xs, ys):
            error += pow(self.R[x, y] - predicted[x, y], 2)
        return np.sqrt(error)

    def sgd(self):
        """
        随机梯度下降
        """
        for i, j, r in self.samples:
            # 计算预测值和error
            prediction = self.get_rating(i, j)
            e = (r - prediction)

            # 更新 biases
            self.b_u[i] += self.alpha * (e - self.beta * self.b_u[i])
            self.b_i[j] += self.alpha * (e - self.beta * self.b_i[j])

            # 更新 user 和 item 隐特征矩阵
            self.P[i, :] += self.alpha * (e * self.Q[j, :] - self.beta * self.P[i,:])
            self.Q[j, :] += self.alpha * (e * self.P[i, :] - self.beta * self.Q[j,:])

    def get_rating(self, i, j):
        """
        获取预测评分 r_ij,其中i是用户id,j是项目id
        """
        prediction = self.b + self.b_u[i] + self.b_i[j] + self.P[i, :].dot(self.Q[j, :].T)
        return prediction

    def full_matrix(self):
        """
        获取完整的预测矩阵
        """
        return self.b + self.b_u[:,np.newaxis] + self.b_i[np.newaxis:,] + self.P.dot(self.Q.T)

if __name__ == "__main__":
    obs_dataset = loadData('./ratings.dat')  # 读取数据 ratings.dat
    R = getUIMat(obs_dataset) # 获取交互矩阵

    # alpha是学习率,不宜过大;beta是正则化系数,不宜过小
    mf = MF(R, K=2, alpha=0.1, beta=0.3, iterations=100)
    mf.train()

    # ------ 进行推荐 ------ #
    # 给用户1推荐top10
    each_user = 1
    user_ratings = mf.full_matrix()[each_user].tolist()
    topN = [(i, user_ratings.index(i)) for i in user_ratings] # 关联项目id及其评分
    topN = [i[1] for i in sorted(topN, key=lambda x:x[0], reverse=True)][:10]

    print("------ user ------")
    print(each_user)
    print("------ temp_topN ------")
    print(topN)

    # 给所有用户推荐Top10
    # user_list = [i[0] for i in obs_dataset]
    # for each_user in tqdm(list(set(user_list)), total=len(list(set(user_list)))):
    #     user_ratings = mf.full_matrix()[each_user].tolist()
    #     topN = [(i, user_ratings.index(i)) for i in user_ratings]  # 关联项目id及其评分
    #     # 对TopN列表排序,取出index,即项目id
    #     topN = [i[1] for i in sorted(topN, key=lambda x:x[0], reverse=True)][:10]
    #     print("------ each_user ------")
    #     print(each_user)
    #     print("------ temp_topN ------")
    #     print(temp_topN)

对用户1(user_id=1)产生一次推荐的输出结果(示例):

Iteration: 1 ; error = 19.0769
 10%|■■■■■■■■                                                                     | 1/10 [00:13<02:04, 13.79s/it] 
 Iteration: 2 ; error = 11.2177
 20%|■■■■■■■■■■■■■■■■                                                             | 2/10 [00:27<01:51, 13.90s/it] 
 Iteration: 3 ; error = 7.8996
 30%|■■■■■■■■■■■■■■■■■■■■■■■■                                                     | 3/10 [00:41<01:37, 13.89s/it] 
 Iteration: 4 ; error = 6.0109
 40%|■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■                                             | 4/10 [00:55<01:23, 13.91s/it] 
 Iteration: 5 ; error = 4.7724
 50%|■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■                                     | 5/10 [01:09<01:09, 13.90s/it] 
 Iteration: 6 ; error = 3.9248
 60%|■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■                             | 6/10 [01:23<00:55, 13.94s/it] 
 Iteration: 7 ; error = 3.2809
 70%|■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■                     | 7/10 [01:37<00:41, 13.99s/it] 
 Iteration: 8 ; error = 2.7991
 80%|■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■             | 8/10 [01:51<00:27, 13.97s/it] 
 Iteration: 9 ; error = 2.4106
 90%|■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■     | 9/10 [02:05<00:13, 13.90s/it] 
 Iteration: 10 ; error = 2.0992

------ user ------
1
------ temp_topN ------
[579, 1618, 2131, 576, 309, 892, 513, 1563, 106, 346]
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐