Menu

Splitting Data into Train and Test Sets

Splitting Data into Train and Test Sets

Once the data has been explored, it needs to be split into two parts: one for training the model and one for testing how well it performs on unseen data.

from sklearn.model_selection import train_test_split

X = df.drop("species", axis=1)
y = df["species"]

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

Code Explanation

  • X = df.drop("species", axis=1) separates the feature columns from the target column, keeping only the measurements.
  • y = df["species"] stores just the species labels separately, since this is what the model needs to predict.
  • test_size=0.2 reserves 20% of the data for testing, keeping the remaining 80%  for training.
  • random_state=42 ensures the same split happens every time the code runs, keeping results consistent.

After this step is done, you will have four separate variables, X_train and y_train for training the model, and X_test and y_test for evaluating it later. Once this split is ready, the next lesson moves on to actually building the model.


Machine Learning Tutorial

AP

Abhishek Pati



Learn via Video Course

Artificial Intelligence and Machine Learning Course Logo

Artificial Intelligence and Machine Learning Course

55 hrs



Get in Touch For Details