Lesson 6 of 18 · 2 min
Why Train/Test Split? (Critical Concept)
The problem without split:
Imagine you're studying for an exam. If you study using the exact exam paper, memorize the answers, then take the same exam — you'll score 100%. But you haven't actually learned anything. You just memorized.
Same with ML models. If you train on all data and test on the same data — the model "memorizes" answers. It looks great but fails on new data.
The solution — split your data:
- Training set (80%): Model learns from this — like studying
- Test set (20%): Model never sees this during training — like the actual exam
from sklearn.model_selection import train_test_split
X = df.drop("Price", axis=1)
y = df["Price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# random_state=42 means same split every time you run (reproducible)
print(f"Total rows: {len(df)}")
print(f"Training rows: {len(X_train)}") # 80%
print(f"Testing rows: {len(X_test)}") # 20%
# CORRECT: fit only on training data
model.fit(X_train, y_train)
# CORRECT: evaluate on test data (unseen)
y_pred = model.predict(X_test)
# WRONG (never do this):
# model.fit(X, y) # trained on everything
# y_pred = model.predict(X) # tested on same data = cheating
