你想用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])
你可以用滿足約束的所有可能的索引創建另一個數組。然後,生成一個0到1之間的隨機數減去這個新數組的大小。從數組中刪除這個項目,並重復'num'次。 – kbunarjo
你能提供一些樣本數據嗎? –
你使用'itertools.compress'嗎?只需使用數組索引! –