gpt4 book ai didi

python - 从 SQL 中高效地读取 Python 稀疏矩阵

转载 作者:太空宇宙 更新时间:2023-11-03 10:50:08 26 4
gpt4 key购买 nike

我在 MySQL 中有一个包含三列的表:行索引、列索引和值,我想将其读入 scipy csr_matrix。我使用 Python-MySQL 连接器。有 112,500 个非零元素。

尝试 1:

A = csr_matrix((N_rows, N_cols), dtype=float)
show = 'SELECT * FROM my_table'
cursor.execute(show)
for (row, col, value) in cursor:
A[row, col] = value

这太慢了,我不得不在 60 秒后停止它。它提到了效率警告,并建议使用 lil 矩阵。

尝试 2:

A = lil_matrix((N_rows, N_cols), dtype=float)
show = 'SELECT * FROM my_table'
cursor.execute(show)
for (row, col, value) in cursor:
A[row, col] = value
A = csr_matrix(A)

这需要 6.4 秒(三秒的平均值)。这是尽善尽美,还是有一种更快的方法可以在不通过循环的情况下创建 csr_matrix?如果我执行 cursor.fetchall(),数据如下所示:

[(row_0, col_0, value_0), (row_1, col_1, value_1), ...]

这不能用于 csr_matrix 构造函数。

最佳答案

cursor.fetchall()返回的数据几乎在coo_matrix中格式。你可以做

import numpy as np
from scipy.sparse import coo_matrix

data = cursor.fetchall()
#data = [(1, 2, 1.2), (3, 4, 7.1)]

arr = np.array(data, dtype=[('row', int), ('col', int), ('value', float)])
spmat = coo_matrix((arr['value'], (arr['row'], arr['col'])))

代替 np.array(cursor.fetchall(), ...) 你也可以最好使用

arr = np.fromiter(cursor, dtype=[('row', int), ('col', int), ('value', float)])

将数据库中的数据直接加载到 Numpy 数组中。

关于python - 从 SQL 中高效地读取 Python 稀疏矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25935864/

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