python中导入数据后用easyensamble和bagging预测数据
时间: 2023-05-30 09:03:46 浏览: 125
以下是使用EasyEnsemble和Bagging进行数据预测的示例代码:
使用EasyEnsemble:
```python
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.ensemble import BaggingClassifier
from imblearn.ensemble import EasyEnsembleClassifier
# 生成数据集
X, y = make_classification(n_samples=1000, n_classes=2, weights=[0.1, 0.9], random_state=42)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 使用EasyEnsemble对训练集进行重采样
ee = EasyEnsembleClassifier(random_state=42)
X_resampled, y_resampled = ee.fit_resample(X_train, y_train)
# 使用Bagging对每个子集训练一个分类器
bagging = BaggingClassifier(random_state=42)
bagging.fit(X_resampled, y_resampled)
# 预测测试集并计算准确率
y_pred = bagging.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy: {:.2f}%".format(accuracy * 100))
```
使用Bagging:
```python
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.ensemble import BaggingClassifier
# 生成数据集
X, y = make_classification(n_samples=1000, n_classes=2, weights=[0.1, 0.9], random_state=42)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 使用Bagging对训练集进行重采样
bagging = BaggingClassifier(random_state=42)
bagging.fit(X_train, y_train)
# 预测测试集并计算准确率
y_pred = bagging.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy: {:.2f}%".format(accuracy * 100))
```
阅读全文