2017-04-17 98 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