[英]RuntimeWarning: overflow encountered in reduce, np.sum result is inf
我有兩個 hdf5 文件,第一個文件數據形狀為(1, 10240)
,np.sum 值為 51260.0。 第二個文件數據形狀也是(1, 10240)
,np.sum 值為 51070.0。 但是當我讀取兩個文件和 append 到一個列表時, 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.sum
是inf
?
您的代碼沒有明顯的問題。 您可以使用這個簡單的示例進行驗證。 您使用.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
如評論中所述,您需要驗證 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,因此可能會因版本而有所不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.