1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

XGBoostを使用したPython機械学習チュートリアル(データ可視化付き)

Last updated at Posted at 2024-08-17

第1章: XGBoostの概要

XGBoostは高性能な勾配ブースティングライブラリです。決定木アルゴリズムを使用し、高速で正確な予測モデルを構築できます。

import xgboost as xgb
print(xgb.__version__)

第2章: データの準備

必要なライブラリをインポートし、データを読み込みます。

import pandas as pd
from sklearn.model_selection import train_test_split

data = pd.read_csv('data.csv')
X = data.drop('target', axis=1)
y = data['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

第3章: XGBoostモデルの作成

XGBoostモデルを初期化し、パラメータを設定します。

model = xgb.XGBClassifier(
    max_depth=3,
    learning_rate=0.1,
    n_estimators=100,
    objective='binary:logistic'
)

第4章: モデルの学習

作成したモデルをトレーニングデータで学習させます。

model.fit(X_train, y_train)

第5章: 予測と評価

学習したモデルを使用して予測を行い、精度を評価します。

from sklearn.metrics import accuracy_score

y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f'精度: {accuracy:.2f}')

第6章: 特徴量の重要度の可視化

XGBoostモデルの特徴量の重要度を可視化します[3]。

import matplotlib.pyplot as plt

xgb.plot_importance(model)
plt.show()

第7章: 決定木の可視化

XGBoostモデルの個々の決定木を可視化します[5]。

xgb.plot_tree(model, num_trees=0)
plt.show()

第8章: 学習曲線の可視化

モデルの学習過程を可視化します。

results = model.evals_result()
epochs = len(results['validation_0']['error'])
x_axis = range(0, epochs)

fig, ax = plt.subplots()
ax.plot(x_axis, results['validation_0']['error'], label='Train')
ax.plot(x_axis, results['validation_1']['error'], label='Test')
ax.legend()
plt.ylabel('Error')
plt.title('XGBoost Error')
plt.show()

第9章: クロスバリデーション

モデルの汎化性能を評価するためにクロスバリデーションを実行します[4]。

from sklearn.model_selection import cross_val_score

cv_scores = cross_val_score(model, X, y, cv=5)
print(f'クロスバリデーションスコア: {cv_scores.mean():.2f} (+/- {cv_scores.std() * 2:.2f})')

第10章: ハイパーパラメータチューニング

グリッドサーチを使用してハイパーパラメータを最適化します。

from sklearn.model_selection import GridSearchCV

param_grid = {
    'max_depth': [3, 4, 5],
    'learning_rate': [0.1, 0.01, 0.001],
    'n_estimators': [100, 200, 300]
}
grid_search = GridSearchCV(model, param_grid, cv=5)
grid_search.fit(X, y)
print(f'最適パラメータ: {grid_search.best_params_}')

第11章: 予測結果の可視化

予測結果を散布図で可視化します。

plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred, cmap='viridis')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('XGBoost Predictions')
plt.colorbar(label='Predicted Class')
plt.show()

第12章: モデルの保存と読み込み

学習したモデルを保存し、後で読み込むことができます。

model.save_model('xgboost_model.json')
loaded_model = xgb.XGBClassifier()
loaded_model.load_model('xgboost_model.json')

このチュートリアルでは、XGBoostの基本的な使用方法と、データ可視化ライブラリを活用した結果の表示方法を紹介しました。各章で実践的なコード例を提供し、モデルの学習から評価、可視化まで一連のプロセスを解説しました。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?