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

2024-04-27 04:00:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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并返回每个样本的索引?你知道吗


Tags: numpy编码np整数数组类别array样本
3条回答

整数标签的通用数的矢量化-

# 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)]。你知道吗

对于负片标签,只需按最小值偏移即可。你知道吗

您可以使用np.wherenp.random.choice()

x = np.array([2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 1, 1, 1, 0, 1, 0, 0, 2, 2, 1])
ind0 = np.random.choice(np.where(x==0)[0])
ind1 = np.random.choice(np.where(x==1)[0])
ind2 = np.random.choice(np.where(x==2)[0])

由于np.where返回一个元组,其中包含一个数组,因此要访问数组,需要访问元组的0索引。你知道吗

import numpy as np

array = np.array([2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 1, 1, 1, 0, 1, 0, 0, 2, 2, 1])
categories = [0,1,2]
for category in categories:
    indices = np.where(array  == category)[0]
    random_choice = array[np.random.choice(indices)]

1)在条件为真的情况下获取数字的索引(类别) 2) 从这些指数中随机选择

相关问题 更多 >