[英]Assign a the value of a sparse matrix to numpy array
import numpy as np
import scipy.sparse as scsp
from scipy.sparse import csr_matrix,lil_matrix
# create an empty numpy matrix
wi=np.empty((num_clusters*num_cluster_neurons, input))
for i in range(num_clusters*num_cluster_neurons):
temp_neuron_prob=dic_cluster_prob[dic_neuron_cluster[i]]
#create 1*input shape sparse matrix according to probability
lil=lil_matrix(scsp.rand(1, input, temp_neuron_prob))
#want to assign the 1*input sparse matrix to one slice of the numpy matrix
wi[i,:]=lil[:]
我試圖將lil_matrix的值分配給一片numpy數組,但是它給出了錯誤“使用序列設置數組元素”
我想知道為什么會出現此錯誤,因為它們具有相同的大小,並且我怎么做才能提高效率,因為numpy數組比稀疏矩陣(lil_matrix)更快。
我想使用numpy數組來使稀疏矩陣創建的值
稀疏矩陣不是數組的子類(例如np.matrix
),也不一定表現出類似的行為(盡管它確實嘗試了許多方式)。
In [129]: arr = np.zeros((3,4),int)
In [130]: M = sparse.lil_matrix([0,1,2,0])
In [131]: M.shape
Out[131]: (1, 4)
In [132]: arr[0,:] = M
...
ValueError: setting an array element with a sequence.
但是,如果我首先將稀疏矩陣轉換為數組或矩陣,則分配有效:
In [133]: arr[0,:] = M.A
In [134]: arr[0,:] = M.todense()
In [135]: arr
Out[135]:
array([[0, 1, 2, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
通常,稀疏矩陣不能插入numpy
代碼。 例外是當numpy
代碼將任務委托給對象自己的方法時。
看起來您正在嘗試生成以下內容:
In [148]: arr = np.zeros((3,5),float)
In [149]: for i in range(arr.shape[0]):
...: arr[i,:] = sparse.rand(1,5, .2*(i+1)).A
...:
In [150]: arr
Out[150]:
array([[ 0. , 0. , 0.82470353, 0. , 0. ],
[ 0. , 0.43339367, 0.99427277, 0. , 0. ],
[ 0. , 0.99843277, 0.05182824, 0.1705916 , 0. ]])
純稀疏等效項可能是:
In [151]: alist = []
In [152]: for i in range(3):
...: alist.append(sparse.rand(1,5, .2*(i+1)))
...:
...:
In [153]: alist
Out[153]:
[<1x5 sparse matrix of type '<class 'numpy.float64'>'
with 1 stored elements in COOrdinate format>,
<1x5 sparse matrix of type '<class 'numpy.float64'>'
with 2 stored elements in COOrdinate format>,
<1x5 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements in COOrdinate format>]
In [154]: sparse.vstack(alist)
Out[154]:
<3x5 sparse matrix of type '<class 'numpy.float64'>'
with 6 stored elements in COOrdinate format>
In [155]: _.A
Out[155]:
array([[ 0. , 0. , 0. , 0.19028467, 0. ],
[ 0. , 0. , 0. , 0.92668274, 0.67424419],
[ 0.96208905, 0.63604635, 0. , 0.69463657, 0. ]])
但是考慮到sparse.vstack
使用稀疏bmat
將矩陣連接到一個新矩陣中,並且bmat
結合了組件的coo
屬性,因此密集數組累積方法可能會更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.