[英]sparse CSR matrix into 1-dim
我一直在嘗試重塑我的矩陣:
數組([<320000x799928 類型的稀疏矩陣 '<class 'numpy.float64'>' 具有 2929143 個以壓縮稀疏行格式存儲的元素>],dtype=object)
到一個 1 暗矩陣,因為我想將它輸入到神經網絡中。 經典的轉換都不起作用。 我嘗試了重塑、展平、.todense 和 .toarray
知道這里會發生什么嗎?
顯示為:
array([<320000x799928 sparse matrix of type '<class 'numpy.float64'>' with 2929143 stored elements in Compressed Sparse Row format>], dtype=object)
是單個元素(形狀(1,)) numpy
數組,對象 dtype。 元素是稀疏矩陣,但數組本身不是。
從一個小的稀疏矩陣A
開始,我可以制作一個像你一樣顯示的數組:
In [101]: arr = np.array([A])
In [102]: arr
Out[102]:
array([<3x3 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements in Compressed Sparse Row format>],
dtype=object)
In [103]: arr.shape
Out[103]: (1,)
這已經是一個一維數組 - 但不是數字。
我可以通過以下方式訪問該元素:
In [104]: arr[0]
Out[104]:
<3x3 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements in Compressed Sparse Row format>
In [105]: print(arr[0])
(0, 0) 1.0
(1, 1) 1.0
(2, 2) 1.0
並將toarray
(或todense
)應用於它:
In [106]: arr[0].toarray()
Out[106]:
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
todense
將制作一個np.matrix
。
一旦它是一個ndarray
,它就可以被展平
In [107]: arr[0].toarray().ravel()
Out[107]: array([1., 0., 0., 0., 1., 0., 0., 0., 1.])
稀疏矩陣本身可以重塑為 1 行矩陣。 但只要它是sparse
的,它就必須保持 2d。
In [109]: arr[0].reshape(1,9)
Out[109]:
<1x9 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements in COOrdinate format>
In [110]: arr[0].reshape(1,9).A
Out[110]: array([[1., 0., 0., 0., 1., 0., 0., 0., 1.]])
np.matrix
有一個屬性,它返回一個 raveled 1d 數組:
In [115]: arr[0].todense().A1
Out[115]: array([1., 0., 0., 0., 1., 0., 0., 0., 1.])
但是對於使用toarray
(或todense
)非常謹慎。 對於這些尺寸,數組對於大多數內存來說太大了:
In [118]: 320000*799928*8/1e9
Out[118]: 2047.81568
它作為一個稀疏矩陣工作,因為只有一小部分值是非零的
In [119]: 2929143/(320000*799928)
Out[119]: 1.1442994713274194e-05
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.