機器學習中需要了解的 5 種采樣方法
點擊上方“小白學視覺”,選擇加"星標"或“置頂”
重磅干貨,第一時間送達
本文轉自 | 視覺算法
sample_df = df.sample(100)

我們可以選擇在整個人口中隨機抽取一個 60 大小的樣本,但在這些城鎮(zhèn)中,隨機樣本可能不太平衡,因此會產生偏差,導致估計誤差很大。
相反,如果我們選擇從 A、B 和 C 鎮(zhèn)分別抽取 10、20 和 30 個隨機樣本,那么我們可以在總樣本大小相同的情況下,產生較小的估計誤差。
使用 python 可以很容易地做到這一點:
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.25)
水塘采樣
假設您有一個項目流,它長度較大且未知以至于我們只能迭代一次。
創(chuàng)建一個算法,從這個流中隨機選擇一個項目,這樣每個項目都有相同的可能被選中。
import randomdef generator(max): number = 1 while number < max: number += 1 yield number# Create as stream generatorstream = generator(10000)# Doing Reservoir Sampling from the streamk=5reservoir = []for i, element in enumerate(stream): if i+1<= k: reservoir.append(element) else: probability = k/(i+1) if random.random() < probability: # Select item in stream and remove one of the k items already selected reservoir[random.choice(range(0,k))] = elementprint(reservoir)------------------------------------[1369, 4108, 9986, 828, 5589]
移除第一個項目的概率是項目 3 被選中的概率乘以項目 1 被隨機選為水塘中 2 個要素的替代候選的概率。這個概率是:
2/3*1/2 = 1/3
因此,選擇項目 1 的概率為:
1–1/3=2/3
from sklearn.datasets import make_classificationX, y = make_classification( n_classes=2, class_sep=1.5, weights=[0.9, 0.1], n_informative=3, n_redundant=1, flip_y=0, n_features=20, n_clusters_per_class=1, n_samples=100, random_state=10)X = pd.DataFrame(X)X[ target ] = y
num_0 = len(X[X[ target ]==0])num_1 = len(X[X[ target ]==1])print(num_0,num_1)# random undersampleundersampled_data = pd.concat([ X[X[ target ]==0].sample(num_1) , X[X[ target ]==1] ])print(len(undersampled_data))# random oversampleoversampled_data = pd.concat([ X[X[ target ]==0] , X[X[ target ]==1].sample(num_0, replace=True) ])print(len(oversampled_data))------------------------------------------------------------OUTPUT:90 1020180
在這個算法中,我們最終從 Tomek Links 中刪除了大多數(shù)元素,這為分類器提供了一個更好的決策邊界。
from imblearn.under_sampling import TomekLinks
tl = TomekLinks(return_indices=True, ratio= majority )X_tl, y_tl, id_tl = tl.fit_sample(X, y)
from imblearn.over_sampling import SMOTE
smote = SMOTE(ratio= minority )X_sm, y_sm = smote.fit_sample(X, y)
—完—
交流群
歡迎加入公眾號讀者群一起和同行交流,目前有SLAM、三維視覺、傳感器、自動駕駛、計算攝影、檢測、分割、識別、醫(yī)學影像、GAN、算法競賽等微信群(以后會逐漸細分),請掃描下面微信號加群,備注:”昵稱+學校/公司+研究方向“,例如:”張三 + 上海交大 + 視覺SLAM“。請按照格式備注,否則不予通過。添加成功后會根據(jù)研究方向邀請進入相關微信群。請勿在群內發(fā)送廣告,否則會請出群,謝謝理解~
評論
圖片
表情

