18. Building Classification and Regression Models¶
Learn how to build complete classification and regression models using Keras and PyTorch, from dataset preparation and model design to training, evaluation, prediction, and production-oriented model selection.
๐ฏ Learning Objectives¶
After completing this chapter, you will be able to:
- Understand the end-to-end Deep Learning model development workflow
- Differentiate between classification and regression problems
- Identify appropriate input and output representations
- Build classification models using Keras
- Build classification models using PyTorch
- Build regression models using Keras
- Build regression models using PyTorch
- Select appropriate output layers
- Select appropriate loss functions
- Select appropriate activation functions
- Understand binary and multi-class classification
- Understand regression model outputs
- Train models using mini-batches
- Evaluate classification models
- Evaluate regression models
- Use validation data correctly
- Compare Keras and PyTorch implementations
- Understand logits, probabilities, and thresholds
- Avoid common model-design mistakes
- Build production-oriented training pipelines
๐ Overview¶
Two of the most common supervised Deep Learning problems are:
Examples:
Classification
Email โ Spam / Not Spam
Image โ Cat / Dog
Transaction โ Fraud / Legitimate
Customer โ Churn / No Churn
The overall workflow is similar:
Data
โ
Preprocessing
โ
Train / Validation / Test Split
โ
Model
โ
Forward Pass
โ
Loss
โ
Backpropagation
โ
Optimizer
โ
Evaluation
โ
Prediction
๐ง Classification vs Regression¶
| Characteristic | Classification | Regression |
|---|---|---|
| Target | Category | Continuous value |
| Example | Fraud / Legitimate | Transaction Amount |
| Output | Class score / probability | Numeric value |
| Common Loss | Cross-Entropy / BCE | MSE / MAE |
| Typical Output | Logits | Linear value |
| Evaluation | Accuracy, Precision, Recall, F1 | MAE, MSE, RMSE, Rยฒ |
๐ End-to-End Model Development Workflow¶
flowchart LR
DATA["Raw Data"]
CLEAN["Data Preparation"]
SPLIT["Train / Validation / Test"]
MODEL["Model Architecture"]
TRAIN["Training"]
VALIDATE["Validation"]
EVALUATE["Evaluation"]
PREDICT["Prediction"]
DEPLOY["Deployment"]
DATA --> CLEAN
CLEAN --> SPLIT
SPLIT --> MODEL
MODEL --> TRAIN
TRAIN --> VALIDATE
VALIDATE --> EVALUATE
EVALUATE --> PREDICT
PREDICT --> DEPLOY
๐ง Choosing the Problem Type¶
Before building a model, identify the target variable.
Classification¶
If:
the problem is classification.
Examples:
Regression¶
If:
and the target is continuous, the problem is regression.
Examples:
๐ง Classification Types¶
Classification can be divided into:
Binary Classification
โ
โผ
Two Classes
Multi-Class Classification
โ
โผ
More Than Two Classes
Multi-Label Classification
โ
โผ
Multiple Independent Labels
๐ต Binary Classification¶
Example:
Typical model output:
with:
in PyTorch or:
in Keras.
๐ข Multi-Class Classification¶
Example:
The model produces one score for each class.
For four classes:
These are logits.
The predicted class is generally:
in PyTorch.
๐ก Multi-Label Classification¶
A sample may belong to multiple classes simultaneously.
Example:
Each class is treated as an independent binary decision.
Typical output:
with:
interpretation.
๐ง Regression¶
Regression predicts a continuous numerical value.
Example:
For house-price prediction:
๐ง Model Output Design¶
The output layer should match the problem.
| Problem | Output Units | Output Activation | Typical Loss |
|---|---|---|---|
| Binary Classification | 1 | Sigmoid interpretation | Binary Cross-Entropy |
| Multi-Class | N | Softmax interpretation | Cross-Entropy |
| Multi-Label | N | Sigmoid interpretation | Binary Cross-Entropy |
| Regression | 1 | Linear | MSE / MAE |
A major principle:
The model output, activation, target representation, and loss function must be designed together.
๐ง Classification Decision Pipeline¶
flowchart LR
INPUT["Features"]
MODEL["Neural Network"]
LOGITS["Logits"]
PROB["Probability"]
THRESHOLD["Threshold"]
CLASS["Predicted Class"]
INPUT --> MODEL
MODEL --> LOGITS
LOGITS --> PROB
PROB --> THRESHOLD
THRESHOLD --> CLASS
For binary classification, a threshold such as 0.5 is common as a starting point, but production systems may choose a different threshold based on business costs and validation performance.
๐ Classification Threshold¶
A binary classifier may produce:
Using:
the prediction becomes:
If the threshold is:
the same prediction becomes:
::contentReference[oaicite:0]{index=0}
This is important because threshold selection affects:
๐ง Dataset Preparation¶
Before model construction:
Raw Dataset
โ
Data Cleaning
โ
Feature Preparation
โ
Target Preparation
โ
Normalization / Scaling
โ
Train / Validation / Test Split
๐ Train / Validation / Test¶
A typical structure is:
Responsibilities:
| Dataset | Purpose |
|---|---|
| Training | Learn parameters |
| Validation | Tune architecture / hyperparameters |
| Test | Final unbiased evaluation |
โ Data Leakage¶
Never allow information from the validation or test set to influence training preprocessing.
Incorrect:
Preferred:
๐ง Feature Scaling¶
Neural networks often benefit from appropriately scaled numerical features.
Common approaches:
Standardization is commonly represented as:
[ z=\frac{x-\mu}{\sigma} ]
where:
The scaling parameters should be learned from the training set.
๐ง Model Architecture¶
A basic feed-forward model looks like:
๐ง Classification Architecture¶
flowchart LR
INPUT["Input Features"]
D1["Dense / Linear"]
A1["ReLU"]
D2["Dense / Linear"]
A2["ReLU"]
OUT["Output"]
LOSS["Classification Loss"]
INPUT --> D1
D1 --> A1
A1 --> D2
D2 --> A2
A2 --> OUT
OUT --> LOSS
๐ง Regression Architecture¶
flowchart LR
INPUT["Input Features"]
D1["Dense / Linear"]
A1["ReLU"]
D2["Dense / Linear"]
A2["ReLU"]
OUT["Linear Output"]
LOSS["Regression Loss"]
INPUT --> D1
D1 --> A1
A1 --> D2
D2 --> A2
A2 --> OUT
OUT --> LOSS
๐ Part I โ Classification with Keras¶
๐งช Keras Binary Classification¶
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Input(
shape=(10,)
),
tf.keras.layers.Dense(
64,
activation="relu"
),
tf.keras.layers.Dense(
32,
activation="relu"
),
tf.keras.layers.Dense(
1,
activation="sigmoid"
)
])
Compile:
๐ง Keras Binary Classification Architecture¶
flowchart LR
INPUT["10 Features"]
D1["Dense 64"]
R1["ReLU"]
D2["Dense 32"]
R2["ReLU"]
OUT["Dense 1"]
SIG["Sigmoid"]
INPUT --> D1
D1 --> R1
R1 --> D2
D2 --> R2
R2 --> OUT
OUT --> SIG
๐งช Training Keras Classification Model¶
๐งช Keras Multi-Class Classification¶
Suppose there are:
The output layer can be:
model = tf.keras.Sequential([
tf.keras.layers.Input(
shape=(784,)
),
tf.keras.layers.Dense(
128,
activation="relu"
),
tf.keras.layers.Dense(
64,
activation="relu"
),
tf.keras.layers.Dense(
10,
activation="softmax"
)
])
Compile:
๐ง Keras Multi-Class Output¶
For example:
Prediction:
๐ง sparse_categorical_crossentropy¶
Use:
such as:
Example:
๐ง categorical_crossentropy¶
Use:
Example:
Then:
๐ Part II โ Classification with PyTorch¶
๐งช PyTorch Binary Classification¶
import torch
import torch.nn as nn
class BinaryClassifier(
nn.Module
):
def __init__(
self
):
super().__init__()
self.network = nn.Sequential(
nn.Linear(
10,
64
),
nn.ReLU(),
nn.Linear(
64,
32
),
nn.ReLU(),
nn.Linear(
32,
1
)
)
def forward(
self,
x
):
return self.network(
x
)
Loss:
๐ง Why No Sigmoid Layer?¶
With:
the model should generally return raw logits.
Conceptually:
The loss internally combines the sigmoid operation with the binary cross-entropy calculation in a numerically stable way.
For inference:
๐งช PyTorch Binary Prediction¶
model.eval()
with torch.no_grad():
logits = model(
x
)
probabilities = torch.sigmoid(
logits
)
predictions = (
probabilities >= 0.5
).int()
๐งช PyTorch Multi-Class Classification¶
class MultiClassClassifier(
nn.Module
):
def __init__(
self,
input_features,
num_classes
):
super().__init__()
self.network = nn.Sequential(
nn.Linear(
input_features,
128
),
nn.ReLU(),
nn.Linear(
128,
64
),
nn.ReLU(),
nn.Linear(
64,
num_classes
)
)
def forward(
self,
x
):
return self.network(
x
)
Loss:
๐ง PyTorch Multi-Class Pipeline¶
flowchart LR
INPUT["Input"]
MODEL["PyTorch Model"]
LOGITS["Raw Logits"]
LOSS["CrossEntropyLoss"]
ARGMAX["Argmax"]
CLASS["Predicted Class"]
INPUT --> MODEL
MODEL --> LOGITS
LOGITS --> LOSS
LOGITS --> ARGMAX
ARGMAX --> CLASS
During training:
During prediction:
If probabilities are needed:
๐ง Keras vs PyTorch Classification¶
| Concept | Keras | PyTorch |
|---|---|---|
| Dense Layer | Dense |
nn.Linear |
| ReLU | activation="relu" |
nn.ReLU() |
| Binary Loss | binary_crossentropy |
BCEWithLogitsLoss |
| Multi-Class Loss | categorical_crossentropy |
CrossEntropyLoss |
| Training | model.fit() |
Training loop |
| Prediction | model.predict() |
model(x) |
| Evaluation | model.evaluate() |
Custom evaluation loop |
| GPU | TensorFlow device management | .to(device) |
๐ Part III โ Regression with Keras¶
๐งช Keras Regression Model¶
model = tf.keras.Sequential([
tf.keras.layers.Input(
shape=(10,)
),
tf.keras.layers.Dense(
64,
activation="relu"
),
tf.keras.layers.Dense(
32,
activation="relu"
),
tf.keras.layers.Dense(
1
)
])
Notice that the output layer does not use:
It produces a continuous value.
๐ง Keras Regression Architecture¶
flowchart LR
INPUT["Input Features"]
D1["Dense 64"]
R1["ReLU"]
D2["Dense 32"]
R2["ReLU"]
OUT["Dense 1"]
INPUT --> D1
D1 --> R1
R1 --> D2
D2 --> R2
R2 --> OUT
๐งช Compile Regression Model¶
Train:
๐งฎ Mean Squared Error¶
For predictions:
and targets:
MSE measures the average squared error.
๐งฎ Mean Absolute Error¶
MAE measures average absolute error.
๐งช PyTorch Regression Model¶
class RegressionModel(
nn.Module
):
def __init__(
self,
input_features
):
super().__init__()
self.network = nn.Sequential(
nn.Linear(
input_features,
64
),
nn.ReLU(),
nn.Linear(
64,
32
),
nn.ReLU(),
nn.Linear(
32,
1
)
)
def forward(
self,
x
):
return self.network(
x
)
Loss:
Optimizer:
๐ง PyTorch Regression Training¶
for epoch in range(
epochs
):
model.train()
for x_batch, y_batch in train_loader:
x_batch = x_batch.to(
device
)
y_batch = y_batch.to(
device
)
optimizer.zero_grad()
predictions = model(
x_batch
)
loss = loss_fn(
predictions,
y_batch
)
loss.backward()
optimizer.step()
๐ง Regression Pipeline¶
flowchart LR
INPUT["Features"]
MODEL["Neural Network"]
OUTPUT["Continuous Output"]
LOSS["MSE / MAE"]
GRAD["Gradients"]
UPDATE["Parameter Update"]
INPUT --> MODEL
MODEL --> OUTPUT
OUTPUT --> LOSS
LOSS --> GRAD
GRAD --> UPDATE
UPDATE --> MODEL
๐ง Classification Loss Selection¶
A practical decision tree:
flowchart TD
START["Classification Problem"]
BINARY{"Binary?"}
MULTI{"Multiple Classes?"}
MULTILABEL["Multi-Label"]
BCE["Binary Cross-Entropy"]
CE["Categorical Cross-Entropy"]
START --> BINARY
BINARY -->|Yes| BCE
BINARY -->|No| MULTI
MULTI -->|Independent Labels| MULTILABEL
MULTI -->|Mutually Exclusive Classes| CE
๐ง Regression Loss Selection¶
General guidance:
| Loss | Characteristics |
|---|---|
| MSE | Penalizes large errors strongly |
| MAE | More robust to outliers |
| Huber | Combines MSE-like and MAE-like behavior |
๐ง Model Evaluation โ Classification¶
Common metrics:
๐งฎ Accuracy¶
[ Accuracy = \frac{TP+TN} {TP+TN+FP+FN} ]
::contentReference[oaicite:4]{index=4}
Accuracy can be misleading when classes are heavily imbalanced.
๐งฎ Precision¶
[ Precision = \frac{TP} {TP+FP} ]
Precision answers:
Of the examples predicted as positive, how many were actually positive?
๐งฎ Recall¶
[ Recall = \frac{TP} {TP+FN} ]
Recall answers:
Of all actual positive examples, how many did the model identify?
๐งฎ F1 Score¶
[ F1 = 2 \frac{Precision\times Recall} {Precision+Recall} ]
F1 provides a balance between precision and recall.
๐ Confusion Matrix¶
This matrix is fundamental for understanding classification behavior.
๐ง Model Evaluation โ Regression¶
Common metrics:
๐งฎ RMSE¶
RMSE is the square root of MSE.
[ RMSE = \sqrt{ \frac{1}{n} \sum_{i=1}^{n} (y_i-\hat{y}_i)^2 } ]
RMSE has the same units as the target variable.
๐ Regression Residuals¶
A residual is:
[ e_i=y_i-\hat{y}_i ]
A good regression model should generally produce residuals without strong systematic patterns.
๐ง Regression Line¶
For simple linear regression:
[ \hat{y}=b_0+b_1x ]
::contentReference[oaicite:7]{index=7}
Deep Neural Networks extend this idea by learning multiple nonlinear transformations.
๐ง Keras Training Workflow¶
flowchart TD
DATA["Training Data"]
MODEL["Keras Model"]
COMPILE["Compile"]
FIT["model.fit()"]
VALIDATE["Validation"]
EVAL["model.evaluate()"]
PREDICT["model.predict()"]
DATA --> MODEL
MODEL --> COMPILE
COMPILE --> FIT
FIT --> VALIDATE
VALIDATE --> EVAL
EVAL --> PREDICT
๐ง PyTorch Training Workflow¶
flowchart TD
DATA["DataLoader"]
MODEL["PyTorch Model"]
ZERO["zero_grad()"]
FORWARD["Forward Pass"]
LOSS["Loss"]
BACK["backward()"]
STEP["optimizer.step()"]
EVAL["Evaluation"]
DATA --> ZERO
ZERO --> FORWARD
FORWARD --> LOSS
LOSS --> BACK
BACK --> STEP
STEP --> EVAL
EVAL --> DATA
๐ง Keras vs PyTorch Training¶
Keras¶
PyTorch¶
for epoch in range(
epochs
):
model.train()
for x_batch, y_batch in train_loader:
optimizer.zero_grad()
predictions = model(
x_batch
)
loss = loss_fn(
predictions,
y_batch
)
loss.backward()
optimizer.step()
The abstraction level is different, but the underlying optimization process is similar.
๐ง What Happens During Training?¶
Regardless of framework:
Input
โ
Forward Pass
โ
Prediction
โ
Loss
โ
Gradient Calculation
โ
Parameter Update
โ
Repeat
๐ง Epochs and Batches¶
Suppose:
Then approximately:
and:
across 20 epochs.
๐ง Overfitting¶
A model may achieve:
This suggests potential overfitting.
Typical solutions include:
๐ง Underfitting¶
Example:
The model may be underfitting.
Potential approaches:
Increase Model Capacity
Train Longer
Improve Features
Reduce Excessive Regularization
Tune Learning Rate
๐ง Early Stopping¶
Keras:
callback = tf.keras.callbacks.EarlyStopping(
monitor="val_loss",
patience=5,
restore_best_weights=True
)
Training:
PyTorch requires implementing or using an external training utility for equivalent early-stopping behavior.
๐ง Model Capacity¶
A model's capacity is influenced by:
Too little capacity:
Too much capacity:
๐ง Choosing Output Activations¶
Binary Classification
โ
Sigmoid interpretation
Multi-Class
โ
Softmax interpretation
Multi-Label
โ
Independent Sigmoid interpretation
Regression
โ
Linear Output
โ Common Activation Mistakes¶
Mistake 1¶
Using:
for a regression output.
Incorrect.
Mistake 2¶
Using:
for mutually exclusive multi-class logits when the intended loss expects raw class logits.
Mistake 3¶
Adding:
before PyTorch:
This is generally unnecessary.
Mistake 4¶
Using:
on a regression output when the target can legitimately be negative.
๐ง Production Model Selection¶
Model architecture should be driven by:
Problem Type
+
Data Size
+
Data Distribution
+
Latency Requirements
+
Accuracy Requirements
+
Interpretability
+
Hardware
+
Cost
Do not automatically choose the deepest network.
๐ข Enterprise Example โ Fraud Detection¶
Suppose a financial system predicts whether a transaction is fraudulent.
Input:
Target:
Architecture:
Transaction Features
โ
Dense Layer
โ
ReLU
โ
Dense Layer
โ
ReLU
โ
Binary Logit
โ
Probability
โ
Threshold
โ
Fraud / Legitimate
Production considerations:
False Positive Cost
False Negative Cost
Latency
Class Imbalance
Threshold Selection
Model Drift
Feature Drift
Monitoring
๐ข Enterprise Example โ Customer Value Prediction¶
Input:
Target:
Architecture:
Evaluation:
๐ง Production Model Lifecycle¶
flowchart TD
PROBLEM["Business Problem"]
DATA["Data"]
EXP["Experimentation"]
TRAIN["Training"]
VALIDATE["Validation"]
TEST["Final Test"]
REGISTER["Model Registry"]
DEPLOY["Deployment"]
MONITOR["Monitoring"]
RETRAIN["Retraining"]
PROBLEM --> DATA
DATA --> EXP
EXP --> TRAIN
TRAIN --> VALIDATE
VALIDATE --> TEST
TEST --> REGISTER
REGISTER --> DEPLOY
DEPLOY --> MONITOR
MONITOR --> RETRAIN
RETRAIN --> TRAIN
๐ง Classification vs Regression โ Framework Perspective¶
flowchart TD
PROBLEM["Supervised Learning"]
CLASS["Classification"]
REG["Regression"]
KERAS_C["Keras Classifier"]
TORCH_C["PyTorch Classifier"]
KERAS_R["Keras Regressor"]
TORCH_R["PyTorch Regressor"]
PROBLEM --> CLASS
PROBLEM --> REG
CLASS --> KERAS_C
CLASS --> TORCH_C
REG --> KERAS_R
REG --> TORCH_R
๐งช Practical Exercise 1 โ Binary Classification¶
Build a binary classifier using:
Implement it using:
Compare:
๐งช Practical Exercise 2 โ Multi-Class Classification¶
Build a classifier with:
Implement:
Compare:
๐งช Practical Exercise 3 โ Regression¶
Build a regression model:
Evaluate:
Implement using both:
๐งช Practical Exercise 4 โ Threshold Optimization¶
Train a binary classifier and evaluate thresholds:
For each threshold calculate:
Identify the threshold that best matches the business objective.
๐งช Practical Exercise 5 โ Imbalanced Classification¶
Create a dataset with:
Compare:
Demonstrate why accuracy alone can be misleading.
๐งช Practical Exercise 6 โ Keras vs PyTorch¶
Build equivalent models in both frameworks.
Compare:
Model Definition
Loss Configuration
Optimizer
Training
Validation
Prediction
Checkpointing
GPU Execution
Document the differences.
๐ง Interview Questions¶
Beginner¶
1. What is the difference between classification and regression?¶
Classification predicts categories, while regression predicts continuous numerical values.
2. What output layer is commonly used for regression?¶
A linear output layer with one or more continuous outputs.
3. What loss is commonly used for regression?¶
MSE is common, while MAE and Huber are also frequently useful.
4. What is binary classification?¶
A classification problem with two possible classes.
5. What is multi-class classification?¶
A classification problem where each sample belongs to one of multiple mutually exclusive classes.
Intermediate¶
6. Why does PyTorch commonly use raw logits with CrossEntropyLoss?¶
Because CrossEntropyLoss internally performs the relevant log-softmax and negative-log-likelihood computation.
7. Why does BCEWithLogitsLoss use logits?¶
It combines sigmoid and binary cross-entropy in a numerically stable implementation.
8. Why should validation data not be used to fit preprocessing parameters?¶
Doing so introduces information leakage and can make evaluation overly optimistic.
9. Why is accuracy insufficient for imbalanced classification?¶
A model can achieve high accuracy by predominantly predicting the majority class while performing poorly on the minority class.
10. What is the difference between logits and probabilities?¶
Logits are unconstrained model scores. Probabilities are normalized or transformed scores, such as sigmoid or softmax outputs.
Advanced¶
11. How would you select a classification threshold?¶
Evaluate candidate thresholds on validation data using business-relevant metrics such as precision, recall, F1, cost, or expected utility.
12. Why might you prefer recall over precision?¶
In situations where missing a positive case is more costly than generating false alarms, maximizing recall may be preferable.
13. Why might you prefer precision over recall?¶
When false positives are particularly expensive, improving precision may be more important.
14. Why can a deeper network perform worse than a smaller network?¶
Because additional capacity can increase overfitting, optimization difficulty, computational cost, and sensitivity to hyperparameters.
15. How would you compare Keras and PyTorch implementations?¶
Compare equivalent:
Architecture
Loss
Optimizer
Dataset
Batch Size
Learning Rate
Epochs
Initialization
Evaluation Metrics
Hardware
Only then is the framework comparison meaningful.
๐ข Enterprise Perspective¶
Building a model is not the same as solving a business problem.
An enterprise Deep Learning implementation must connect:
Business Objective
โ
ML Problem Definition
โ
Data
โ
Model
โ
Evaluation
โ
Business Threshold
โ
Deployment
โ
Monitoring
For classification, the most accurate model is not always the best model.
For regression, the lowest MSE is not always the best business solution.
Production decisions should consider:
Production Insight
Do not optimize only for model accuracy.
A production model must satisfy the complete system objective:
A slightly less accurate model may be preferable if it is significantly faster, cheaper, easier to monitor, and more reliable in production.
๐ Key Takeaways¶
- Classification predicts categories.
- Regression predicts continuous values.
- Binary classification commonly uses one output logit.
- Multi-class classification uses one logit per class.
- Multi-label classification uses independent outputs for each label.
- Regression generally uses a linear output.
- Output activation and loss function must be selected together.
- Keras provides high-level APIs such as
model.fit(). - PyTorch provides greater control through explicit training loops.
CrossEntropyLossexpects raw logits in the common PyTorch multi-class pattern.BCEWithLogitsLosscombines sigmoid behavior with binary cross-entropy.- MSE, MAE, and RMSE are common regression metrics.
- Accuracy alone can be misleading for imbalanced datasets.
- Classification thresholds affect precision and recall.
- Validation data should guide model and hyperparameter decisions.
- Test data should be reserved for final evaluation.
- Data leakage can invalidate model evaluation.
- Keras and PyTorch can implement equivalent architectures using different abstractions.
- Production model selection must consider business requirements, latency, cost, and maintainability in addition to predictive performance.
๐ Further Reading¶
Continue with:
- 19. Convolutional Neural Networks
- 20. CNN Architecture, Optimization and Training
- 21. Transfer Learning and Fine-Tuning
- 22. ResNet, Residual Connections and TorchVision
- 23. Vision Transformers and CNN-ViT Hybrids
- 35. GPU-Accelerated Deep Learning
- 36. Deep Learning Training and Model Lifecycle
- 37. Building Production Deep Learning Systems
The next chapter moves into Computer Vision, beginning with the architecture and mathematics of Convolutional Neural Networks.
โก๏ธ Next Chapter¶
19. Convolutional Neural Networks
Enterprise AI Engineering Handbook
Building Production-Grade Enterprise AI Systems โ One Chapter at a Time.