在保留分布的同时对 numpy 数组进行下采样

Downsample numpy array while preserving distribution

我正在尝试编写一个函数,该函数可以对具有浮点数的 numpy.ndarray 进行随机采样,同时保留数组中数字的分布。我现在有这个功能:

import random
from collections import Counter

def sample(A, N):
    population = np.zeros(sum(A))
    counter = 0
    for i, x in enumerate(A):
            for j in range(x):
                    population[counter] = i
                    counter += 1

    sampling = population[np.random.choice(0, len(population), N)]
    return np.histogram(sampling, bins = np.arange(len(A)+1))[0]

所以我希望该函数像这样工作(不包括此示例的分配会计):

a = np.array([1.94, 5.68, 2.77, 7.39, 2.51])
new_a = sample(a,3)

new_a
array([1.94, 2.77, 7.39])

但是,当我将函数应用于这样的数组时,我得到:

TypeError                                 Traceback (most recent call last)
<ipython-input-74-07e3aa976da4> in <module>
----> 1 sample(a, 3)

<ipython-input-63-2d69398e2a22> in sample(A, N)
      3 
      4 def sample(A, N):
----> 5     population = np.zeros(sum(A))
      6     counter = 0
      7     for i, x in enumerate(A):

TypeError: 'numpy.float64' object cannot be interpreted as an integer

任何有关修改或创建适用于此的函数的帮助都将不胜感激!

In [67]: a = np.array([1.94, 5.68, 2.77, 7.39, 2.51])                                                  
In [68]: np.zeros(sum(a))                                                                              
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-68-263779bc977b> in <module>
----> 1 np.zeros(sum(a))

TypeError: 'numpy.float64' object cannot be interpreted as an integer

对形状求和不会产生此错误:

In [69]: np.zeros(sum(a.shape))                                                                        
Out[69]: array([0., 0., 0., 0., 0.])

但是你不需要使用 sum:

In [70]: a.shape                                                                                       
Out[70]: (5,)
In [71]: np.zeros(a.shape)                                                                             
Out[71]: array([0., 0., 0., 0., 0.])

事实上,如果 a 是二维的,并且您想要一个具有相同项目数的一维数组,您需要形状的乘积,而不是总和。

但是你想要 return 一个与 A 大小完全相同的数组吗?我以为你是想缩小尺寸。