TECHNOLOGIESTieInn Technologies

Your first model with scikit-learn: split, fit, predict

ML Foundations · 10 questions

Short notes

Key idea

scikit-learn models all follow the same three steps: split the data, fit on the training part, predict on the test part and measure. Learn the pattern once and it works for every model.

Syntax

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

X = df[["months_active", "orders_90d", "complaints"]]
y = df["churned"]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y)

model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
pred = model.predict(X_test)
print(accuracy_score(y_test, pred))
model.predict_proba(X_test)[:, 1]     # probability of class 1

Example

Swap LogisticRegression for RandomForestClassifier() and nothing else changes: same fit, predict and score. That makes comparing models quick.

Traps

  • Measuring on the training data shows how well the model memorised, not how well it predicts.
  • Always compare with a baseline, such as predicting the most common class every time.
  • stratify=y keeps class balance in both splits.
  • Set random_state so results are repeatable.

Want the full lesson with step-by-step examples, a project and a certificate? ML Foundations course, ₹180 →

Questions

Open in Code Lab5 free questions
5 questions

    Your first model with scikit-learn: split, fit, predict

  1. Question 1easy

    In scikit-learn code, what do X and y usually hold?

  2. Your first model with scikit-learn: split, fit, predict

  3. Question 2easy

    With 200 rows and test_size=0.25, how many rows are in the test set?

    from sklearn.model_selection import train_test_split
    rows = list(range(200))
    train, test = train_test_split(rows, test_size=0.25, random_state=0)
    print(len(test))
  4. Your first model with scikit-learn: split, fit, predict

  5. Question 3medium

    A model scores 99% on its training data and 70% on the test data. Which number do you report?

  6. Your first model with scikit-learn: split, fit, predict

  7. Question 4medium

    What does model.predict_proba(X_test)[:, 1] return for a yes/no classifier?

  8. Your first model with scikit-learn: split, fit, predict

  9. Question 5easy

    Why pass random_state=42 to train_test_split?

5 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.