Kmeans Smote过采样Python代码
时间: 2023-07-10 19:31:47 浏览: 169
下面是使用K-means SMOTE算法进行过采样的Python示例代码:
```python
from imblearn.over_sampling import KMeansSMOTE
from sklearn.datasets import make_classification
# 创建不平衡数据集
X, y = make_classification(n_classes=2, class_sep=2, weights=[0.1, 0.9], n_informative=3, n_redundant=1, flip_y=0, n_features=20, n_clusters_per_class=1, n_samples=1000, random_state=10)
# 使用K-means SMOTE算法进行过采样
kmeans_smote = KMeansSMOTE(k_neighbors=5, random_state=10)
X_resampled, y_resampled = kmeans_smote.fit_resample(X, y)
print("原始数据集中各类别样本数量:", {i: len(y[y==i]) for i in set(y)})
print("过采样后数据集中各类别样本数量:", {i: len(y_resampled[y_resampled==i]) for i in set(y_resampled)})
```
上述代码中,我们使用`make_classification`函数创建了一个不平衡的二分类数据集,其中正样本比例为90%,负样本比例为10%。然后我们使用`KMeansSMOTE`算法进行过采样,其中`k_neighbors`表示在SMOTE算法中选取的k个近邻样本的数量。最后,我们输出了过采样前后各个类别样本的数量。