AdaBoost算法代码(鸢尾花分类)
时间: 2023-07-05 13:12:02 浏览: 140
好的,以下是基于Python的AdaBoost算法代码:
首先,我们需要导入必要的库和数据集:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.model_selection import train_test_split
iris = load_iris()
X = iris.data[:, :2]
y = iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
接下来,我们定义一个AdaBoost分类器并训练它:
```python
# 定义一个单层决策树作为基分类器
clf = DecisionTreeClassifier(max_depth=1)
# 定义AdaBoost分类器
ada_clf = AdaBoostClassifier(
base_estimator=clf,
n_estimators=200, # 基分类器的数量
learning_rate=0.5 # 学习率
)
# 训练AdaBoost分类器
ada_clf.fit(X_train, y_train)
```
最后,我们可以在测试集上进行预测并计算分类器的准确率:
```python
# 在测试集上进行预测
y_pred = ada_clf.predict(X_test)
# 计算分类器的准确率
accuracy = np.mean(y_pred == y_test)
print("Accuracy: {:.2f}%".format(accuracy * 100))
```
完整代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.model_selection import train_test_split
iris = load_iris()
X = iris.data[:, :2]
y = iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 定义一个单层决策树作为基分类器
clf = DecisionTreeClassifier(max_depth=1)
# 定义AdaBoost分类器
ada_clf = AdaBoostClassifier(
base_estimator=clf,
n_estimators=200, # 基分类器的数量
learning_rate=0.5 # 学习率
)
# 训练AdaBoost分类器
ada_clf.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = ada_clf.predict(X_test)
# 计算分类器的准确率
accuracy = np.mean(y_pred == y_test)
print("Accuracy: {:.2f}%".format(accuracy * 100))
```
希望对你有所帮助!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)