xgboost预测鸢尾花数据集
时间: 2023-09-04 18:08:21 浏览: 29
首先,我们需要导入必要的库并加载鸢尾花数据集:
```python
import xgboost as xgb
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
接下来,我们需要将数据转换为`DMatrix`格式,这是XGBoost能够接受的格式:
```python
# 将数据转换为 DMatrix 格式
dtrain = xgb.DMatrix(X_train, label=y_train)
dtest = xgb.DMatrix(X_test, label=y_test)
```
然后,我们可以定义一个参数字典,并训练我们的模型:
```python
# 定义参数字典
params = {
'max_depth': 3, # 树的最大深度
'eta': 0.1, # 学习率
'objective': 'multi:softmax',# 多分类问题
'num_class': 3 # 类别数
}
# 训练模型
num_rounds = 50
model = xgb.train(params, dtrain, num_rounds)
```
最后,我们可以使用训练好的模型进行预测并计算准确率:
```python
# 预测测试集
preds = model.predict(dtest)
# 计算准确率
accuracy = sum(preds == y_test) / len(y_test)
print('准确率:{:.2f}%'.format(accuracy * 100))
```
完整的代码如下:
```python
import xgboost as xgb
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 将数据转换为 DMatrix 格式
dtrain = xgb.DMatrix(X_train, label=y_train)
dtest = xgb.DMatrix(X_test, label=y_test)
# 定义参数字典
params = {
'max_depth': 3, # 树的最大深度
'eta': 0.1, # 学习率
'objective': 'multi:softmax',# 多分类问题
'num_class': 3 # 类别数
}
# 训练模型
num_rounds = 50
model = xgb.train(params, dtrain, num_rounds)
# 预测测试集
preds = model.predict(dtest)
# 计算准确率
accuracy = sum(preds == y_test) / len(y_test)
print('准确率:{:.2f}%'.format(accuracy * 100))
```
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![csv](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)