0Pricing
Data Science Academy · Aula

Usar train_test_split corretamente

Estratificação, random_state e proporções.

Usar train_test_split corretamente é uma aula grátis de Data Science Academy no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Data Science Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Data Science Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

One Helper, Two Sets

The function train_test_split takes your features and target and hands back train and test pieces in one tidy call.

from sklearn.model_selection import train_test_split

Four Things Come Back

It returns four objects in a fixed order: train features, test features, train target, test target. Unpack them carefully so each lands in the right name.

X_train, X_test, y_train, y_test = train_test_split(X, y)

Set the Test Size

Use test_size to choose how much data to reserve. A value of 0.2 means 20% goes to the test set.

train_test_split(X, y, test_size=0.2)

Shuffling by Default

By default the rows are shuffled before splitting. That mixing prevents any hidden order in your file from biasing either set.

Make It Reproducible

Pass random_state to lock the shuffle. The same number gives the same split every run, so your results are repeatable. 🔁

train_test_split(X, y, test_size=0.2, random_state=42)

Why Reproducibility Matters

Without a fixed seed, every run reshuffles and your scores wobble. A locked random_state lets teammates reproduce your exact numbers.

The Imbalance Problem

If a class is rare, a plain random split might dump most of it into one set. Now train and test no longer reflect the same class balance.

Stratify to the Rescue

Pass stratify equal to your target so both sets keep the same class proportions. Essential for classification with uneven classes.

train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)

Keep X and y Aligned

The split keeps each row's features and label together. Row 7's features always travel with row 7's label, never scrambled apart.

Choosing the Ratio

Common splits are 80/20 or 70/30. With lots of data you can spare a smaller test slice; with little data, give the test set a bit more.

Split Before You Touch

Run the split first, before scaling or filling values. Doing prep on the full set leaks test information back into training.

Quick Check

Your target classes are very imbalanced. Which argument helps?

Recap

Unpack four sets, set test_size, fix random_state for repeatability, and use stratify when classes are uneven. Split first, prep later. 🔁

Perguntas Frequentes

A aula “Usar train_test_split corretamente” é grátis?

Sim — o texto completo de “Usar train_test_split corretamente” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Data Science Academy, atualize para CoddyKit PRO. O curso de Data Science Academy inclui 4 aulas no total.

O que vou aprender em “Usar train_test_split corretamente”?

Estratificação, random_state e proporções. Você pratica Data Science Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Data Science Academy?

Nenhuma experiência prévia é necessária. Data Science Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “Usar train_test_split corretamente”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Data Science Academy?

Sim. Cada aula de Data Science Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Por que separar um conjunto de teste
  2. Usar train_test_split corretamente
  3. Validação cruzada em K partes
  4. Impedir o vazamento de dados antes que comece
← Voltar para Data Science Academy