python - 将字典转换为 coo_matrix

标签 python dictionary scipy sparse-matrix

我有一本这样的字典,

{(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

最佳答案

正如其他人在评论中指出的那样,coo_matrix() 期望坐标为二维:data 值存储位于相应坐标中的实际数据值。这也体现在 LightFM.fit()文档。

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

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

借用 coo_matrix() 中的示例文档:

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:] (因为 k0。类似地,对于 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])

关于python - 将字典转换为 coo_matrix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47852335/

相关文章:

python - 用with语句定义的变量在with block 之外可用吗?

python - 如何压缩这个?

python - 奇怪的 "symbolic boolean expression has no truth value"错误 - 这是 SymPy 中的错误吗?

python - 从Python脚本调用Matlab函数: "not enough values to unpack" ValueError

python - ERROR : a package requires another one, 未安装,Python

python - 过滤掉 ANSI 转义序列

python - 使用字典将 python 数据类型转换为其他语言的数据类型

python - 如何根据不同的关键字段对字典进行排序?

python - scipy.cluster.vq.kmeans2 中的 "Matrix is not positive definite"错误

Python SciPy : optimization issue fmin_cobyla : one constraint is not respected