【问题标题】:Convert dictionary to coo_matrix将字典转换为 coo_matrix
【发布时间】:2018-05-30 20:15:16
【问题描述】:

我有一本这样的字典,

{(0, 1, 2, 3, 0, 0): 0, (19, 49, 0, 0, 0, 0): 12, (85, 1, 87, 0, 0, 0): 22, (78, 79, 80, 81, 0, 0): 20, (0, 17, 18, 19, 0, 0): 8, (24, 25, 26, 27, 0, 0): 6, (62, 63, 64, 65, 0, 0): 16}

如何将其转换为 coo_matrix?我尝试了以下但我得到Error: int object is not subscriptable

data,row, col = [], [], []
 for k, v in diction.items():
     r = int(k[0][1:])
     c = int(k[1][1:])
     data.append(v)
     row.append(r-1)
     col.append(c-1)
     # Create the COO-matrix
 coo = coo_matrix((data,(row,col)))

我需要这样做,因为 LightFM.fit 方法只接受 coo 矩阵作为参数。

预期输出(coo 矩阵)

(0, 1, 2, 3, 0, 0)      0
(19, 49, 0, 0, 0, 0)    12
(85, 1, 87, 0, 0, 0)    22

【问题讨论】:

  • 这个的预期输出是什么?
  • @RoadRunner 请查看编辑
  • 我知道(或期望)他们想要什么。但是你似乎是 ML 的新手,应该先掌握这些基本的数据格式,然后再问这样的问题。尝试将您的预期输出转换为 MATRIX 形式。这就是 coo_matrix 能给你的全部。如果您的预期输出不像您的预期输出那样是矩阵(2-d!),那么您无法做到这一点。您可能要求 one_hot_encoding 或其他一些预处理。但这与 scipy 的稀疏矩阵没有太大关系。格式非常标准,您将从 scikit-learn 的文档中学到很多东西。访问它并阅读预处理教程。
  • 并且由于您的项目用户又名矩阵分解模型有点特殊,因此事情变得更简单(与我上面的评论相比)。但是你所展示的和这个模型的映射,嗯......我没有看到。这些矩阵的稀疏表示通常具有 3 个值;项目用户价值。现在将其与您的(维度太多)进行比较。并确保您知道矩阵和张量之间的区别!用于(低阶)张量分解的(工作)软件并不多。
  • 这行不通。看起来你想要一个 6d 数组。 scipy sparse 包只创建二维矩阵。

标签: python dictionary scipy sparse-matrix


【解决方案1】:

正如其他人在 cmets 中指出的那样,coo_matrix() 期望坐标为 2 维rowscolumnsdata 值存储实际数据值,即位于对应坐标中。这也反映在LightFM.fit() 文档中。

这个概念可能不清楚,我将尝试对文档中给出的解释做出另一种解释:三个输入 datarow 必须具有相同的长度;并且是一维的。

每个坐标通常分别通过索引 ij、row-index 和 column-index 引用,因为它们表示第 i 行和 j'第列(á la matrix_row[i]matrix_column[j])。

借鉴coo_matrix() docs 中的示例:

row  = np.array([0, 3, 1, 0])
col  = np.array([0, 3, 1, 2])
data = np.array([4, 5, 7, 9])

for value, i, j in zip(data, row, col):
    print("In the {}'th row, on the {}'th column, insert the value {}"
          .format(i, j, value))
print("All other values are 0, because it's sparse.")

coo_matrix((data, (row, col)), shape=(4, 4)).toarray()

输出:

In the 0'th row, on the 0'th column, insert the value 4
In the 3'th row, on the 3'th column, insert the value 5
In the 1'th row, on the 1'th column, insert the value 7
In the 0'th row, on the 2'th column, insert the value 9
All other values are 0, because it's sparse.

array([
   [4, 0, 9, 0],
   [0, 7, 0, 0],
   [0, 0, 0, 0],
   [0, 0, 0, 5]
])

代码注释:

Error: int object is not subscriptable 错误可能来自您的代码,您尝试在其中下标k,这是您的,例如你的第一个k 将是(0, 1, 2, 3, 0, 0)

当您执行r=int(k[0][1:]) 时,您尝试获取0[1:](因为k 中的zero'eth 条目是0。同样对于c = int(k[1][1:])k[1]1,所以k[1][1:] 是尝试做1[1:]

另外,int() 也行不通。如果您想要转换列表中的每个元素,请使用numpy.array.astype()。例如。 np.array([1.2, 3, 4.4]).astype(int) 会给array([1, 3, 4])

【讨论】:

    猜你喜欢
    • 2018-11-12
    • 2011-09-19
    • 2019-02-06
    • 2018-08-21
    • 1970-01-01
    • 2015-07-28
    • 2013-02-19
    • 2016-10-16
    • 2020-02-01
    相关资源
    最近更新 更多