Pythonで始める競馬データ分析 - pandas基礎からXGBoostまで

🎯 はじめに

競馬データ分析は、機械学習の実践的な学習に最適な題材です。本記事では、Pythonのpandasライブラリを使った基本的なデータ処理から、 XGBoostを活用した高精度予想モデルの構築まで、実際のコード例とともに解説します。

この記事で学べること

  • pandasによる競馬データの前処理手法
  • 競馬特有の特徴量エンジニアリング
  • scikit-learnでの基本的な機械学習
  • XGBoostによる高精度モデル構築
  • モデル評価とパフォーマンス改善

📊 1. データ準備とpandas基礎

必要なライブラリのインストール

# 必要なライブラリをインストール
pip install pandas numpy scikit-learn xgboost matplotlib seaborn

基本的なデータ読み込み

import pandas as pd
import numpy as np
from datetime import datetime

# 競馬データの読み込み
race_data = pd.read_csv('race_results.csv')
horse_data = pd.read_csv('horse_info.csv')

# データの基本情報確認
print("レースデータ形状", race_data.shape)
print("馬データ形状", horse_data.shape)

データの前処理

# 欠損値の確認と処理
print("欠損値の数")
print(race_data.isnull().sum())

# 日付型への変換
race_data['race_date'] = pd.to_datetime(race_data['race_date'])

# 不要なデータの除去
race_data = race_data.dropna(subset=['horse_id', 'finish_position'])

🔧 2. 特徴量エンジニアリング

基本的な特徴量作成

def create_basic_features(df):
    # 馬齢グループ化
    df['age_group'] = pd.cut(df['horse_age'], bins=[0, 3, 5, 7, 20],
                            labels=['young', 'prime', 'mature', 'veteran'])

    # 斤量差
    df['weight_diff'] = df['jockey_weight'] - df['jockey_weight'].mean()

    # 馬体重変化
    df['weight_change'] = df.groupby('horse_id')['horse_weight'].diff()

    return df

race_data = create_basic_features(race_data)

過去成績特徴量

def create_performance_features(df):
    # ソート
    df = df.sort_values(['horse_id', 'race_date'])

    # 過去のレース成績
    df['past_3_avg_finish'] = df.groupby('horse_id')['finish_position'].rolling(3).mean().shift(1)
    df['past_5_avg_finish'] = df.groupby('horse_id')['finish_position'].rolling(5).mean().shift(1)

    # 勝率計算
    df['win_rate'] = df.groupby('horse_id').apply(
        lambda x: (x['finish_position'] == 1).rolling(5).mean().shift(1)
    ).reset_index(level=0, drop=True)

    return df

race_data = create_performance_features(race_data)

🚀 3. XGBoostによる高精度モデル

XGBoostモデルの構築

import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 目的変数の作成(1着なら1、それ以外は0)
race_data['target'] = (race_data['finish_position'] == 1).astype(int)

# 特徴量選択
feature_columns = [
    'horse_age', 'jockey_weight', 'horse_weight', 'odds',
    'weight_diff', 'weight_change', 'past_3_avg_finish',
    'past_5_avg_finish', 'win_rate'
]

# 欠損値処理
data_clean = race_data[feature_columns + ['target']].dropna()
X = data_clean[feature_columns]
y = data_clean['target']

# 訓練・テストデータ分割
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=42, stratify=y
)

# XGBoostモデルの訓練
xgb_model = xgb.XGBClassifier(
    objective='binary_logistic',
    max_depth=6,
    learning_rate=0.1,
    n_estimators=100,
    random_state=42
)

xgb_model.fit(X_train, y_train)

# 予測と評価
y_pred = xgb_model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)

print("XGBoost精度", accuracy)

🎯 まとめ

本記事では、Pythonとpandasを使った競馬データ分析の基礎から、XGBoostによる高精度予想モデルの構築まで解説しました。 特に重要なのは以下のポイントです:

重要なポイント

  • データ品質: 前処理と特徴量エンジニアリングがモデル性能に最も影響
  • 過去成績特徴量: 馬の過去パフォーマンスが最も重要な特徴量
  • モデル選択: XGBoostは競馬データに特に有効
  • 評価指標: 単純な精度だけでなく、AUCや確率較正も重要

さらに高度な手法(深層学習、アンサンブル学習、時系列分析など)に挑戦することで、 より精度の高い予想モデルを構築できます。