Python编译器在尝试查找相似矩阵时出现IndexError

我正在尝试制作一个电影推荐系统,这需要我为前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)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注