Python编译器在试图找到相似矩阵时给出IndexError



我正在尝试制作一个电影推荐系统,该系统要求我为top 100 users找到用户用户similarity matrix

运行代码我得到:

similarMatrix[row] = top100_similar
IndexError: 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()  #this will give indices of rows in "row_index" and indices of columns in 
#"col_index" where there is a non-zero value exist.
rows = np.unique(row_index)
similarMatrix = np.zeros(61700).reshape(617,100)    # 617*100 = 61700. As we are building similarity matrix only 
#for top 100 most similar users.
timeTaken = []
howManyDone = 0
for row in rows[:top]:
howManyDone += 1
startTimestamp = datetime.now().timestamp()  #it will give seconds elapsed
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 similarMatrix

simMatrix = getUser_UserSimilarity(TrainUISparseData, 100)

请告诉我具体需要在哪里修改。

错误是由于以下行

similarMatrix = np.zeros(61700).reshape(617,100) 
你的<<p> strong> similarMatrix 尺寸小于sparseMatrix. 这就是为什么你得到索引错误。

你需要使similarMatrix的维数等于sparsemmatrix的维数。因此,将代码修改如下

similarMatrix = np.zeros(sparseMatrix.shape[0]*100).reshape(sparseMatrix.shape[0],100) 

或者更简单的结构

n_cols = 100
n_rows = sparseMatrix.shape[0]
similarMatrix = np.zeros(n_rows*n_cols).reshape(n_rows, n_cols)

最新更新