gpt4 book ai didi

python - 将字典转换为 coo_matrix

转载 作者:太空宇宙 更新时间:2023-11-04 00:24:57 25 4
gpt4 key购买 nike

我有这样一本字典,

{(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() 期望坐标在2 维 中:data 值存储实际数据值,位于相应坐标 中。这也反射(reflect)在 LightFM.fit() 中。文档。

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

每个坐标通常分别通过索引ij、行索引和列索引来引用,因为它们表示第 i 行和 j'第 列(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:](因为 中的 zero'eth 条目code>k is 0. Similarily for 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com