python - 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]]
但它似乎变天真而不快。
解决方案
这就是我想出的:我测试了它的方阵。
首先是一些辅助函数:
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]
推荐阅读
- javascript - JavaScript 将数据分组到 2 层深的树视图中,最后一层是数组
- mysql - 加入动态表时是否使用索引?
- vim - 如何在 INSERT 模式下使用 vim 普通模式命令(遍历文本)
- java - DynamoDBAttribute 上的 AWS DynamoDB 约束
- javascript - javascript 常量行为
- python - 合并两个没有 on 参数的 dfs
- scala - 检查 spark 中是否存在嵌套列
- python-3.x - 使用 Keras 训练模型时出现内存不足错误
- django - Django 教程第 5 部分。Indexview 测试没有收到消息“没有可用的民意调查”。
- angularjs - 高图 - 堆积条形聊天:如何在堆积条形图类型中添加中位数