注意
转到末尾 以下载完整的示例代码。
管道嵌入采样器的使用#
一个关于 :class:~imblearn.pipeline.Pipeline` 对象的示例(或
make_pipeline
辅助函数)与
转换器和重采样器一起工作的示例。
# Authors: Christos Aridas
# Guillaume Lemaitre <g.lemaitre58@gmail.com>
# License: MIT
print(__doc__)
首先,我们创建一个不平衡的数据集并将其分成两个集合。
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_classes=2,
class_sep=1.25,
weights=[0.3, 0.7],
n_informative=3,
n_redundant=1,
flip_y=0,
n_features=5,
n_clusters_per_class=1,
n_samples=5000,
random_state=10,
)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)
现在,我们将创建我们稍后希望组合的每个单独步骤
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import EditedNearestNeighbours
pca = PCA(n_components=2)
enn = EditedNearestNeighbours()
smote = SMOTE(random_state=0)
knn = KNeighborsClassifier(n_neighbors=1)
现在,我们终于可以创建一个管道来指定在将数据提供给最终分类器之前,不同的转换器和采样器应按什么顺序执行。
from imblearn.pipeline import make_pipeline
model = make_pipeline(pca, enn, smote, knn)
我们现在可以将创建的管道用作普通分类器,其中在调用fit
时会进行重采样,而在调用decision_function
、predict_proba
或predict
时则禁用重采样。
precision recall f1-score support
0 0.99 0.99 0.99 375
1 1.00 1.00 1.00 875
accuracy 0.99 1250
macro avg 0.99 0.99 0.99 1250
weighted avg 0.99 0.99 0.99 1250
脚本的总运行时间: (0 分钟 1.485 秒)
预计内存使用量: 199 MB