0

我正在尝试将我在 MATLAB 中的一个项目翻译成 Python+Numpy,因为 MATLAB 总是内存不足。我拥有的文件相当长,因此我尝试制作一个显示相同错误的最小示例。

基本上我正在制作数据集的二维直方图,并希望在经过一些处理后保存它。问题是当我尝试保存直方图函数的输出时,numpy.save 函数会抛出“ValueError:设置带有序列的数组元素”。当我查看 Numpy 的文档时,我找不到问题所在。

我的 Python 版本是 2.6.6,Debian 发行版上的 Numpy 版本是 1.4.1。

import numpy as np
import random

n_samples = 5
rows      = 5

out_file = file('dens.bin','wb')

x_bins = np.arange(-2.005,2.005,0.01)
y_bins = np.arange(-0.5,n_samples+0.5)

listy = [random.gauss(0,1) for r in range(n_samples*rows)]

dens = np.histogram2d( listy, \
       range(n_samples)*rows, \
       [y_bins, x_bins])

print 'Write data'
np.savez(out_file, dens)
out_file.close()

完整输出:

$ python error.py 
Write data
Traceback (most recent call last):
  File "error.py", line 19, in <module>
    np.savez(out_file, dens)
  File "/usr/lib/pymodules/python2.6/numpy/lib/io.py", line 439, in savez
    format.write_array(fid, np.asanyarray(val))
  File "/usr/lib/pymodules/python2.6/numpy/core/numeric.py", line 312, in asanyarray
   return array(a, dtype, copy=False, order=order, subok=True)
ValueError: setting an array element with a sequence.
4

1 回答 1

0

Note that np.histogram2d actually returns a tuple of three arrays: (hist, x_bins, y_bins). If you want to save all three of these, you have to unpack them as @Francesco said.

dens = np.histogram2d(listy,
                      range(n_samples)*rows,
                      [y_bins, x_bins])
np.savez('dens.bin', *dens)

Alternatively, if you only need the histogram itself, you could save just that.

np.savez('dens.bin', dens[0])

If you want to keep track of which of these is which, use the **kwds instead of the *args

denskw = dict(zip(['hist','y_bins','x_bins'], dens))
np.savez('dens.bin', **denskw)

Then, you can load it like

dens = np.load('dens.bin')
hist = dens['hist']# etc
于 2013-05-16T16:26:11.627 回答