【问题标题】:RuntimeWarning: overflow encountered in reduce, np.sum result is infRuntimeWarning:reduce遇到溢出,np.sum结果为inf
【发布时间】:2021-07-02 23:11:22
【问题描述】:

我有两个hdf5文件,第一个文件数据形状为(1, 10240),np.sum值为51260.0。第二个文件数据形状也是(1, 10240),np.sum 值为 51070.0。但是当我读取两个文件并附加到一个列表时,np.sum 结果为inf,并报告此信息:

/usr/lib64/python2.7/site-packages/numpy-1.14.5-py2.7-linux-x86_64.egg/numpy/core/_methods.py:32: 
RuntimeWarning: overflow encountered in reduce
  return umr_sum(a, axis, dtype, out, keepdims)

代码如下:

datas = []
for filename in os.listdir("path/"):
    filename = "path/" + filename
    data = h5py.File(filename)
    datas.append(list(data.get(key).value.reshape(-1)))
    data.close()
print np.sum(datas)

如果我只读取一个文件,代码是可以的,np.sum 结果也可以。

当我读取两个文件时,为什么np.suminf

【问题讨论】:

  • 能否添加完整的回溯错误
  • 没有错误,但是np.sum结果是inf,并报RuntimeWarning: overflow encountered in reduce@AnuragDhadse
  • 你能打印出 data[key].dtype 的输出吗?同样要调试,您可以先写入两个变量(NumPy 数组)并检查它们

标签: python python-2.7 numpy hdf5


【解决方案1】:

您的代码没有明显错误。您可以使用这个简单的示例进行验证。您使用.append 创建datas 作为列表列表。我用.extend() 添加了第二种方法来获得一个列表。两者都给出相同的结果。

arr1 = np.array([1,2,3])
arr2 = np.array([11,22,33])
datas = []
datas.append(list(arr1))
datas.append(list(arr2))
np.sum(datas)
Out[20]: 72

datas = []
datas.append(list(arr1.reshape(-1)))
datas.append(list(arr2.reshape(-1)))
np.sum(datas)
Out[25]: 72

datas = []
datas.extend(list(arr1.reshape(-1)))
datas.extend(list(arr2.reshape(-1)))
np.sum(datas)
Out[30]: 72

如 cmets 中所述,您需要验证 HDF5 文件的 data[key] 的 dtype。这是执行此操作的代码的修改版本。 (注意:我修改了读取数据集的调用;与data.get(key).value 相比,data[key][:] 是返回 NumPy 数组的更简单方法。)

datas = []
for filename in os.listdir("path/"):
    filename = "path/" + filename
    data = h5py.File(filename)
    print data[key].dtype
    arr = data[key][:]
    print arr.dtype, arr.shape, np.sum(arr)
    datas.append(list(arr.reshape(-1)))
    data.close()
print np.sum(datas)

注意:我使用的是 Python 3.8 和 NumPy 1.19.2,因此版本可能会有所不同。

【讨论】:

  • data[key].dtypearr.dtypefloat16np.sum(arr)np.sum(datas)inf
  • 您需要调查为什么np.sum(arr) 返回inf。这解释了错误,但与您最初的帖子不一致。你在里面说:“the first file np.sum is 51260.0. the second file np.sum is 51070.0”。您是如何获得这些值的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-15
  • 2020-08-30
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
相关资源
最近更新 更多