train and test xgboost in python

Here's an example of how to train and test an XGBoost model in Python:

main.py
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer

# Load the breast cancer dataset
data = load_breast_cancer()
X, y = data.data, data.target

# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Create an XGBoost model
model = xgb.XGBClassifier()

# Train the model on the training set
model.fit(X_train, y_train)

# Test the model on the testing set
y_pred = model.predict(X_test)

# Evaluate the model's accuracy
accuracy = sum(y_test == y_pred) / len(y_test)
print("Accuracy:", accuracy)
656 chars
24 lines

In this example, we load the breast cancer dataset from scikit-learn, split it into training and testing sets using train_test_split, create an XGBoost model using xgb.XGBClassifier, train the model on the training set using model.fit, test the model on the testing set using model.predict, and evaluate the accuracy of the model using the percentage of correct predictions.

gistlibby LogSnag