首页 > 解决方案 > ijv mpmath 矩阵的稀疏矩阵表示(coo_matrix 等效)

问题描述

显然 coo_matrix 不适用于 mapmath 矩阵。是否有任何等效的实现或简单的算法来实现 mpmath?

import mpmath
import numpy as np 
from scipy.sparse import coo_matrix

A = np.diag([1]*5)
A_coo = coo_matrix(A)
print(A_coo.row)
print(A_coo.col)
print(A_coo.data)


A_mp = mpmath.diag([1]*5)
A_mp_coo = coo_matrix(A_mp)
print(A_mp_coo.row)
print(A_mp_coo.col)
print(A_mp_coo.data)

输出

[0 1 2 3 4]
[0 1 2 3 4]
[1 1 1 1 1]
# ----------------------
[0 0 0 0 0]
[ 0  6 12 18 24]
[mpf('1.0') mpf('1.0') mpf('1.0') mpf('1.0') mpf('1.0')]

编辑:

我认为是遍历每个元素并找到 mpmath 矩阵的非零元素的 i,j 索引,然后使用以下命令:

size=np.count_nonzero(A_mp)
rows, cols = ... # looping over evey elements to find the indices on nonzero elements

compactMatrix = np.zeros((3, size))
for i in range(size):
    compactMatrix[0, i] = rows[i]
    compactMatrix[1, i] = cols[i]
    compactMatrix[2, i] = A_mp[rows[i], cols[i]]

但它似乎变天真而不快。

标签: pythonsparse-matrixmpmath

解决方案


这就是我想出的:我测试了它的方阵。

首先是一些辅助函数:

def to_single_index(i, j, N):
    return N * i + j

def from_single_index(indices, N):
    i_list = []
    j_list = []
    for k in indices:
        i_list.append(k // N)
        j_list.append(k % N)

    return np.array(i_list), np.array(j_list)

def to_mp_matrix(a):

    m, n = a.shape
    A = mpmath.matrix(m,n)
    for i in range(m):
        for j in range(n):
            A[i,j] = a[i, j]
    return A

制作一个稀疏有向矩阵来测试代码:

N = 5
A = nx.to_numpy_array(nx.gnp_random_graph(
    N, 0.5, seed=2, directed=True))

使用 coo_matrix 检查正确性:

A_coo = coo_matrix(A)
i = A_coo.row
j = A_coo.col
print(i)
print(j)

# [0 0 1 2 3 3 4 4]
# [3 4 4 4 0 1 2 3]

转换为 mpmath 矩阵并获取非零元素的索引:

A_mp = to_mp_matrix(A)
indices = np.nonzero(A_mp)[0]
print(indices)
# [ 3  4  9 14 15 16 22 23]

在mamath矩阵上测试代码:

indices = to_single_index(i, j, N)
print(indices)
# [ 3  4  9 14 15 16 22 23]

i_list, j_list = from_single_index(indices, N)
print(i_list)
print(j_list)
# [0 0 1 2 3 3 4 4]
# [3 4 4 4 0 1 2 3]

推荐阅读