创建大型 numpy 数组时出现内存错误

问题描述 投票:0回答:1

我的目标是绘制给定值和计数的直方图。

hist
仅接受数据数组作为输入。我尝试使用
np.repeat
重新创建数据,但这给出了
MemoryError: Unable to allocate 15.9 GiB for an array with shape (2138500000,) and data type float64

想知道是否有更聪明的方法来做到这一点。

import numpy as np 
import matplotlib.pyplot as plt 

values = [ 1, 2, 2.5, 4, 5, 5.75, 6.5]
counts = [10**8, 10**9, 1.5*10**7, 1.25*10**7, 10**6, 10**7,10**9]

data_recreated = np.repeat(values, counts)

f1, ax = plt.subplots(1,1)

ax.hist(data_recreated, bins=5)
python numpy matplotlib
1个回答
0
投票

正如我在评论中提到的,不确定在这里使用重复的理想用例是什么?您是否想说您想要表示一个数据集,其中: 值 1 出现 1 亿次 值 2 出现 10 亿次,依此类推?...

如果是这样,那么我们可以使用权重实现相同的统计可视化,而不是创建完整的数组。

import numpy as np
import matplotlib.pyplot as plt


values = [1, 2, 2.5, 4, 5, 5.75, 6.5]
counts = [10**8, 10**9, 1.5*10**7, 1.25*10**7, 10**6, 10**7, 10**9]


plt.figure(figsize=(10, 6))


plt.hist(values, bins=5, weights=counts, edgecolor='black')


plt.title('Histogram of Values')
plt.xlabel('Values')
plt.ylabel('Frequency')


plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))

# Add grid for better readability
plt.grid(True, alpha=0.3)


plt.show()

结果 enter image description here

验证

counts_hist, bin_edges, _ = plt.hist(values, bins=5, weights=counts)
print("\nBin edges:", bin_edges)
print("Counts in each bin:", counts_hist)

Bin edges: [1.  2.1 3.2 4.3 5.4 6.5]
Counts in each bin: [1.10e+09 1.50e+07 1.25e+07 1.00e+06 1.01e+09]

这是

1.10 billion
15 million
12.5 million
1 million
1.01 billion
© www.soinside.com 2019 - 2024. All rights reserved.