XGBoosting Home | About | Contact | Examples

XGBoost for the Iris Dataset

The Iris dataset is a classic and widely used dataset for classification tasks.

It consists of 150 samples, with 4 features (sepal length, sepal width, petal length, petal width) and 3 classes (setosa, versicolor, virginica).

In this example, we’ll load the Iris dataset from scikit-learn, perform hyperparameter tuning using GridSearchCV with common XGBoost parameters, save the best model, load it, and use it to make predictions.

from sklearn.datasets import load_iris
from sklearn.model_selection import GridSearchCV, train_test_split
from xgboost import XGBClassifier
import numpy as np

# Load the Iris dataset
iris = load_iris()
X, y = iris.data, iris.target

# Print key information about the dataset
print(f"Dataset shape: {X.shape}")
print(f"Features: {iris.feature_names}")
print(f"Classes: {iris.target_names}")

# Split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Define parameter grid
param_grid = {
    'max_depth': [3, 4, 5],
    'learning_rate': [0.1, 0.01, 0.05],
    'n_estimators': [50, 100, 200],
    'subsample': [0.8, 1.0],
    'colsample_bytree': [0.8, 1.0]
}

# Create XGBClassifier
model = XGBClassifier(objective='multi:softmax', num_class=3, random_state=42, n_jobs=1)

# Perform grid search
grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=3, n_jobs=-1)
grid_search.fit(X_train, y_train)

# Print best score and parameters
print(f"Best score: {grid_search.best_score_:.3f}")
print(f"Best parameters: {grid_search.best_params_}")

# Access best model
best_model = grid_search.best_estimator_

# Save best model
best_model.save_model('best_model_iris.ubj')

# Load saved model
loaded_model = XGBClassifier()
loaded_model.load_model('best_model_iris.ubj')

# Use loaded model for predictions
predictions = loaded_model.predict(X_test)

# Print accuracy score
accuracy = loaded_model.score(X_test, y_test)
print(f"Accuracy: {accuracy:.3f}")

Running the example, you will see results like the following:

Dataset shape: (150, 4)
Features: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
Classes: ['setosa' 'versicolor' 'virginica']
Best score: 0.958
Best parameters: {'colsample_bytree': 1.0, 'learning_rate': 0.01, 'max_depth': 3, 'n_estimators': 50, 'subsample': 0.8}
Accuracy: 1.000

In this example, we first load the Iris dataset using load_iris() from scikit-learn. We print some key information about the dataset, such as its shape, feature names, and class names.

Next, we split the data into train and test sets using train_test_split(). We define a parameter grid with common XGBoost hyperparameters, including max_depth, learning_rate, n_estimators, subsample, and colsample_bytree.

We create an instance of XGBClassifier and perform a grid search using GridSearchCV with 3-fold cross-validation. After fitting the grid search object, we print the best score and corresponding best parameters.

We access the best model using best_estimator_ and save it to a file named ‘best_model_iris.ubj’ using the save_model() method. To demonstrate loading the saved model, we create a new XGBClassifier instance and load the saved model using load_model().

Finally, we use the loaded model to make predictions on the test set and print the accuracy score.

By following this approach, you can easily perform hyperparameter tuning on the Iris dataset using XGBoost, save the best model, and use it for making predictions.



See Also