推荐系统是一种信息过滤系统,用于预测用户对物品的评分或偏好。这个定义不是很好理解,因为它用“怎么做”来定义“是什么”,我们可以换个角度来理解:

推荐引擎

推荐引擎意在把最需要的推荐给用户。

在不同的机器学习场景中通常需要分析相似样本。而统计相似样本的方式可以基于欧氏距离分数,也可基于皮氏距离分数。

欧氏距离分数

$$

欧氏距离分数 = \frac{1}{1+欧氏距离}

$$

计算所得欧氏距离分数区间处于:[0, 1],越趋于0样本间的欧氏距离越远,样本越不相似;越趋于1,样本间的欧氏距离越近,越相似。

构建样本之间的欧氏距离得分矩阵:

$$

\left[ \begin{array}{c} & a & b & c & d & .. \\ a & 1 & 0.2 & 0.3 & 0.4 & .. \\ b & 0.2 & 1 & x & x & .. \\ c & 0.3 & x & 1 & x & .. \\ d & 0.4 & x & x & 1 & .. \\ .. & .. & .. & .. & .. & .. \\ \end{array} \right]

$$

案例:解析ratings.json,根据每个用户对已观看电影的打分计算样本间的欧氏距离,输出欧氏距离得分矩阵。

import json
import numpy as np

with open('../data/ratings.json', 'r') as f:
    ratings = json.loads(f.read())
users, scmat = list(ratings.keys()), []
for user1 in users:
    scrow = []
    for user2 in users:
        movies = set()
        for movie in ratings[user1]:
            if movie in ratings[user2]:
                movies.add(movie)
        if len(movies) == 0:
            score = 0
        else:
            x, y = [], []
            for movie in movies:
                x.append(ratings[user1][movie])
                y.append(ratings[user2][movie])
            x = np.array(x)
            y = np.array(y)
            score = 1 / (1 + np.sqrt(((x - y) ** 2).sum()))
        scrow.append(score)
    scmat.append(scrow)
users = np.array(users)
scmat = np.array(scmat)
for scrow in scmat:
    print('  '.join('{:.2f}'.format(score) for score in scrow)) 

皮尔逊相关系数

A = [1,2,3,1,2] 
B = [3,4,5,3,4] 
m = np.corrcoef(A, B)

皮尔逊相关系数 = 协方差 / 标准差之积

相关系数处于[-1, 1]区间。越靠近-1代表两组样本反相关,越靠近1代表两组样本正相关。

案例:使用皮尔逊相关系数计算两用户对一组电影评分的相关性。