XGBoost, gradient boosting framework'ün optimize edilmiş ve scalable implementasyonudur. Kaggle yarışmalarında ve endüstride en popüler algoritmalardan biridir.
import xgboost as xgb
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import accuracy_score, classification_report
import pandas as pd
X = df.drop('target', axis=1)
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
xgb_model = xgb.XGBClassifier(
random_state=42,
eval_metric='logloss'
)
xgb_model.fit(X_train, y_train)
y_pred = xgb_model.predict(X_test)
print(f"Basic XGBoost Accuracy: {accuracy_score(y_test, y_pred):.4f}")
param_grid = {
'n_estimators': [100, 200, 300],
'max_depth': [3, 4, 5, 6],
'learning_rate': [0.01, 0.1, 0.2],
'subsample': [0.8, 0.9, 1.0],
'colsample_bytree': [0.8, 0.9, 1.0]
}
grid_search = GridSearchCV(
estimator=xgb.XGBClassifier(random_state=42, eval_metric='logloss'),
param_grid={
'n_estimators': [100, 200],
'max_depth': [3, 4],
'learning_rate': [0.1, 0.2]
},
scoring='accuracy',
cv=3,
n_jobs=-1
)
grid_search.fit(X_train, y_train)
print(f"En iyi parametreler: {grid_search.best_params_}")
print(f"En iyi CV score: {grid_search.best_score_:.4f}")
best_xgb = grid_search.best_estimator_
y_pred_best = best_xgb.predict(X_test)
final_accuracy = accuracy_score(y_test, y_pred_best)
print(f"Final XGBoost Accuracy: {final_accuracy:.4f}")
print("\nClassification Report:")
print(classification_report(y_test, y_pred_best))
feature_importance = best_xgb.feature_importances_
feature_names = X.columns
importance_df = pd.DataFrame({
'feature': feature_names,
'importance': feature_importance
}).sort_values('importance', ascending=False)
print("\nTop 10 Features:")
print(importance_df.head(10))
xgb_early = xgb.XGBClassifier(
random_state=42,
eval_metric='logloss',
early_stopping_rounds=10
)
X_train_split, X_val, y_train_split, y_val = train_test_split(
X_train, y_train, test_size=0.2, random_state=42
)
xgb_early.fit(
X_train_split, y_train_split,
eval_set=[(X_val, y_val)],
verbose=False
)
Gradient Boosting: Sequential learning from mistakes
Regularization: L1/L2 penalty terms
Parallel Processing: Multi-threaded tree construction
Missing Values: Automatic handling
Feature Importance: Built-in feature selection
XGBoost Hyperparameters:
- n_estimators: Boosting rounds sayısı
- max_depth: Tree derinliği (overfitting kontrol)
- learning_rate: Shrinkage parameter (0.01-0.3)
- subsample: Row sampling ratio
- colsample_bytree: Feature sampling ratio
- reg_alpha/reg_lambda: L1/L2 regularization