gpt4 book ai didi

python - 从 2D numpy 数组创建 COO 矩阵

转载 作者:行者123 更新时间:2023-11-30 22:24:18 26 4
gpt4 key购买 nike

我有一个看起来像这样的 2D numpy 数组,

[[3, 4, 5, 6], [4, 5, 6, 7], [9, 10, 3, 5]]

我使用以下代码将其转换为 COO 矩阵:

# Flatten 2D array
data = np.asarray(twod_array).flatten()
row = np.arange(0, len(data))
col = np.arange(0, len(row))
# Make COO matrix
mat = coo_matrix((data, (row, col)), shape=(len(row), len(row)))

这是将 2D numpy 数组转换为 COO 矩阵的正确方法吗?

编辑

我想做的是这样的,我在一列上有零件,在另一列上有项目。

parts                                 item
processor, display, sensor temp. monitoring system
fan baldes, motor, sensor motion detecting fan
. .
. .

我已将上面的数据转换为数字,以便进一步处理。

parts         items
1, 2, 3 1
4, 5, 3 2

现在,我想将上述数据输入 LightFM,所以我创建了一个像这样的 2D 数组。

[[1, 2, 3, 1], [4, 5, 3, 2]]

但是由于 LightFM 的 fit 方法仅接受形状为 [n_users, n_items] 的 np.float32 coo_matrix,这是一个包含用户-项目交互的矩阵。我使用上述方法转换了二维数组。

最佳答案

In [301]: A = np.array([[3, 4, 5, 6], [4, 5, 6, 7], [9, 10, 3, 5]])
In [302]: A
Out[302]:
array([[ 3, 4, 5, 6],
[ 4, 5, 6, 7],
[ 9, 10, 3, 5]])

创建矩阵的方法:

In [305]: data =A.flatten()
In [306]: M = sparse.coo_matrix((data,(np.arange(len(data)),np.arange(len(data))
...: )))
In [307]: M
Out[307]:
<12x12 sparse matrix of type '<class 'numpy.int32'>'
with 12 stored elements in COOrdinate format>

print(M) 将显示这 12 个值及其坐标。

如果它不是太大,我喜欢将矩阵显示为数组。 M.AM.toarray() 的快捷方式:

In [308]: M.A
Out[308]:
array([[ 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5]])

查看对角线 - 这是原始数组的 12 个值。那是你要的吗? A 原来的 3x4 布局完全丢失了。它也可能是这 12 个数字的一​​维列表。

或者,您可以将数组传递给稀疏构造函数,生成原始数组的稀疏副本

In [309]: M1 = sparse.coo_matrix(A)
In [310]: M1
Out[310]:
<3x4 sparse matrix of type '<class 'numpy.int32'>'
with 12 stored elements in COOrdinate format>
In [311]: M1.A
Out[311]:
array([[ 3, 4, 5, 6],
[ 4, 5, 6, 7],
[ 9, 10, 3, 5]])

这是一个没有任何 0 的 3x4 数组,而不是 12x12 对角线。如果 A 已经有很多 0,这更有意义。

你真的知道你需要什么样的稀疏矩阵吗?

关于python - 从 2D numpy 数组创建 COO 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47862425/

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