python - 如何为 numpy 数组中的每个类别随机选择 1 个样本(整数编码)

标签 python numpy

我使用整数编码来表示 numpy 数组中的类别。但是,我不知道如何为每个类别取 1 个随机样本并返回索引值。

例如,我有一个像这样的数组:

np.array([2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 1, 1, 1, 0, 1, 0, 0, 2, 2, 1])

我如何随机抽取 0、1 和 2 并返回每个样本的索引?

最佳答案

向量化一个用于整数标签的通用数量 -

# https://stackoverflow.com/a/51915131/ @Divakar
def random_num_per_grp(L):
    # For each element in L pick a random number within range specified by it
    r1 = np.random.rand(np.sum(L)) + np.repeat(np.arange(len(L)),L)
    offset = np.r_[0,np.cumsum(L[:-1])]
    return r1.argsort()[offset] - offset

# a is input array
sidx = a.argsort()
c = np.bincount(a)
out = sidx[random_num_per_grp(c) + np.r_[0,c[:-1].cumsum()]]

为了简化我们的案例,我们可以跳过 random_num_per_grp 最后一部分的偏移。因此,它会是 - return r1.argsort()[offset] 然后得到 out,它会是 - sidx[random_num_per_grp(c)].

对于负标签,简单地抵消最小值。

关于python - 如何为 numpy 数组中的每个类别随机选择 1 个样本(整数编码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57198687/

相关文章:

Python argpartsort 性能瓶颈

python - numpy.cov 实际上做了什么

python - 计算重复范围内出现的次数

python - 拆分为多个以逗号分隔的列值

python - "where()"在 SQLAlchemy 中如何工作

python - argparse 的 add_argument 如何在关键字参数之前采用可变长度参数?

python - 如何使用 Python 复制 xml 元素?

python - SCIPY Python 中的 RVS

python - 受其他数组限制的 Numpy 随机数组

python - 当函数应用于行时, Pandas 的 .groupby 函数出现奇怪的问题