【问题标题】:Predicting Values in Movie Recommendations电影推荐中的预测值
【发布时间】:2018-02-16 06:16:32
【问题描述】:

我一直在尝试使用 python 中的 movielens 数据集创建推荐系统。我的目标是确定用户之间的相似度,然后以这种格式为每个用户输出推荐的前五部电影:

User-id1 movie-id1 movie-id2 movie-id3 movie-id4 movie-id5
User-id2 movie-id1 movie-id2 movie-id3 movie-id4 movie-id5

我现在使用的数据是这个ratings 数据集。

这是目前为止的代码:

import pandas as pd
import numpy as np
from sklearn import cross_validation as cv
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import mean_squared_error
from math import sqrt
import scipy.sparse as sp
from scipy.sparse.linalg import svds
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.read_csv('ratings.csv')


df.drop('timestamp', axis=1, inplace=True)
n_users = df.userId.unique().shape[0]
n_items = df.movieId.unique().shape[0]

#Pivot table so users are rows and movies are columns, ratings are then values
df = df.pivot(index='userId', columns='movieId', values='rating')

#subtract row mean from each rating to center data
df = df.sub(df.mean(axis=1), axis=0)

#copy to fill in predictions
c1 = df.copy()
c1 = c1.fillna('a')

#second copy to find which values were filled in and return the highest rated values
c2 = c1.copy()

#fill NAN with 0
df = df.fillna(0)


#Get cosine similarity between rows
similarity = pd.DataFrame(cosine_similarity(df))

#get top 5 similar profiles
tmp = similarity.apply(lambda row: sorted(zip(similarity.columns, row), key=lambda c: -c[1]), axis=1)
tmp = tmp.ix[:,1:6]
l = np.array(tmp)

##Prediction function - does not work needs improvement
def predict(df, c1, l):
for i in range(c1.shape[0]):
    for j in range(i+1, c1.shape[1]):
        try:
            if c1.iloc[i][j] == 'a':
                num = df[l[i][0][0]]*l[i][0][1] + df[l[i][1][0]]*l[i][1][1] + df[l[i][2][0]]*l[i][2][1] + df[l[i][3][0]]*l[i][3][1] + df[l[i][4][0]]*l[i][4][1]
                den = l[i][0][1] + l[i][1][0] + l[i][2][0] + l[i][3][0] + l[i][4][0]
                c1[i][j] = num/den
        except:
            pass
return c1

res = predict(df, c1, l)
print(res)

res = predict(df, c1, l)
print(res)

我正在尝试实现预测功能。我想预测缺失值并将它们添加到 c1。我正在尝试实现this。公式以及如何使用它的示例在图片中。如您所见,它使用了最相似用户的相似度分数。

相似度的输出是这样的:例如这里是user1的相似度:

[(34, 0.19269904365720053) (196, 0.19187531680008307)
 (538, 0.14932027335788825) (67, 0.14093020024386654)
 (419, 0.11034407313683092) (319, 0.10055810007385564)]

我需要使用预测函数中的这些相似性来预测缺失的电影评分的帮助。如果解决了这个问题,我将不得不为每个用户找到推荐的前 5 部电影,并以上述格式输出。

我目前需要预测功能方面的帮助。任何建议都有帮助。如果您需要更多信息或说明,请告诉我。

感谢您的阅读

【问题讨论】:

  • 您遇到的错误是什么?
  • 我的主要问题是我不确定如何根据类似用户正确预测未看过电影的用户的新值。
  • 如果您有类似的用户,观看他们的电影很简单,那么问题是什么?
  • 我无法使用上述公式来预测用户的评分。我不确定如何准确地构造函数。

标签: python pandas numpy dataframe recommendation-engine


【解决方案1】:

首先,矢量化使复杂的问题变得更加容易。这里有一些建议可以改善你已经拥有的东西

  1. 将用户 ID 用作数据透视表中的列,这使得预测示例更易于查看
  2. NaN 代表缺失值,在概念上与 0 不同,在这种特殊情况下,一个大的负数就可以了,而且只有在使用余弦相似度函数时才需要
  3. 利用 pandas 的高级功能,例如要保留原始值但添加预测,可以使用 fillna
  4. 在构造similarity 数据框时,一定要跟踪useIds,您可以通过将索引和列设置为df.columns 来做到这一点

这是我编辑的代码版本,包括预测实现:

```

import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.preprocessing import scale


def predict(l):
    # finds the userIds corresponding to the top 5 similarities
    # calculate the prediction according to the formula
    return (df[l.index] * l).sum(axis=1) / l.sum()


# use userID as columns for convinience when interpretering the forumla
df = pd.read_csv('ratings.csv').pivot(columns='userId',
                                                index='movieId',
                                                values='rating')

similarity = pd.DataFrame(cosine_similarity(
    scale(df.T.fillna(-1000))),
    index=df.columns,
    columns=df.columns)
# iterate each column (userID),
# for each userID find the highest five similarities
# and use to calculate the prediction for that user,
# use fillna so that original ratings dont change

res = df.apply(lambda col: ' '.join('{}'.format(mid) for mid in col.fillna(
    predict(similarity[col.name].nlargest(6).iloc[1:])).nlargest(5).index))
print(res)

```

这里是输出示例

userId
1    1172 1953 2105 1339 1029
2           17 39 150 222 265
3      318 356 1197 2959 3949
4          34 112 141 260 296
5    597 1035 1380 2081 33166
dtype: object

编辑

上面的代码将推荐前 5 名,无论用户是否已经观看/评分。为了解决这个问题,我们可以在选择推荐时将原始评分的值重置为 0,如下所示\

res = df.apply(lambda col: ' '.join('{}'.format(mid) for mid in (0 * col).fillna(
    predict(similarity[col.name].nlargest(6).iloc[1:])).nlargest(5).index))

输出

userId
1           2278 4085 3072 585 256
2               595 597 32 344 316
3              590 457 150 380 253
4         1375 2571 2011 1287 2455
5              480 590 457 296 165
6          1196 7064 26151 260 480
....

【讨论】:

  • 哦,我明白了,谢谢,您的解决方案真是太棒了!一个快速的问题在我上面的代码中,我减去了每一行的平均值以使观察居中并确保余弦相似度是准确的,这段代码是否实现了相同的效果?
  • 不客气。我已经编辑了代码以包含规范化。使用比例,我已经编辑了代码。
猜你喜欢
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-17
  • 2017-03-26
相关资源
最近更新 更多