Ravindra BagaleCourses & study guides मराठी Track your progress

34. Classification in Python with Logistic Regression

34.2 Copy-Run LogisticRegression

Why. You need the same discipline as regression: split, fit on train only, predict on test.

What. sklearn.linear_model.LogisticRegression learns weights that map features to a probability of class 1, then applies a threshold (default 0.5) to emit 0 or 1.

How.

Copy-run a tiny churn-style model

  1. Build X and y.
  2. train_test_split with stratify=y when classes are uneven (Chapter 31).
  3. Fit LogisticRegression.
  4. Print predict on the test set.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

df = pd.DataFrame({
 "orders_last_30d": [2, 8, 1, 12, 3, 9, 0, 11, 4, 7, 1, 10],
 "complaints": [1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0],
 "churned": [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
})
X = df[["orders_last_30d", "complaints"]]
y = df["churned"]

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

clf = LogisticRegression(max_iter=200)
clf.fit(X_train, y_train)
print("Predictions:", clf.predict(X_test))
print("True labels:", y_test.values)

What you should see. A short list of 0/1 predictions beside the true labels. Scoring quality comes in Chapter 37 — here the goal is a clean fit/predict path.

Fictional data

Churn flags are invented for teaching, not a real app export.