Course contentsShow
← Data Science
Lesson 2059 of 2,14547. Reproducible ResearchFree lesson

Seeds in Train-Test Splits

Apply random seeds to ensure consistent data partitioning across runs for fair model comparison.

Seeds in Train-Test Splits

What you'll learn: How to use random seeds to guarantee identical train-test splits every time you run your experiments.

Why This Matters

When you split your data into training and testing sets, the split is typically random. Without a seed, each run produces a different partition—meaning your model might score 92% accuracy today and 88% tomorrow, not because your code changed, but because you got different test samples. This makes comparison impossible.

The Core Idea

Setting a seed before creating train-test splits ensures the random selection process produces exactly the same split every time. Think of it like shuffling a deck of cards with a specific "shuffle algorithm ID"—anyone using that same ID will shuffle the cards into the identical order.

When you apply a seed to your split operation, the pseudorandom number generator (PRNG) follows the same sequence, selecting the same rows for training and testing across all runs.

Practical Application

In Python's scikit-learn, the train_test_split() function accepts a random_state parameter:

from sklearn.model_selection import train_test_split

# Same split every time
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

In R's caret package:

set.seed(42)
trainIndex <- createDataPartition(y, p=0.8, list=FALSE)

The specific number (42, 123, etc.) doesn't matter—what matters is consistency. Use the same seed across team members, in your reports, and between experiments to ensure everyone works with identical data partitions.

When It's Critical

Seeds in splits are essential when:

  • Comparing different models fairly
  • Debugging model behavior
  • Sharing experiments with colleagues
  • Publishing reproducible research

Key Takeaway: Always set a random seed before train-test splits to ensure consistent data partitioning across runs, enabling fair model comparison and reproducible results.