从 numpy 数组创建稀疏矩阵 [英] Creating a sparse matrix from numpy array
本文介绍了从 numpy 数组创建稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用 numpy 数组中的值创建一个矩阵.这些值应根据索引数组分布在矩阵线上.
像这样:
<预><代码>>>>价值观数组([ 0.73620381, 0.61843002, 0.33604769, 0.72344274, 0.48943796])>>>工业数组([0, 1, 2, 3, 2])>>>m = np.zeros((4, 5))>>>对于 enumerate(zip(inds, values)) 中的 i, (index, value):m[index, i] = 值>>>米数组([[ 0.73620381, 0. , 0. , 0. , 0. ],[ 0. , 0.61843002, 0. , 0. , 0. ],[ 0. , 0. , 0.33604769, 0. , 0.48943796],[ 0. , 0. , 0. , 0.72344274, 0. ]])我想知道是否有一种矢量化的方式来做到这一点,即没有循环.有什么建议吗?
解决方案
这里是如何使用 花式索引:
<预><代码>>>>价值观数组([ 0.73620381, 0.61843002, 0.33604769, 0.72344274, 0.48943796])>>>工业数组([0, 1, 2, 3, 2])>>>mshape = (4,5)>>>m = np.zeros(mshape)>>>m[inds,np.arange(mshape[1])] = 值>>>米数组([[ 0.73620381, 0. , 0. , 0. , 0. ],[ 0. , 0.61843002, 0. , 0. , 0. ],[ 0. , 0. , 0.33604769, 0. , 0.48943796],[ 0. , 0. , 0. , 0.72344274, 0. ]])I need to create a matrix with values from a numpy array. The values should be distributed over the matrix lines according to an array of indices.
Like this:
>>> values
array([ 0.73620381, 0.61843002, 0.33604769, 0.72344274, 0.48943796])
>>> inds
array([0, 1, 2, 3, 2])
>>> m = np.zeros((4, 5))
>>> for i, (index, value) in enumerate(zip(inds, values)):
m[index, i] = value
>>> m
array([[ 0.73620381, 0. , 0. , 0. , 0. ],
[ 0. , 0.61843002, 0. , 0. , 0. ],
[ 0. , 0. , 0.33604769, 0. , 0.48943796],
[ 0. , 0. , 0. , 0.72344274, 0. ]])
I'd like to know if there is a vectorized way to do it, i.e., without a loop. Any suggestions?
解决方案
Here's how you could do it with fancy indexing:
>>> values
array([ 0.73620381, 0.61843002, 0.33604769, 0.72344274, 0.48943796])
>>> inds
array([0, 1, 2, 3, 2])
>>> mshape = (4,5)
>>> m = np.zeros(mshape)
>>> m[inds,np.arange(mshape[1])] = values
>>> m
array([[ 0.73620381, 0. , 0. , 0. , 0. ],
[ 0. , 0.61843002, 0. , 0. , 0. ],
[ 0. , 0. , 0.33604769, 0. , 0.48943796],
[ 0. , 0. , 0. , 0.72344274, 0. ]])
这篇关于从 numpy 数组创建稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文