31. Train Test Split in Machine Learning
31.2 How train_test_split Works in sklearn
Why. sklearn gives one clear function so you do not hand-split and accidentally leak rows.
What. train_test_split from sklearn.model_selection randomly splits arrays or DataFrames into train and test parts.
How.
Copy-run in Jupyter
- Install/import sklearn (you set up packages in Chapter 2).
- Build a tiny fictional table.
- Call
train_test_splitwithtest_size=0.2andrandom_state=42. - Print shapes. Confirm rows do not overlap.
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.DataFrame({
"items": [2, 3, 5, 8, 1, 4, 7, 6, 2, 9],
"distance_km": [1.2, 3.0, 4.5, 6.1, 0.8, 2.2, 5.0, 3.3, 1.0, 7.4],
"was_late": [0, 0, 1, 1, 0, 0, 1, 0, 0, 1],
})
X = df[["items", "distance_km"]]
y = df["was_late"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print("train rows", len(X_train), "test rows", len(X_test))
print(X_train.head())
What you should see. About 8 train rows and 2 test rows on this tiny set. On real data, keep more rows; this is only to learn the API.
No model fit yet
We only split. Fitting starts in Chapter 33 (linear regression draft). Foundations first.
Ravindra Bagale's Tip
Make it a habit to write random_state=42 when you split data. Then your output matches your classmate's output, which makes debugging much easier. Later, in a real project, your team can decide its own policy for random_state.
Ravindra Bagale's Tip – मराठी
Data split करताना random_state=42 लिहायची सवय लावा. त्यामुळे तुमचा output तुमच्या classmate च्या output शी match होतो, आणि debugging खूप सोपं होतं. नंतर खऱ्या project मध्ये random_state साठी कोणती policy वापरायची हे तुमची team ठरवू शकते.
Ravindra Bagale's Tip – हिंदी
Data split करते समय random_state=42 लिखने की आदत डालो. इससे तुम्हारा output तुम्हारे classmate के output से match होता है, और debugging बहुत आसान हो जाती है. बाद में असली project में random_state के लिए कौन सी policy रखनी है, यह तुम्हारी team तय कर सकती है.