收藏 | 機器學習中需要了解的 5 種采樣方法
點擊上方“小白學視覺”,選擇加"星標"或“置頂”
重磅干貨,第一時間送達
sample_df = df.sample(100)?
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 = 1while number < max:number += 1yield 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 selectedreservoir[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 ] = ynum_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 中刪除了大多數元素,這為分類器提供了一個更好的決策邊界。

from imblearn.under_sampling import TomekLinkstl = TomekLinks(return_indices=True, ratio= majority )X_tl, y_tl, id_tl = tl.fit_sample(X, y)

from imblearn.over_sampling import SMOTEsmote = SMOTE(ratio= minority )X_sm, y_sm = smote.fit_sample(X, y)
?
下載1:OpenCV-Contrib擴展模塊中文版教程 在「小白學視覺」公眾號后臺回復:擴展模塊中文教程,即可下載全網第一份OpenCV擴展模塊教程中文版,涵蓋擴展模塊安裝、SFM算法、立體視覺、目標跟蹤、生物視覺、超分辨率處理等二十多章內容。 下載2:Python視覺實戰(zhàn)項目52講 在「小白學視覺」公眾號后臺回復:Python視覺實戰(zhàn)項目,即可下載包括圖像分割、口罩檢測、車道線檢測、車輛計數、添加眼線、車牌識別、字符識別、情緒檢測、文本內容提取、面部識別等31個視覺實戰(zhàn)項目,助力快速學校計算機視覺。 下載3:OpenCV實戰(zhàn)項目20講 在「小白學視覺」公眾號后臺回復:OpenCV實戰(zhàn)項目20講,即可下載含有20個基于OpenCV實現20個實戰(zhàn)項目,實現OpenCV學習進階。 交流群
歡迎加入公眾號讀者群一起和同行交流,目前有SLAM、三維視覺、傳感器、自動駕駛、計算攝影、檢測、分割、識別、醫(yī)學影像、GAN、算法競賽等微信群(以后會逐漸細分),請掃描下面微信號加群,備注:”昵稱+學校/公司+研究方向“,例如:”張三?+?上海交大?+?視覺SLAM“。請按照格式備注,否則不予通過。添加成功后會根據研究方向邀請進入相關微信群。請勿在群內發(fā)送廣告,否則會請出群,謝謝理解~
評論
圖片
表情
