Skip to content
トピック
Python
Sklearn Train Test Split: Pythonでデータを分割する完全ガイド

Sklearn Train Test Split: Pythonでデータを分割する完全ガイド

Updated on

データセット全体で機械学習モデルをトレーニングし、同じデータで評価すると、重大な問題が発生します。モデルは良好に機能しているように見えますが、パターンを学習するのではなく、単にデータを記憶しているだけです。この過学習は、モデルが新しい未知のデータに遭遇したときに悲惨な失敗を意味します。データサイエンティストは、トレーニング中にモデルが一度も見たことのないデータでモデルのパフォーマンスを評価する信頼できる方法が必要です。

解決策は訓練テスト分割です。評価用にデータの一部を確保することで、実世界でモデルがどのように機能するかの正直な評価を得ることができます。sklearnのtrain_test_split関数はこのプロセスを簡単にしますが、誤って使用すると、データリーク、汎化性能の低下、誤解を招くパフォーマンス指標につながる可能性があります。

このガイドでは、基本的な使用法から時系列データ、不均衡クラス、マルチアウトプット問題の高度なテクニックまで、sklearnのtrain_test_splitについて知っておくべきすべてを説明します。

📚

Train Test Splitとは?

Train test splitは、機械学習モデルを評価するための基本的な技術です。データセットを2つの部分に分割します。モデルを適合させるために使用される訓練セットと、未知のデータでモデルのパフォーマンスを評価するために使用されるテストセットです。

scikit-learn(sklearn)のtrain_test_split関数は、このプロセスを自動化し、1行のコードでランダムなシャッフルと分割を処理します。

from sklearn.model_selection import train_test_split
 
# 基本的な使用法
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

この例では、Xには特徴量(入力変数)が含まれ、yには目的変数(予測したいもの)が含まれています。この関数は4つの配列を返します:訓練特徴量、テスト特徴量、訓練ラベル、テストラベルです。

基本的なtrain_test_split構文

train_test_splitの最も簡単な使用法は、2つの引数のみを必要とします:特徴量と目的変数です。

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
 
# サンプルデータをロード
iris = load_iris()
X = iris.data
y = iris.target
 
# データを分割(80%訓練、20%テスト)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
 
print(f"Training samples: {len(X_train)}")
print(f"Test samples: {len(X_test)}")

これはデータをランダムに分割し、80%が訓練に、20%がテストに使用されます。しかし、この基本的な使用法には重大な欠陥があります。コードを実行するたびに分割が異なるため、結果が再現できません。

必須パラメータ

test_sizeとtrain_size

test_sizeパラメータは、テストセットに使用されるデータの量を制御します。次のように指定できます:

  • 0.0と1.0の間のfloat(データセットの割合)
  • 整数(テストサンプルの絶対数)
# 30%テストセット
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
 
# テストセットに50サンプル
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=50)
 
# または、train_sizeを指定
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8)

test_sizetrain_sizeの両方を指定する場合、それらは1.0(または整数を使用する場合はデータセットの総サイズ)になる必要があります。ほとんどの場合、test_sizeのみを指定すれば十分です。

再現性のためのrandom_state

random_stateパラメータは再現可能な結果にとって重要です。これがないと、コードを実行するたびに異なる分割が得られ、デバッグや実験の比較が不可能になります。

# random_stateなし - 毎回異なる分割
X_train1, X_test1, y_train1, y_test1 = train_test_split(X, y, test_size=0.2)
X_train2, X_test2, y_train2, y_test2 = train_test_split(X, y, test_size=0.2)
 
print(f"Same split? {(X_train1 == X_train2).all()}")  # False
 
# random_stateあり - 毎回同じ分割
X_train1, X_test1, y_train1, y_test1 = train_test_split(X, y, test_size=0.2, random_state=42)
X_train2, X_test2, y_train2, y_test2 = train_test_split(X, y, test_size=0.2, random_state=42)
 
print(f"Same split? {(X_train1 == X_train2).all()}")  # True

random_stateには任意の整数を使用してください。特定の数字は重要ではありません。重要なのは、プロジェクト全体で同じ数字を一貫して使用することです。

shuffleパラメータ

デフォルトでは、train_test_splitは分割前にデータをシャッフルします。ほとんどの機械学習タスクでは、これはまさに必要なものです。ただし、時系列データや順序が重要な場合は、シャッフルを無効にする必要があります。

# シャッフル有効(デフォルト)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=True)
 
# シャッフル無効(時系列用)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)

shuffle=Falseの場合、関数は単に最初の部分を訓練用に、最後の部分をテスト用に取り、元の順序を維持します。

パラメータ参照表

パラメータデフォルト説明
test_sizefloatまたはintNoneテストセットの割合(0.0-1.0)またはサンプル数
train_sizefloatまたはintNone訓練セットの割合(0.0-1.0)またはサンプル数
random_stateintNone再現性のための乱数シード
shuffleboolTrue分割前にデータをシャッフルするかどうか
stratifyarray-likeNone層化分割に使用するデータ

不均衡データの層化分割

データセットに不均衡なクラスがある場合(一部のクラスが他のクラスよりもはるかに少ないサンプルを持っている)、ランダムな分割は全体の分布を適切に表さない訓練セットやテストセットを作成する可能性があります。これは分類タスクで特に問題になります。

stratifyパラメータは、訓練セットとテストセットのクラス分布が元のデータセットと一致することを保証します。

import numpy as np
from sklearn.model_selection import train_test_split
 
# 不均衡なデータセットを作成(90%クラス0、10%クラス1)
X = np.random.randn(1000, 5)
y = np.array([0] * 900 + [1] * 100)
 
# 層化なし
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(f"Train distribution: Class 0: {sum(y_train == 0)}, Class 1: {sum(y_train == 1)}")
print(f"Test distribution: Class 0: {sum(y_test == 0)}, Class 1: {sum(y_test == 1)}")
 
# 層化あり
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)
print(f"\nStratified train distribution: Class 0: {sum(y_train == 0)}, Class 1: {sum(y_train == 1)}")
print(f"Stratified test distribution: Class 0: {sum(y_test == 0)}, Class 1: {sum(y_test == 1)}")

層化を使用すると、訓練セットとテストセットの両方が90/10のクラス分布を維持します。層化がないと、運が良ければ代表的な分割が得られるかもしれませんが、クラス1が5%しかないテストセットになる可能性があり、信頼性の低い評価指標につながります。

複数の配列の分割

複数の配列を一度に分割でき、sklearnはそれらが同じ方法で分割されることを保証します(すべての配列に同じインデックス)。

import numpy as np
 
X = np.random.randn(100, 5)
y = np.random.randint(0, 2, 100)
sample_weights = np.random.rand(100)
 
# 3つの配列をすべて分割
X_train, X_test, y_train, y_test, weights_train, weights_test = train_test_split(
    X, y, sample_weights, test_size=0.2, random_state=42
)
 
print(f"X_train shape: {X_train.shape}")
print(f"y_train shape: {y_train.shape}")
print(f"weights_train shape: {weights_train.shape}")

これは、サンプル重み、複数の目的変数、または一貫して分割する必要がある追加のメタデータがある場合に特に便利です。

Train/Test Split vs 交差検証 vs ホールドアウト

異なる検証戦略は異なる目的に役立ちます。比較は次のとおりです:

方法データ使用計算コスト最適な用途制限事項
Train/Test Split70-80%訓練、20-30%テストクイックモデル評価、大規模データセット単一評価、分割で運不運がある可能性
交差検証100%訓練/テストに使用(k-fold)高(k倍遅い)小規模データセット、信頼性の高いパフォーマンス推定計算コストが高い、時系列には不向き
Train/Val/Test (ホールドアウト)60%訓練、20%検証、20%テストハイパーパラメータチューニング、最終評価より多くのデータが必要、より複雑なワークフロー
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
 
iris = load_iris()
X, y = iris.data, iris.target
model = RandomForestClassifier(random_state=42)
 
# 方法1: シンプルなtrain/test分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model.fit(X_train, y_train)
print(f"Train/Test Split Score: {model.score(X_test, y_test):.3f}")
 
# 方法2: 5分割交差検証
scores = cross_val_score(model, X, y, cv=5)
print(f"Cross-Validation Score: {scores.mean():.3f} (+/- {scores.std():.3f})")
 
# 方法3: Train/Val/Test分割
X_temp, X_test, y_temp, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X_temp, y_temp, test_size=0.25, random_state=42)
model.fit(X_train, y_train)
print(f"Validation Score: {model.score(X_val, y_val):.3f}")
print(f"Test Score: {model.score(X_test, y_test):.3f}")

ほとんどのプロジェクトでは、シンプルなtrain/test分割から始めてください。データが限られている場合や、より堅牢なパフォーマンス推定が必要な場合は交差検証を使用してください。ハイパーパラメータをチューニングする必要がある場合は、train/val/testを使用してください。

高度な分割テクニック

時系列分割

時系列データの場合、ランダムなシャッフルは時間的順序を破壊し、データリーク(過去を予測するために未来の情報を使用)につながる可能性があります。代わりにTimeSeriesSplitを使用してください:

from sklearn.model_selection import TimeSeriesSplit
import numpy as np
 
X = np.random.randn(100, 5)
y = np.random.randn(100)
 
tscv = TimeSeriesSplit(n_splits=5)
 
for train_index, test_index in tscv.split(X):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    print(f"Train size: {len(train_index)}, Test size: {len(test_index)}")

TimeSeriesSplitは、各訓練セットが特定のポイントまでのすべての過去のデータを含み、テストセットが直後の期間を含む複数のtrain/test分割を作成します。これは、将来を予測するために過去のデータしかない現実世界の予測をシミュレートします。

グループ化されたデータのGroupShuffleSplit

データにグループがある場合(例:同じ患者からの複数の測定、同じ顧客からの複数のトランザクション)、データリークを避けるために、グループ全体が訓練セットまたはテストセットのいずれかに留まることを確認する必要があります。

from sklearn.model_selection import GroupShuffleSplit
import numpy as np
 
X = np.random.randn(100, 5)
y = np.random.randint(0, 2, 100)
groups = np.array([0] * 25 + [1] * 25 + [2] * 25 + [3] * 25)  # 4グループ
 
gss = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
 
for train_idx, test_idx in gss.split(X, y, groups):
    X_train, X_test = X[train_idx], X[test_idx]
    y_train, y_test = y[train_idx], y[test_idx]
    print(f"Train groups: {np.unique(groups[train_idx])}")
    print(f"Test groups: {np.unique(groups[test_idx])}")

これにより、特定のグループのすべてのサンプルが訓練セットまたはテストセットのいずれかにあり、両方には決してないことが保証されます。

層化マルチアウトプット分割

マルチアウトプット分類問題の場合、2D配列でstratifyを直接使用することはできません。代わりに、すべての出力の組み合わせを表す単一のラベルを作成します:

import numpy as np
from sklearn.model_selection import train_test_split
 
X = np.random.randn(1000, 10)
y = np.random.randint(0, 2, (1000, 3))  # 3つのバイナリ出力
 
# 層化用の組み合わせラベルを作成
y_combined = y[:, 0] * 4 + y[:, 1] * 2 + y[:, 2]
 
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y_combined
)
 
print(f"Original distribution: {np.unique(y_combined, return_counts=True)[1]}")
print(f"Train distribution: {np.unique(y_combined[:(len(X) - len(X_test))], return_counts=True)[1]}")

Train Test Splitのベストプラクティス

適切な分割比率の選択

最も一般的な分割比率は次のとおりです:

  • 80/20: 中規模から大規模なデータセット(10,000以上のサンプル)の標準的な選択
  • 70/30: より堅牢なテスト評価のための小規模データセット(1,000〜10,000サンプル)に適しています
  • 90/10: 非常に大規模なデータセット(100,000以上のサンプル)で、10%でも十分なテストサンプルが得られる場合
  • 60/20/20: ハイパーパラメータをチューニングする際のtrain/validation/test用
import numpy as np
 
def recommend_split_ratio(n_samples):
    if n_samples < 1000:
        return "Consider cross-validation instead of simple split"
    elif n_samples < 10000:
        return "70/30 split recommended"
    elif n_samples < 100000:
        return "80/20 split recommended"
    else:
        return "90/10 or 80/20 split recommended"
 
sample_sizes = [500, 5000, 50000, 500000]
for size in sample_sizes:
    print(f"{size} samples: {recommend_split_ratio(size)}")

データリークの回避

データリークは、テストセットからの情報が訓練プロセスに影響を与える場合に発生します。一般的な原因:

  1. 分割前の前処理: 常に最初に分割してから前処理する
  2. 結合データでの特徴量スケーリング: 訓練データでのみスケーラーを適合させる
  3. 結合データでの特徴量選択: 訓練データのみを使用して特徴量を選択する
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import numpy as np
 
X = np.random.randn(1000, 10)
y = np.random.randint(0, 2, 1000)
 
# 間違い: 分割前にスケーリング(データリーク!)
scaler_wrong = StandardScaler()
X_scaled_wrong = scaler_wrong.fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X_scaled_wrong, y, test_size=0.2)
 
# 正しい: 最初に分割してからスケーリング
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)  # 訓練データに適合
X_test_scaled = scaler.transform(X_test)  # 訓練統計を使用してテストデータを変換

間違ったアプローチは、データセット全体(テストサンプルを含む)からの情報を使用してスケーリングパラメータを計算し、テストセットに関する情報が訓練プロセスにリークします。

可能な限り層化する

分類問題では、特定の理由がない限り、常に層化分割を使用してください。これは特に次の場合に重要です:

  • 不均衡なデータセット
  • 小規模データセット
  • まれなクラスを持つマルチクラス問題
from sklearn.model_selection import train_test_split
import numpy as np
 
# 希少疾患データセット: 1%の陽性ケース
X = np.random.randn(1000, 20)
y = np.array([0] * 990 + [1] * 10)
 
# 層化なし - テストセットに陽性ケースがない可能性!
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=123)
print(f"Non-stratified test positives: {sum(y_test)}")
 
# 層化あり - 比例表現を保証
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.1, random_state=123, stratify=y
)
print(f"Stratified test positives: {sum(y_test)}")

避けるべき一般的な間違い

1. random_stateを忘れる

random_stateがないと、コードを実行するたびに結果が変わります。これにより、デバッグが不可能になり、実験が再現できなくなります。

# 悪い: random_stateなし
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
 
# 良い: random_stateを設定
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

2. 不均衡クラスを層化しない

不均衡なデータセットの場合、ランダム分割は非常に代表的でないテストセットを作成する可能性があり、信頼性の低いパフォーマンス指標につながります。

# 悪い: 不均衡データに対する層化なし
X_train, X_test, y_train, y_test = train_test_split(X, y_imbalanced, test_size=0.2)
 
# 良い: 層化を使用
X_train, X_test, y_train, y_test = train_test_split(
    X, y_imbalanced, test_size=0.2, stratify=y_imbalanced, random_state=42
)

3. シャッフルを使用した時系列データの分割

時系列モデルは時間的順序に依存します。シャッフルはこの構造を破壊し、深刻なデータリークにつながる可能性があります。

# 悪い: 時系列データのシャッフル
X_train, X_test, y_train, y_test = train_test_split(
    X_timeseries, y_timeseries, test_size=0.2, shuffle=True
)
 
# 良い: シャッフルを無効にするかTimeSeriesSplitを使用
X_train, X_test, y_train, y_test = train_test_split(
    X_timeseries, y_timeseries, test_size=0.2, shuffle=False
)

4. 分割前の前処理

分割前にデータセット全体で前処理器(スケーラー、インピューター、エンコーダー)を適合させると、データリークが発生します。

# 悪い: 分割前の前処理
X_scaled = StandardScaler().fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2)
 
# 良い: 最初に分割してから前処理
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

5. ハイパーパラメータチューニングにテストセットを使用

テストセットは最終評価にのみ使用する必要があります。ハイパーパラメータを選択するために使用すると、本質的にテストデータで訓練していることになります。

# 悪い: テストセットでのチューニング
from sklearn.ensemble import RandomForestClassifier
 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
best_score = 0
best_params = None
for n_estimators in [10, 50, 100]:
    model = RandomForestClassifier(n_estimators=n_estimators)
    model.fit(X_train, y_train)
    score = model.score(X_test, y_test)  # テストセットを使用!
    if score > best_score:
        best_score = score
        best_params = n_estimators
 
# 良い: 検証セットまたは交差検証を使用
X_temp, X_test, y_temp, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X_temp, y_temp, test_size=0.25, random_state=42)
 
best_score = 0
best_params = None
for n_estimators in [10, 50, 100]:
    model = RandomForestClassifier(n_estimators=n_estimators)
    model.fit(X_train, y_train)
    score = model.score(X_val, y_val)  # 検証セットを使用
    if score > best_score:
        best_score = score
        best_params = n_estimators

実践例: 完全なワークフロー

train_test_splitを正しく使用した完全な機械学習ワークフローは次のとおりです:

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
 
# データをロード
np.random.seed(42)
X = np.random.randn(1000, 10)
y = (X[:, 0] + X[:, 1] > 0).astype(int)  # 二値分類
 
# ステップ1: データを分割(バランスの取れたテストセットのために層化)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)
 
# ステップ2: 前処理(訓練データのみに適合)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
 
# ステップ3: モデルを訓練
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)
 
# ステップ4: 評価
y_pred = model.predict(X_test_scaled)
print("Classification Report:")
print(classification_report(y_test, y_pred))
print("\nConfusion Matrix:")
print(confusion_matrix(y_test, y_pred))
 
# ステップ5: 過学習をチェック
train_score = model.score(X_train_scaled, y_train)
test_score = model.score(X_test_scaled, y_test)
print(f"\nTrain accuracy: {train_score:.3f}")
print(f"Test accuracy: {test_score:.3f}")
print(f"Overfitting gap: {train_score - test_score:.3f}")

インタラクティブなデータ分割のためのRunCellの使用

Jupyterノートブックで作業する際、異なる分割比率やパラメータを実験するのは面倒です。RunCell (opens in a new tab)は、Jupyterのデータサイエンスワークフロー専用に設計されたAIエージェントを提供します。次のことに役立ちます:

  • 複数の分割比率を自動的にテストして結果を比較
  • 前処理パイプラインのデータリークを検出
  • 特定のデータセットに最適な層化戦略を提案
  • 適切なtrain/test比率を選択するための検証曲線を生成

RunCellはJupyter環境に直接統合され、繰り返しコードを書くことなくデータ分割戦略を簡単に反復できます。

PyGWalkerでデータを可視化

データを分割した後、訓練セットとテストセットが類似した分布を持っていることを確認することが重要です。PyGWalker (opens in a new tab)は、pandasのDataFrameをTableauスタイルのインタラクティブな可視化に変換し、次のことを容易にします:

  • 訓練セットとテストセット間の特徴量分布の比較
  • 分割における潜在的なサンプリングバイアスの特定
  • クラス不均衡の可視化と層化が正しく機能したことの確認
  • 訓練データの特徴量間の関係の探索
import pygwalker as pyg
import pandas as pd
 
# 可視化用にDataFrameに変換
train_df = pd.DataFrame(X_train, columns=[f'feature_{i}' for i in range(X_train.shape[1])])
train_df['dataset'] = 'train'
test_df = pd.DataFrame(X_test, columns=[f'feature_{i}' for i in range(X_test.shape[1])])
test_df['dataset'] = 'test'
 
combined = pd.concat([train_df, test_df])
 
# インタラクティブな可視化を作成
pyg.walk(combined)

これにより、訓練分布とテスト分布が一致するかどうかをインタラクティブに探索でき、信頼性の高いモデル評価に不可欠です。

FAQ

80/20分割と70/30分割のどちらを選択すべきですか?

10,000サンプル以上のデータセットには80/20を使用し、より小規模なデータセット(1,000〜10,000サンプル)には70/30を使用してください。重要なのは、テストセットに信頼できる評価のための十分なサンプルがあることを確認することです。通常、分類問題では少なくとも200〜500サンプルです。非常に大規模なデータセット(100,000以上のサンプル)の場合、90/10または95/5を使用できます。5%でも数千のテストサンプルが得られるためです。

random_stateとは何ですか?なぜ重要ですか?

random_stateは、分割前にデータをシャッフルする乱数ジェネレータのシードです。同じrandom_state値を使用すると、コードを実行するたびに同じ分割が得られることが保証され、再現性とデバッグに不可欠です。これがないと、毎回異なるtrain/test分割が得られ、パフォーマンスの変化がモデルの改善によるものか、単に幸運/不運なデータ分割によるものかを判断できません。

いつstratifyパラメータを使用すべきですか?

不均衡なクラスや小規模なデータセットがある場合は特に、すべての分類問題にstratify=yを使用してください。層化により、訓練セットとテストセットのクラス分布が全体の分布と一致することが保証されます。たとえば、データの10%が陽性ケースの場合、層化により訓練セットとテストセットの両方が約10%の陽性ケースを持つことが保証され、代表的でない分割による評価バイアスが防止されます。

時系列データにtrain_test_splitを使用できますか?

いいえ、時系列データにshuffle=Truetrain_test_splitを使用すべきではありません。時間的順序が破壊され、データリーク(過去を予測するために未来のデータを使用)が発生するためです。代わりに、単純な時系列分割にはshuffle=Falsetrain_test_splitを使用するか、時間的順序を尊重する交差検証にはTimeSeriesSplitを使用してください。時系列では、訓練データが常にテストデータの前に時系列的に来ることを確認してください。

train_test_splitは交差検証とどう違いますか?

train_test_splitは単一のtrain/testパーティション(通常80/20)を作成し、1つのパフォーマンス推定値を提供します。交差検証(k-foldなど)は複数のtrain/test分割を作成して結果を平均し、より堅牢なパフォーマンス推定値を提供します。大規模データセットとクイック評価にはtrain_test_splitを使用してください。小規模データセット(1,000サンプル未満)またはより信頼性の高いパフォーマンス推定が必要な場合は交差検証を使用してください。交差検証はk倍遅く(例:5分割は5倍遅い)なりますが、パフォーマンス指標の分散を減らします。

結論

Sklearnのtrain_test_splitは、機械学習モデルを評価するための基本的なツールです。データを適切に分割することで、実世界のモデルの動作を予測する正直なパフォーマンス推定値が得られます。重要な原則を覚えておいてください:再現性のために常にrandom_stateを設定し、分類問題にはstratifyを使用し、分割前の前処理を避け、データセットサイズに基づいて分割比率を選択してください。

これらの基本をマスターすれば、過学習モデルや誤解を招くパフォーマンス指標につながる最も一般的な落とし穴を回避できます。シンプルな分類器を構築する場合でも、複雑なディープラーニングシステムを構築する場合でも、適切なtrain-test分割は信頼性の高い機械学習への第一歩です。

📚