gpt4 book ai didi

python - 从数组中随机选择正负数据

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:18 25 4
gpt4 key购买 nike

我写了下面的函数:

def searchPosotive (X,y, num):
pos = sample(list(compress(X, y)), num)
return (pos)

此函数接受两个 numpy 矩阵,Xy。这两个数组是相关的,即。 X[i]y[i] 的标签。标签是 1 或 0。

此函数从 X 中随机选取 num 值,其等效 y 值等于 1,并返回一个 (num, n) 数组,其中n 是 X 中的列数。

我需要获取它包含的索引值列表。例如,如果 pos[a] == X[a],则 a 需要在该列表中。我怎样才能做到这一点?

当我寻找反例时,我也需要这样做。我目前使用的功能是:

def searchNegative (X,y, num):
mat=X[y==0]
rows = np.random.choice(len(mat), size=num,replace=False)
mat=mat[rows,:]
return (mat)

最佳答案

您想使用 np.where 获取正(或负)Y 的索引。然后,从索引中采样。这是一个正数函数,您可以修改它以让您选择正数或负数,或者为负数编写另一个函数:首先,假设:

>>> y
array([1, 0, 1, 1, 1, 0, 0, 1, 0, 1])
>>> X
array([[-25, 62, 94, 70, 96, 70, 38, -18, -57, 1],
[ 40, 86, -98, -48, 40, 29, 4, -83, 44, -12],
[ 57, 23, -96, 97, -24, -93, -33, -64, 61, 15],
[ 44, 29, 31, -38, 11, 85, 37, -96, -37, -70],
[-10, -37, -24, -66, 27, -44, -16, -50, 3, -91],
[-97, 81, 52, 41, 39, -14, 95, 76, 28, -32],
[-74, 49, -91, -65, -96, 86, -13, 43, 22, 80],
[ 5, 20, -77, 74, -89, 46, -90, 95, 30, 13],
[ 36, 6, 55, -74, -49, -66, 38, 37, -84, 28],
[-23, -28, -32, -30, -4, -52, -4, 99, -67, -98]])

所以...

>>> def sample_positive(X, y, num):
... pos_index = np.where(y == 1)[0]
... rows = np.random.choice(pos_index, size=num, replace=False)
... mat = X[rows,:]
... return (mat, rows)
...
>>> X_sample, idx = sample_positive(X, y, 2)
>>> X_sample
array([[-23, -28, -32, -30, -4, -52, -4, 99, -67, -98],
[-10, -37, -24, -66, 27, -44, -16, -50, 3, -91]])
>>> idx
array([9, 4])
>>> X
array([[-25, 62, 94, 70, 96, 70, 38, -18, -57, 1],
[ 40, 86, -98, -48, 40, 29, 4, -83, 44, -12],
[ 57, 23, -96, 97, -24, -93, -33, -64, 61, 15],
[ 44, 29, 31, -38, 11, 85, 37, -96, -37, -70],
[-10, -37, -24, -66, 27, -44, -16, -50, 3, -91],
[-97, 81, 52, 41, 39, -14, 95, 76, 28, -32],
[-74, 49, -91, -65, -96, 86, -13, 43, 22, 80],
[ 5, 20, -77, 74, -89, 46, -90, 95, 30, 13],
[ 36, 6, 55, -74, -49, -66, 38, 37, -84, 28],
[-23, -28, -32, -30, -4, -52, -4, 99, -67, -98]])
>>> y
array([1, 0, 1, 1, 1, 0, 0, 1, 0, 1])

关于python - 从数组中随机选择正负数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43461202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com