[英]Stratified Sampling in Python without scikit-learn
我有一個向量,其中包含樣本 1 的 10 個值和樣本 2 的 25 個值。
Fact = np.array((2,2,2,2,1,2,1,1,2,2,2,1,2,2,2,1,2,2,2,1,2,2,1,1,2,1,2,2,2,2,2,2,1,2,2))
我想創建一個分層輸出向量,其中:
樣本 1 分為 80%:8 個 1 值和 20%:2 個 0 值。
樣本 2 分為 80%:20 個 1 值和 20%:5 個 0 值。
預期的輸出將是:
Output = np.array((0,1,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,0,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1))
我怎樣才能自動化呢? 我不能使用 scikit-learn 的采樣功能,因為它不是用於機器學習體驗。
這是獲得所需結果的一種方法,增加了輸出的可重復性。 我們從輸入( fact
)數組中為兩組中的每一個繪制隨機索引值,無需替換。 然后,我們創建一個新的輸出數組,我們在與繪制的索引值對應的位置分配1
並在其他任何位置分配0
。
import numpy as np
from numpy.random import RandomState
rng = RandomState(123)
fact = np.array(
(2,2,2,2,1,2,1,1,2,2,2,1,2,2,2,1,2,2,2,1,2,2,1,1,2,1,2,2,2,2,2,2,1,2,2),
dtype='int8'
)
idx_arr = np.hstack(
(
rng.choice(np.argwhere(fact == 1).flatten(), 8, replace=False),
rng.choice(np.argwhere(fact == 2).flatten(), 20, replace=False),
)
)
out = np.zeros_like(fact, dtype='int8')
np.put(out, idx_arr, 1)
print(out)
# [0 0 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 0 1 1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.