我正在尝试制作一个电影推荐系统,这需要我为前100名用户
找到用户-用户的相似矩阵
。
运行代码时,我得到以下错误:
similarMatrix[row] = top100_similarIndexError: index 663 is out of bounds for axis 0 with size 617
代码如下:
def getUser_UserSimilarity(sparseMatrix, top = 100): startTimestamp20 = datetime.now() row_index, col_index = sparseMatrix.nonzero() #这会给出“row_index”中的行索引和“col_index”中的列索引,其中存在非零值。 rows = np.unique(row_index) similarMatrix = np.zeros(61700).reshape(617,100) # 617*100 = 61700。因为我们只为前100个最相似的用户构建相似矩阵。 timeTaken = [] howManyDone = 0 for row in rows[:top]: howManyDone += 1 startTimestamp = datetime.now().timestamp() #它会给出经过的秒数 sim = cosine_similarity(sparseMatrix.getrow(row), sparseMatrix).ravel() top100_similar_indices = sim.argsort()[-top:] top100_similar = sim[top100_similar_indices] similarMatrix[row] = top100_similar timeforOne = datetime.now().timestamp() - startTimestamp timeTaken.append(timeforOne) if howManyDone % 20 == 0: print("Time elapsed for {} users = {}sec".format(howManyDone, (datetime.now() - startTimestamp20))) print("Average Time taken to compute similarity matrix for 1 user = "+str(sum(timeTaken)/len(timeTaken))+"seconds") fig = plt.figure(figsize = (12,8)) plt.plot(timeTaken, label = 'Time Taken For Each User') plt.plot(np.cumsum(timeTaken), label='Cumulative Time') plt.legend(loc='upper left', fontsize = 15) plt.xlabel('Users', fontsize = 20) plt.ylabel('Time(Seconds)', fontsize = 20) plt.tick_params(labelsize = 15) plt.show() return similarMatrixsimMatrix = getUser_UserSimilarity(TrainUISparseData, 100)
请告诉我具体需要在哪里进行修改。
回答:
错误是由于以下这行代码引起的
similarMatrix = np.zeros(61700).reshape(617,100)
你的similarMatrix的维度比你的sparseMatrix小。这就是你得到索引错误的原因。
你需要使similarMatrix的维度与sparseMatrix的维度相同。因此,修改代码如下
similarMatrix = np.zeros(sparseMatrix.shape[0]*100).reshape(sparseMatrix.shape[0],100)
或者更简单的结构
n_cols = 100n_rows = sparseMatrix.shape[0]similarMatrix = np.zeros(n_rows*n_cols).reshape(n_rows, n_cols)