嵌套字典存储和一维numpy数组的矩阵乘法

时间:2018-08-31 23:02:24

标签: python arrays numpy

所以我想做一个基本矩阵乘以x,所以Ax = b 但是A是包含稀疏矩阵的“字典”(仅给出非零的条目),而x是1d numpy数组。例如

A = {0: {2: 2, 3: 3}, 1: {3: 5}, 3: {1: 10}}

看起来像

<img src="http://latex.codecogs.com/gif.latex?$$\begin{bmatrix}&space;0&space;&&space;0&&space;2&space;&&space;3\\&space;0&space;&&space;0&space;&&space;0&space;&&space;5\\&space;0&&space;0&space;&&space;0&space;&&space;0\\&space;0&&space;10&&space;0&&space;0&space;\end{bmatrix}$$" title="$$\begin{bmatrix} 0 & 0& 2 & 3\\ 0 & 0 & 0 & 5\\ 0& 0 & 0 & 0\\ 0& 10& 0& 0 \end{bmatrix}$$" />

x是一个一维的numpy数组,所以

x = np.array([1, 1, 1, 1]) #x1 x2 x3 x4
x
for i in x:
    print(i)

最后,我希望结果Ax也是1d numpy数组(A为4 x 4,x为4 x 1,因此A * x也必须为4 x 1)。因此输出应为

Ax = np.array([5, 5, 0, 10])

仅给出稀疏矩阵,有没有办法以正确的顺序对A进行矩阵乘法?

1 个答案:

答案 0 :(得分:3)

第一个解决方案使用来自scipy的坐标格式的稀疏矩阵(请参见coo_matrix):

from scipy.sparse import coo_matrix

rows, cols, data = zip(*[(row, col, A[row][col]) for row in A for col in A[row]])
coo = coo_matrix((data, (rows, cols)))

>>> coo.toarray()
array([[ 0,  0,  2,  3],
       [ 0,  0,  0,  5],
       [ 0,  0,  0,  0],
       [ 0, 10,  0,  0]])

coo.dot(x)
>>> array([ 5,  5,  0, 10])

第二种解决方案仅将python和numpy用于NaN,并保存最终数组:

rows = range(min(A.keys()), 1 + max(A.keys()))

result = []
for row in rows:
    row_data = A.get(row)
    result.append(sum(A_val * x[col]
                      for col, A_val in row_data.iteritems())  # .items() for Python 3
                  if row_data else np.nan)
Ax = np.array(result)

>>> Ax
array([  5.,   5.,  nan,  10.])