Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Classification lessons
Probabilities and neighbours · ML-C05 · 12–18 MIN

Logistic regression

Understand a regularised linear class boundary.

  1. FollowRead and run the PythonCurrent exercise
  2. ChangeCompute and inspect the evidence
  3. TransferAdapt the Python

Understand the idea

Logistic regression is a classifier despite its name. It models class log-odds with a linear score and uses regularisation. Scaling helps optimisation and makes regularisation more comparable across inputs.

Understand a regularised linear class boundary.Class AClass BLogistic classification uses a linear decision boundary.
Understand a regularised linear class boundary.Scroll the diagram horizontally if needed.

What the syntax does

LogisticRegression
  • Creates a classification estimator despite the word regression in its name.
max_iter=2000
  • Sets an optimisation iteration limit; it does not guarantee convergence.
  • max_iter: 100, 500, 1000

Supplied for this practice

These objects are prepared afresh before your editor runs.

X
Feature dataframe for the declared population, preserving row indices.
X = df[['length', 'width']]
y
Target series, aligned with X.
y = df.label
X_train / X_test / y_train / y_test
Training feature rows from the declared split. Final-test feature rows from the declared split. Training targets, aligned with X_train. Final-test targets, aligned with X_test.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)

Outputs you create

answer
  1. The requested result, with the values, labels and row order described by this task.
CLASS180 · first 8 rows
lengthwidthlabel
236.033-0.805568A
581.2970.728558A
-1511.27-1.00866A
99.0248-0.24496A
-13.0141-0.660765A
681.1790.602475A
51.14720.873157A
362.131-0.665605A
Your task
  1. Fit a scaled logistic classifier and predict test labels.
answer
Hints

Think: The classifier’s optimisation uses the prepared feature scale learned from training rows.

Tools: Pipeline, StandardScaler and LogisticRegression.

Approach: Build the named scaling/classification steps, fit the training pair and predict through the complete pipeline.

Explained solution
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
model=Pipeline([('scale',StandardScaler()),('model',LogisticRegression(max_iter=2000,random_state=42))]).fit(X_train,y_train)
answer=model.predict(X_test)

The pipeline reuses training statistics for test rows while the iteration budget supports convergence.

Ctrl/⌘+Enter: Run · Tab: indent · Esc then Tab: leave editor

Python loads when you run. Code and results stay in this activity only.

Run your code to inspect its output. Check uses that same run.