加载 .npy 文件会加载一个空数组

Posted

技术标签:

【中文标题】加载 .npy 文件会加载一个空数组【英文标题】:Loading .npy File Loads an Empty Array 【发布时间】:2017-04-17 16:49:27 【问题描述】:

我有一个大小为 TfIDF 的矩阵

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.
()

提前致谢。

【问题讨论】:

文件大小是多少(来自操作系统)? 大约 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]: ()

直接使用pickle:

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

【讨论】:

【参考方案2】:

哈哈。。 我刚做了。。

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 也适用于引用。

【讨论】:

大声笑...我仍然无法对参考 f 执行操作。 一个csr_matrix不是正则数组,不是np.save直接保存的。相反,它将它包装在一个 0d 对象数组中,稀疏矩阵为pickled。所以f.shape 是那个包装的形状。 f.item() 应该给你稀疏矩阵本身。

以上是关于加载 .npy 文件会加载一个空数组的主要内容,如果未能解决你的问题,请参考以下文章

从Google云存储中Numpy加载一个内存映射的数组(mmap_mode)

Numpy数组的保存与加载

在 pytorch 中加载多个 .npy 文件(大小 > 10GB)

Numpy 从谷歌云存储加载内存映射数组(mmap_mode)

numpy 保存/加载损坏数组

切片numpy加载文件如何加载到内存中