Per implementare a = (b/x[:, np.newaxis]).sum(axis=1)
, è possibile utilizzare a = b.sum(axis=1).A1/x
. L'attributo A1
restituisce l'array 1D n, quindi il risultato è un array 1D nd, non uno matrix
. Questa espressione concisa funziona perché si sono entrambi scala da x
e sommando lungo l'asse 1. Ad esempio:
In [190]: b
Out[190]:
<3x3 sparse matrix of type '<type 'numpy.float64'>'
with 5 stored elements in Compressed Sparse Row format>
In [191]: b.A
Out[191]:
array([[ 1., 0., 2.],
[ 0., 3., 0.],
[ 4., 0., 5.]])
In [192]: x
Out[192]: array([ 2., 3., 4.])
In [193]: b.sum(axis=1).A1/x
Out[193]: array([ 1.5 , 1. , 2.25])
Più in generale, se si vuole scalare le righe di una matrice sparsa con un vettore x
, si potrebbe moltiplicare b
a sinistra con una matrice sparsa contenente 1.0/x
sulla diagonale. La funzione scipy.sparse.spdiags
può essere utilizzata per creare una tale matrice. Per esempio:
In [71]: from scipy.sparse import csc_matrix, spdiags
In [72]: b = csc_matrix([[1,0,2],[0,3,0],[4,0,5]], dtype=np.float64)
In [73]: b.A
Out[73]:
array([[ 1., 0., 2.],
[ 0., 3., 0.],
[ 4., 0., 5.]])
In [74]: x = array([2., 3., 4.])
In [75]: d = spdiags(1.0/x, 0, len(x), len(x))
In [76]: d.A
Out[76]:
array([[ 0.5 , 0. , 0. ],
[ 0. , 0.33333333, 0. ],
[ 0. , 0. , 0.25 ]])
In [77]: p = d * b
In [78]: p.A
Out[78]:
array([[ 0.5 , 0. , 1. ],
[ 0. , 1. , 0. ],
[ 1. , 0. , 1.25]])
In [79]: a = p.sum(axis=1)
In [80]: a
Out[80]:
matrix([[ 1.5 ],
[ 1. ],
[ 2.25]])
Per essere chiari, si vuole divisione elemento-saggio lungo l'asse 1? cioè, tutti gli elementi 'N' di' b [i,:] 'sono divisi per' x [i] '? – askewchan
Sì. "Per essere chiari" è il motivo per cui ho incluso il codice. ;) – Juan