CSE-403 Machine Learning

Logistic Regression

Classification Basics, Logistic Regression, Softmax Regression, Multi-Class Classification, Regularization and Model Evaluation

Md. Atikuzzaman
Lecturer, Department of Computer Science & Engineering
atik@cse.green.edu.bd

From Scores to Decisions

Regression predicts a continuous number. Classification predicts a category.

Examples: spam/not spam, pass/fail, disease/no disease, grade A/B/C/D/F.

FeaturesScoreProbabilityClass

Student data
→
Probability
→
Pass / Fail

Daily Classification Examples

Email

Spam or not spam.

Medical

Normal or abnormal case.

Finance

Fraud or legitimate transaction.

Education

At-risk or not-at-risk student.

Classification Dataset

#Study hoursAttendancePrevious markLabel
11.54842Fail
22.05546Fail
33.56458Pass
44.07061Pass
55.58270Pass
62.86050Fail

Notation

x = input features
y ∈ {0,1}
ŷ = predicted class
p(y=1|x) = predicted probability

Binary, Multi-Class and Multi-Label

Binary

Two classes.

y ∈ {0,1}

Multi-Class

More than two exclusive classes.

y ∈ {1,...,K}

Multi-Label

Multiple labels at the same time.

y ∈ {0,1}K

Regression Line vs Classification Boundary

RegressionPredict a continuous valueClassificationFind a boundary between classes

Same Linear Idea, Different Output

Linear Regression: Study Hours → GPA

Suppose the input is only weekly study hours.

\[ z = wx+b \] \[ \hat{y}=z \]

Output: a continuous value such as GPA.

Study hours = 5
z = 0.35(5) + 1.20 = 2.95
Predicted GPA = 2.95

Logistic Regression: Study Hours → Pass / Fail

For classification, we can still begin with the same linear score.

\[ z = wx+b \]

But now the target is not a continuous GPA. The target is a class:

y = 1 → Pass
y = 0 → Fail

The problem: the linear score \(z\) can be any real number, so it is not yet a probability.

Input x
Study hours
→
Linear score
\(z=wx+b\)
→
Regression: use z directly
GPA

Why Logistic Regression Adds the Sigmoid

Linear score z = wx + b Probability of Pass 0.5 threshold Near 0 → likely Fail Near 1 → likely Pass 0 0.5 1

Logistic Regression keeps the linear score

\[ z=wx+b \]

Then it adds one extra step:

\[ p=\sigma(z)=\frac{1}{1+e^{-z}} \]

The sigmoid converts any value of \(z\) into a number between 0 and 1.

Linear regression:
x → wx+b → continuous output

Logistic regression:
x → wx+b → sigmoid → probability → class

Main idea: the linear part is still there. Logistic regression adds sigmoid because classification needs a probability and a decision.

Logistic Regression

Linear score + probability transformation

Logistic regression starts exactly like a linear model by computing z = wᵀx + b.

The sigmoid then turns that unrestricted score into a valid probability between 0 and 1.

\[z=\mathbf{w}^T\mathbf{x}+b\]\[\sigma(z)=\frac{1}{1+e^{-z}}\]\[0 < \sigma(z) < 1\]

Interactive Sigmoid and Threshold

Change the score

Logistic Regression Model

\[p(y=1|\mathbf{x})=\sigma(\mathbf{w}^{T}\mathbf{x}+b)\]\[\hat{y}=\begin{cases}1,&p\ge\tau\\0,&p<\tau\end{cases}\]

Meaning

The logit becomes a probability. The threshold converts probability into a final class.

Binary Cross-Entropy Loss

\[\mathcal{L}^{(i)}=-[y^{(i)}\log(p^{(i)})+(1-y^{(i)})\log(1-p^{(i)})]\]\[J=\frac{1}{n}\sum_{i=1}^{n}\mathcal{L}^{(i)}\]

Why this loss?

It strongly penalizes confident wrong predictions.

Gradient Descent for Logistic Regression

\[\mathbf{w}:=\mathbf{w}-\alpha\frac{\partial J}{\partial \mathbf{w}}\]\[b:=b-\alpha\frac{\partial J}{\partial b}\]\[\frac{\partial J}{\partial \mathbf{w}}=\frac{1}{n}\mathbf{X}^T(\mathbf{p}-\mathbf{y})\]

Idea

Predict probabilities, calculate loss, update parameters, and repeat.

Interactive Decision Boundary

Move the boundary

Softmax Regression

\[p(y=k|\mathbf{x})=\frac{e^{z_k}}{\sum_{j=1}^{K}e^{z_j}}\]\[z_k=\mathbf{w}_k^T\mathbf{x}+b_k\]\[\sum_{k=1}^{K}p(y=k|\mathbf{x})=1\]

Meaning

Softmax converts multiple class scores into a probability distribution.

Interactive Softmax Probabilities

Change class scores

Multi-Class Cross-Entropy

\[\mathbf{y}^{(i)}=[0,0,\ldots,1,\ldots,0]\]\[\mathcal{L}^{(i)}=-\sum_{k=1}^{K}y_k^{(i)}\log(p_k^{(i)})\]

One-hot label

For classes A, B, C, true class B becomes [0, 1, 0].

One-vs-Rest vs Softmax

One-vs-Rest

Train one binary classifier per class.

Simple, but probabilities may not sum to 1.

Softmax

One model compares all classes together.

Common for mutually exclusive classes.

Regularization

\[J_{reg}=J+\lambda||\mathbf{w}||_2^2\]\[J_{lasso}=J+\lambda||\mathbf{w}||_1\]

Purpose

Regularization discourages overly large weights and helps reduce overfitting.

Feature Scaling and Class Imbalance

Feature scaling

Gradient-based training works better when features have comparable scales.

x' = (x - μ) / σ

Class imbalance

Accuracy can be misleading when one class dominates.

Use precision, recall, F1, ROC-AUC, class weights or resampling.

Confusion Matrix

TP
Actual +, Predicted +
FN
Actual +, Predicted −
FP
Actual −, Predicted +
TN
Actual −, Predicted −

Why it matters

Accuracy alone hides mistake types. False negatives and false positives have different real-world costs.

Interactive Evaluation Metrics

Set values

Metrics

\[Precision=\frac{TP}{TP+FP},\quad Recall=\frac{TP}{TP+FN}\]\[F1=\frac{2PR}{P+R}\]

Accuracy, Precision, Recall and F1

Accuracy

(TP+TN)/Total

Precision

TP/(TP+FP)

Recall

TP/(TP+FN)

F1

2PR/(P+R)

ROC Curve and AUC

Threshold-independent view

ROC curve compares true positive rate and false positive rate across many thresholds.

TPR = TP/(TP+FN)
FPR = FP/(FP+TN)

Colab: Logistic Regression Example


import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix

X = np.array([[1.5,48], [2.0,55], [2.8,60], [3.5,64],
              [4.0,70], [5.5,82], [6.0,85], [7.0,90]])
y = np.array([0, 0, 0, 1, 1, 1, 1, 1])

model = LogisticRegression()
model.fit(X, y)

y_pred = model.predict(X)
print(confusion_matrix(y, y_pred))
print("Accuracy:", accuracy_score(y, y_pred))
print("Precision:", precision_score(y, y_pred))
print("Recall:", recall_score(y, y_pred))
print("F1:", f1_score(y, y_pred))
print(model.predict_proba([[3, 66]]))

Common Mistakes

Only accuracy

Misleading in imbalanced datasets.

Wrong threshold

0.5 may not match real risk.

No scaling

Optimization can become unstable.

Data leakage

Test data used during training.

Class Activity

Scenario

A model predicts whether a student is at risk of failing. False negatives mean missing students who need support.

Discussion

Which metric matters most: accuracy, precision, recall or F1?

Should the threshold be lower than 0.5?

Takeaways

Classification predicts categories.

Logistic regression uses sigmoid for binary classification.

Softmax regression handles mutually exclusive multi-class classification.

Cross-entropy penalizes confident wrong predictions.

Evaluation should include confusion matrix, precision, recall, F1 and threshold analysis.

Questions?

Next: Decision Trees and Ensemble Learning