原文鏈接:The 5 Sampling Algorithms every Data Scientist need to know
簡單隨機(jī)采樣
import pandas as pd
df = pd.DataFrame({'val': range(0, 9999)})
sample_df = df.sample(100)
print('df size: %d\nsample df size: %d' %(df.shape[0], sample_df.shape[0]))
df size: 9999
sample df size: 100
分層采樣
假設(shè)有1000名學(xué)生,其中300名是男生,700名是女生。如果從中抽取出100名,可以對1000名隨機(jī)采樣,也可以從男生中選30名,女生中選70名,這就是分層采樣。
import numpy as np
def stratified_sampling(data, column, sample_rate):
labels = np.unique(data[column])
print(labels)
sample_data = pd.DataFrame()
for label in labels:
data_with_label = data[data[column] == label]
sample_num = int(round(data_with_label.shape[0] * sample_rate))
sample_data_with_label = data_with_label.sample(sample_num)
sample_data = sample_data.append(sample_data_with_label)
return sample_data
gender = np.append(['male'] * 300, ['female'] * 700)
df = pd.DataFrame({'gender': gender, 'id': range(0, 1000)})
sample_df = stratified_sampling(df, 'gender', 0.1)
print('sample size: %d\nmale: %d\nfemale: %d' %(sample_df.shape[0]\
, sample_df[sample_df['gender'] == 'male'].shape[0]\
, sample_df[sample_df['gender'] == 'female'].shape[0]))
['female' 'male']
sample size: 100
male: 30
female: 70
水庫采樣
假設(shè)有一個(gè)未知長度的流數(shù)據(jù),只能遍歷一遍,如何從中等概率地選出n個(gè)元素
基本想法是維護(hù)一個(gè)n長的列表,在遍歷流數(shù)據(jù)的過程中,以一定的概率將流數(shù)據(jù)中當(dāng)前遍歷到的元素添加到列表中,或者替換列表中已有的元素。
那么,問題就是,這個(gè)“一定的概率”需要是多少,才能保證每個(gè)選中的元素都是等概率的。
我們把問題簡化一下,假設(shè)有一個(gè)長度為3的流數(shù)據(jù),我們從中選擇2個(gè),那么每個(gè)元素被選中的概率都是2/3。采用如下的步驟:
- 將第1個(gè)元素放入列表元素放入列表
- 將第2個(gè)元素放入列表元素放入列表
- 對第3個(gè)元素,有2/3的概率被放入列表,并隨機(jī)替換1或者2,有1/3的概率不被放進(jìn)列表
第3個(gè)元素替換1的概率是1/3,替換2的概率也是1/3,這樣,每個(gè)元素被選中的概率都是2/3。
import random
def generator(max):
number = 1
while number < max:
number += 1
yield number
# Create as stream generator
stream = generator(1000)
# Doing Reservoir Sampling from the stream
k=5
reservoir = []
for i, element in enumerate(stream):
if i+1<= k:
reservoir.append(element)
else:
probability = 1.0*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))] = element
print(reservoir)
[213, 563, 164, 752, 607]
降采樣和過采樣
在處理高度不平衡的數(shù)據(jù)集的時(shí)候,經(jīng)常會(huì)用戶重采樣方法,重采樣有降采樣和過采樣兩種。降采樣是從樣本多的類別中刪除樣本,過采樣是向樣本少的類別中添加樣本。

from sklearn.datasets import make_classification
# create a classifcation dataset
X, y = make_classification(
n_classes=2, class_sep=1.5, weights=[0.99, 0.01],
n_informative=3, n_redundant=1, flip_y=0,
n_features=20, n_clusters_per_class=1,
n_samples=1000, 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 undersample
undersampled_data = pd.concat([ X[X['target']==0].sample(num_1) , X[X['target']==1] ])
print(len(undersampled_data))
# random oversample
oversampled_data = pd.concat([ X[X['target']==0] , X[X['target']==1].sample(num_0, replace=True) ])
print(len(oversampled_data))
(990, 10)
20
1980
使用 imbalanced-learn 進(jìn)行降采樣和過采樣
imbalanced-learn(imblearn)是一個(gè)處理非平衡數(shù)據(jù)集的Python包。
a. 使用 Tomek Links 進(jìn)行降采樣
Tomek Links 是一組從屬于不同類別的相鄰樣本對。我們可以將這些相鄰的樣本對都刪除,來為分類器提供一個(gè)更清晰的分類邊界。

from imblearn.under_sampling import TomekLinks
tl = TomekLinks(return_indices=True, ratio='majority')
X_tl, y_tl, id_tl = tl.fit_sample(X, y)
b. 使用 SMOTE 進(jìn)行過采樣
SMOTE (Synthetic Minority Oversampling Technique) 對樣本少的類別合成樣本,這些合成的樣本位于已有樣本的臨近位置上。

from imblearn.over_sampling import SMOTE
smote = SMOTE(ratio='minority')
X_sm, y_sm = smote.fit_sample(X, y)
在 imblearn 包中還有其他的算法,比如:
- 降采樣:Cluster Centroids, NearMiss 等
- 過采樣:ADASYN, bSMOTE 等