2017-04-17 105 views
0

我有大小的TFIDF矩陣加載.npy文件加載一個空數組

tr_tfidf_q1.shape, tr_tfidf_q2.shape which gives 
((404288, 83766), (404288, 83766)) 

現在我保存它使用

np.save('tr_tfidf_q1.npy', tr_tfidf_q1) 

當我加載像這樣

f = np.load('tr_tfidf_q1.npy') 
f.shape() ## returns an empty array. 
() 
文件

提前致謝。

+0

什麼是文件(從OS)的尺寸新的功能? – hpaulj

+0

其大約37MB。但我現在可以將它作爲一個數組來使用。 –

回答

1
In [172]: from scipy import sparse 
In [173]: M=sparse.csr_matrix(np.eye(10)) 
In [174]: np.save('test.npy',M) 


In [175]: f=np.load('test.npy') 
In [176]: f 
Out[176]: 
array(<10x10 sparse matrix of type '<class 'numpy.float64'>' 
    with 10 stored elements in Compressed Sparse Row format>, dtype=object) 

請注意dtype=object包裝。這已經形成(),0d。稀疏矩陣不是常規數組或子類。因此,np.save會將其包裝到一個對象數組中,並讓該對象自己的pickle方法負責編寫。

In [177]: f.item() 
Out[177]: 
<10x10 sparse matrix of type '<class 'numpy.float64'>' 
    with 10 stored elements in Compressed Sparse Row format> 
In [178]: f.shape 
Out[178]:() 

使用泡菜直接:

In [181]: with open('test.pkl','wb') as f: 
    ...:  pickle.dump(M,f) 

In [182]: with open('test.pkl','rb') as f: 
    ...:  M1=pickle.load(f)  
In [183]: M1 
Out[183]: 
<10x10 sparse matrix of type '<class 'numpy.float64'>' 
    with 10 stored elements in Compressed Sparse Row format> 

最新scipy版本有救了稀疏矩陣

https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.save_npz.html

0

大聲笑.. 我只是做了..

f = np.load('tr_tfidf.npy') 
f ## returns the below. 

array(<404288x83766 sparse matrix of type '<class 'numpy.float64'>' 
with 2117757 stored elements in Compressed Sparse Row format>, dtype=object) 

我相信XYZ.shape可與引用爲好。

+0

大聲笑......我仍然無法對參考文獻f進行操作。 –

+1

'csr_matrix'不是一個常規數組,並且不是由'np.save'直接保存的。相反,它將它包裝在一個0d對象數組中,稀疏矩陣被「pickled」。所以'f.shape'就是這個包裝的形狀。 'f.item()'應該給你自己的稀疏矩陣。 – hpaulj