AI・データ分析

train_test_split()

機械学習で使うデータを「学習用」と「テスト用」に自動で分割します(scikit-learnの関数、事前に pip install scikit-learn が必要)。

構文

from sklearn.model_selection import train_test_split train_test_split(X, y, test_size=0.2)

使用例

from sklearn.model_selection import train_test_split
X = [[1], [2], [3], [4]]
y = [10, 20, 30, 40]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)
print(len(X_train), len(X_test))

実行結果

3 1

💡 実践的な使用例

from sklearn.model_selection import train_test_split
X = [[1], [2], [3], [4], [5]]
y = [10, 20, 30, 40, 50]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(X_train, X_test)

random_stateに数値を指定しておくと、毎回同じ分割結果になります。実験の再現性を保ちたいときに欠かせないオプションです。

関連トピック

AI scikit-learn 機械学習

← メソッド辞典に戻る