Wine数据集实现adaboost算法的python代码
时间: 2024-05-14 22:18:41 浏览: 147
Adaboost算法介绍及应用.docx
以下是使用Wine数据集实现adaboost算法的Python代码。首先我们需要导入所需的库和数据集:
```python
import numpy as np
from sklearn.ensemble import AdaBoostClassifier
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
wine = load_wine()
X = wine.data
y = wine.target
```
接下来,我们将数据集分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
然后,我们可以使用`AdaBoostClassifier`类来创建adaboost分类器:
```python
ada = AdaBoostClassifier(n_estimators=50, learning_rate=1)
```
在这里,我们选择了50个基本分类器,并将学习率设置为1。现在,我们可以使用训练数据来训练adaboost分类器:
```python
ada.fit(X_train, y_train)
```
最后,我们可以使用测试数据来评估adaboost分类器的性能:
```python
y_pred = ada.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
完整的代码如下:
```python
import numpy as np
from sklearn.ensemble import AdaBoostClassifier
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
wine = load_wine()
X = wine.data
y = wine.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
ada = AdaBoostClassifier(n_estimators=50, learning_rate=1)
ada.fit(X_train, y_train)
y_pred = ada.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
阅读全文