【问题标题】:User-Item rating matrix : IndexError用户项目评分矩阵:IndexError
【发布时间】:2018-07-04 10:54:42
【问题描述】:

我的数据框 urm 的形状为 (96438, 3)

user_id anime_id    user_rating
0   1   20  7.808497
1   3   20  8.000000
2   5   20  6.000000
3   6   20  7.808497
4   10  20  7.808497

我正在尝试建立一个项目用户评分矩阵:

X = urm[["user_id", "anime_id"]].as_matrix()
y = urm["user_rating"].values
n_u = len(urm["user_id"].unique())
n_m = len(urm["anime_id"].unique())

R = np.zeros((n_u, n_m))
for idx, row in enumerate(X):
    R[row[0]-1, row[1]-1] = y[idx]

如果代码成功,矩阵如下所示:(我用 0 填充 NaN)

在索引 user_id 中,anime_id 在列中,并为值评分(我从 pivot_table 中得到了这个矩阵)

在一些教程中它可以工作,但我有一个

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-278-0e06bd0f3133> in <module>()
     15 R = np.zeros((n_u, n_m))
     16 for idx, row in enumerate(X):
---> 17     R[row[0]-1, row[1]-1] = y[idx]

IndexError: index 5276 is out of bounds for axis 1 with size 5143

【问题讨论】:

  • 请提供minimal reproducible example。在这种情况下,错误与您的数据不匹配。此外,向我们展示您对逻辑输出的期望

标签: python pandas numpy indexoutofboundsexception


【解决方案1】:

我尝试了 dennlinger 的第二个建议,它对我有用。 这是我写的代码:

def id_to_index(df):
    """
    maps the values to the lowest consecutive values
    :param df: pandas Dataframe with columns user, item, rating
    :return: pandas Dataframe with the extra columns index_item and index_user
    """

    index_item = np.arange(0, len(df.item.unique()))
    index_user = np.arange(0, len(df.user.unique()))

    df_item_index = pd.DataFrame(df.item.unique(), columns=["item"])
    df_item_index["new_index"] = index_item
    df_user_index = pd.DataFrame(df.user.unique(), columns=["user"])
    df_user_index["new_index"] = index_user

    df["index_item"] = df["item"].map(df_item_index.set_index('item')["new_index"]).fillna(0)
    df["index_user"] = df["user"].map(df_user_index.set_index('user')["new_index"]).fillna(0)


    return df

【讨论】:

    【解决方案2】:

    我假设您有不连续的用户 ID(或电影 ID),这意味着存在具有

    • 没有评级,或
    • 没有电影

    在您的情况下,您正在设置矩阵维度,假设每个值都是连续的(因为您正在使用唯一值的数量定义维度),这会导致一些不连续的值超出范围.

    在这种情况下,您有两种选择:

    • 您可以通过urm["anime_id"].max() 将矩阵的大小定义为urm["user_id"].max()
    • 创建一个字典,将您的值映射到最低的连续值。

    第一种方法的缺点显然是它需要你存储一个更大的矩阵。此外,您可以使用scipy.sparse 根据您拥有的数据格式(通常称为coordinate matrix format)创建矩阵。
    潜在地,您可以执行以下操作:

    from scipy import sparse
    # scipy expects the data in (value_column, (x, y))
    mat = sparse.coo_matrix((urm["user_rating"], (urm["user_id"], urm["anime_id"]))
    # if you want it as a dense matrix
    dense_mat = mat.todense()
    

    然后你也可以按照我之前问过的第二个建议的方式工作here

    【讨论】:

    • 谢谢,我明白了,我会探讨你对稀疏矩阵的建议!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 2012-09-27
    • 1970-01-01
    • 2016-10-04
    • 2017-02-23
    相关资源
    最近更新 更多