Total Pageviews

Saturday, September 26, 2026

šŸ“Š Feature Selection Laboratory

šŸ“Š Feature Selection Laboratory

Complete Mathematical & Interactive Implementation

5 Features × 10 Records Dataset

1. Dataset Used for All Methods

We will use exactly 5 input features and 10 records. The target variable is ExamScore.

Student StudyHours Attendance SleepHours Assignments ScreenTime ExamScore
126053845
236564750
347065655
457576562
568077568
678288474
788588380
899099386
91092910292
1010951010196
Features: StudyHours, Attendance, SleepHours, Assignments, ScreenTime
Target: ExamScore
Records: 10
Features: 5

2. Mathematical Representation

The dataset can be represented by a feature matrix X and target vector y.

X = [ x₁₁ x₁₂ x₁₃ x₁₄ x₁₅
x₂₁ x₂₂ x₂₃ x₂₄ x₂₅
⋮
x₁₀₁ x₁₀₂ x₁₀₃ x₁₀₄ x₁₀₅ ]

Therefore:

X ∈ R10 × 5

and:

y ∈ R10

The objective is to determine whether all five features are useful or whether a smaller subset can provide similar predictive information.

3. Feature Selection Categories

šŸ”µ Filter Methods

Correlation, Variance Threshold, Chi-Square, ANOVA and Mutual Information.

🟣 Wrapper Methods

Forward Selection, Backward Elimination and Recursive Feature Elimination.

🟢 Embedded Methods

L1/Lasso, Decision Tree and Random Forest importance.

🟠 Feature Extraction

PCA creates new components rather than selecting original columns.

4. Variance Threshold

Variance measures how much a feature changes across observations. A feature with extremely small variance may contain little information.

Variance(X) = Ī£(Xįµ¢ − X̄)² / n

Example: StudyHours

StudyHours = 2, 3, 4, 5, 6, 7, 8, 9, 10, 10

Mean:

X̄ = 64 / 10 = 6.4

Population variance:

σ² = [(2−6.4)² + (3−6.4)² + ... + (10−6.4)²] / 10
The feature has substantial variation, so it would not be removed by a reasonable variance threshold.

Python

from sklearn.feature_selection import VarianceThreshold

selector = VarianceThreshold(threshold=1)

X_new = selector.fit_transform(X) 

5. Correlation-Based Feature Selection

Correlation measures the linear relationship between a feature and the target.

r = Ī£(Xįµ¢ − X̄)(Yįµ¢ − Ȳ) / √[Ī£(Xįµ¢ − X̄)² × Ī£(Yįµ¢ − Ȳ)²]

Interpretation:

|r|Interpretation
0No linear relationship
0 to 0.3Weak
0.3 to 0.7Moderate
0.7 to 1Strong
1Perfect linear relationship

Python

import pandas as pd

correlation = df.corr(numeric_only=True)

print(correlation["ExamScore"].sort_values(
ascending=False
)) 
A feature having a high correlation with the target does not automatically mean that it should always be selected. Correlation mainly measures linear association.

6. Chi-Square Feature Selection

The Chi-Square test measures statistical dependence between categorical variables. In machine learning it is commonly used for classification problems.

χ² = Ī£ (O − E)² / E

where:

  • O = observed frequency
  • E = expected frequency

The expected frequency is:

E = (Row Total × Column Total) / Grand Total

Python

from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2

selector = SelectKBest(
score_func=chi2,
k=3
)

X_selected = selector.fit_transform(X, y) 
Chi-square requires suitable non-negative feature values and is mainly appropriate when the target is categorical.

7. ANOVA F-Test

ANOVA compares variation between groups with variation within groups. For classification, it can evaluate numerical features against a categorical target.

F = MSbetween / MSwithin

where:

MSbetween = SSbetween / (k−1)
MSwithin = SSwithin / (N−k)

Python

from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif

selector = SelectKBest(
score_func=f_classif,
k=3
)

X_selected = selector.fit_transform(X, y) 

8. Mutual Information

Mutual Information measures how much knowing one variable reduces uncertainty about another.

I(X;Y) = Σₓ Σᵧ p(x,y) log [ p(x,y) / (p(x)p(y)) ]

Higher mutual information indicates greater statistical dependency.

Python

from sklearn.feature_selection import mutual_info_regression

scores = mutual_info_regression(X, y)

for feature, score in zip(
feature_names, scores
):
print(feature, score) 

9. Forward Selection

Forward selection begins with zero features and adds one feature at a time. At each step, the feature that produces the best validation performance is considered.

S₀ = ∅

Then:

S₁ = S₀ ∪ {best feature}
S₂ = S₁ ∪ {next best feature}

The process continues until the required number of features is reached.

Conceptual Python

selected = []

remaining = feature_names.copy()

while remaining:

```
best_feature = None
best_score = -float("inf")

for feature in remaining:

    current = selected + [feature]

    # train model using current
    # calculate validation score

    # if score > best_score:
    #     best_score = score
    #     best_feature = feature

selected.append(best_feature)
remaining.remove(best_feature)
```

10. Backward Elimination

Backward elimination starts with all five features and removes one feature at a time.

S₀ = {StudyHours, Attendance, SleepHours, Assignments, ScreenTime}

At every iteration the least useful feature is removed.

S₁ = S₀ − {least useful feature}
S₂ = S₁ − {least useful feature}

Conceptual Python

selected = feature_names.copy()

while len(selected) > 2:

```
# evaluate removing each feature

# remove feature whose removal
# causes the smallest performance loss

pass
```

11. Recursive Feature Elimination — RFE

RFE repeatedly fits a model and removes the least important feature.

5 features → 4 → 3 → 2 → selected subset

Python

from sklearn.feature_selection import RFE
from sklearn.linear_model import LinearRegression

model = LinearRegression()

rfe = RFE(
estimator=model,
n_features_to_select=2
)

rfe.fit(X, y)

print(rfe.support_)
print(rfe.ranking_) 
Feature Selected? Rank
StudyHours✓ / ✗1–5
Attendance✓ / ✗1–5
SleepHours✓ / ✗1–5
Assignments✓ / ✗1–5
ScreenTime✓ / ✗1–5

12. L1 Regularization / Lasso

L1 regularization adds the absolute value of coefficients to the loss function.

Loss = Ī£(yįµ¢ − Å·įµ¢)² + λΣ|βⱼ|

If a coefficient becomes zero:

βⱼ = 0

the corresponding feature can effectively be excluded from the linear model.

Python

from sklearn.linear_model import Lasso

model = Lasso(alpha=0.1)

model.fit(X, y)

for feature, coefficient in zip(
feature_names,
model.coef_
):
print(feature, coefficient) 
L1 regularization is an embedded method because feature selection occurs during model training.

13. Decision Tree Feature Importance

Decision trees can estimate feature importance from the reduction in impurity produced by splits.

Importance(j) = Ī£ (weight of node) × impurity decrease

The normalized feature importances usually sum to 1.

from sklearn.tree import DecisionTreeRegressor

model = DecisionTreeRegressor(
random_state=42
)

model.fit(X, y)

for feature, importance in zip(
feature_names,
model.feature_importances_
):
print(feature, importance) 

14. Random Forest Feature Importance

Random Forest combines many decision trees. Feature importance can be obtained from the fitted forest.

Importance(feature) = Average importance across trees

Python

from sklearn.ensemble import RandomForestRegressor

model = RandomForestRegressor(
n_estimators=100,
random_state=42
)

model.fit(X, y)

importance = model.feature_importances_

for f, score in zip(
feature_names,
importance
):
print(f, score) 

15. PCA — Feature Extraction

PCA is included here for comparison, but technically it is a feature-extraction/dimensionality-reduction technique rather than selection of original columns.

Step 1 — Standardization

z = (x − μ) / σ

Step 2 — Covariance Matrix

C = 1/(n−1) Xįµ€X

Step 3 — Eigenvalue Problem

Cv = λv

The eigenvectors corresponding to the largest eigenvalues become the principal components.

PC₁ = w₁X₁ + w₂X₂ + ... + w₅X₅

Explained Variance Ratio

EVRᵢ = λᵢ / Σλⱼ

Python

from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

X_scaled = StandardScaler().fit_transform(X)

pca = PCA(n_components=2)

X_pca = pca.fit_transform(X_scaled)

print(pca.explained_variance_ratio_)
print(X_pca) 

16. Interactive Feature Selection Simulator

The following JavaScript calculates several basic statistics directly from the 10-record dataset.

Click a button to calculate the results.

17. Complete Python Implementation

import pandas as pd
from sklearn.feature_selection import (
    SelectKBest,
    f_classif,
    mutual_info_regression,
    RFE,
    VarianceThreshold
)
from sklearn.linear_model import Lasso, LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

# ------------------------------------------------

# DATASET

# ------------------------------------------------

df = pd.DataFrame({

```
"StudyHours":
[2,3,4,5,6,7,8,9,10,10],

"Attendance":
[60,65,70,75,80,82,85,90,92,95],

"SleepHours":
[5,6,6,7,7,8,8,9,9,10],

"Assignments":
[3,4,5,6,7,8,8,9,10,10],

"ScreenTime":
[8,7,6,5,5,4,3,3,2,1],

"ExamScore":
[45,50,55,62,68,74,80,86,92,96]
```

})

features = [
"StudyHours",
"Attendance",
"SleepHours",
"Assignments",
"ScreenTime"
]

X = df[features]
y = df["ExamScore"]

# ------------------------------------------------

# CORRELATION

# ------------------------------------------------

print("\nCORRELATION")
print(df.corr(numeric_only=True)["ExamScore"])

# ------------------------------------------------

# VARIANCE THRESHOLD

# ------------------------------------------------

print("\nVARIANCE")

vt = VarianceThreshold(
threshold=1
)

vt.fit(X)

for feature, selected in zip(
features,
vt.get_support()
):
print(feature, selected)

# ------------------------------------------------

# MUTUAL INFORMATION

# ------------------------------------------------

print("\nMUTUAL INFORMATION")

mi = mutual_info_regression(
X,
y,
random_state=42
)

for feature, score in zip(
features,
mi
):
print(feature, score)

# ------------------------------------------------

# RFE

# ------------------------------------------------

print("\nRFE")

rfe = RFE(
LinearRegression(),
n_features_to_select=2
)

rfe.fit(X, y)

for feature, selected, rank in zip(
features,
rfe.support_,
rfe.ranking_
):
print(
feature,
selected,
rank
)

# ------------------------------------------------

# LASSO

# ------------------------------------------------

print("\nLASSO")

lasso = Lasso(alpha=0.1)

lasso.fit(X, y)

for feature, coefficient in zip(
features,
lasso.coef_
):
print(
feature,
coefficient
)

# ------------------------------------------------

# DECISION TREE

# ------------------------------------------------

print("\nDECISION TREE")

tree = DecisionTreeRegressor(
random_state=42
)

tree.fit(X, y)

for feature, importance in zip(
features,
tree.feature_importances_
):
print(
feature,
importance
)

# ------------------------------------------------

# RANDOM FOREST

# ------------------------------------------------

print("\nRANDOM FOREST")

forest = RandomForestRegressor(
n_estimators=100,
random_state=42
)

forest.fit(X, y)

for feature, importance in zip(
features,
forest.feature_importances_
):
print(
feature,
importance
)

# ------------------------------------------------

# PCA

# ------------------------------------------------

print("\nPCA")

scaler = StandardScaler()

X_scaled = scaler.fit_transform(X)

pca = PCA(
n_components=2
)

X_pca = pca.fit_transform(
X_scaled
)

print(
"Explained variance:",
pca.explained_variance_ratio_
)

print(
"PCA data:"
)

print(X_pca) 

18. Method Comparison

Method Category Uses Target? Original Features? Main Mathematics
Variance Threshold Filter No Yes Variance
Correlation Filter Yes Yes Pearson r
Chi-Square Filter Yes Yes χ²
ANOVA Filter Yes Yes F-statistic
Mutual Information Filter Yes Yes Information theory
Forward Selection Wrapper Yes Yes Validation score
Backward Elimination Wrapper Yes Yes Validation score
RFE Wrapper Yes Yes Model importance
L1/Lasso Embedded Yes Yes L1 penalty
Decision Tree Embedded Yes Yes Impurity reduction
Random Forest Embedded Yes Yes Average tree importance
PCA Extraction No No Eigenvalues/eigenvectors

19. Important Machine Learning Rule

Never perform feature selection using the complete dataset before cross-validation or testing.

The feature-selection procedure should be fitted only on the training portion of the data. Otherwise information from the validation/test data can influence the selected features, producing data leakage.

Correct Pipeline

Raw Data → Train/Test Split → Feature Selection on Training Data → Model Training → Test Evaluation

With Cross-Validation

Pipeline( Feature Selection + Model ) → Cross Validation → Final Test

20. Final Summary

Technique What It Does
Variance Removes features with very little variation.
Correlation Measures linear relationship with target or between features.
Chi-Square Measures categorical statistical dependence.
ANOVA Compares between-group and within-group variation.
Mutual Information Measures information dependency.
Forward Selection Adds features progressively.
Backward Elimination Removes features progressively.
RFE Recursively removes less important features.
Lasso Uses L1 regularization to shrink coefficients.
Decision Tree Uses impurity reduction for feature importance.
Random Forest Aggregates importance across multiple trees.
PCA Transforms original features into principal components.
Key idea: Feature selection attempts to reduce the number of input variables while retaining useful predictive information. The appropriate method depends on the dataset, target type, model and computational constraints.

šŸ“Š Feature Selection in Machine Learning

```

šŸ“Š Feature Selection in Machine Learning

Concepts, Techniques, Python Implementation and Comparison

1. What is Feature Selection?

Feature Selection is the process of choosing the most useful input variables from a dataset for building a machine learning model. Instead of using every available column, we retain features that provide useful information for predicting the target.

Example:
Suppose a student-performance dataset contains: Study Hours, Attendance, Sleep Hours, Favorite Color, Student ID and Exam Score. If the target is Exam Score, some variables may provide little useful predictive information. Feature selection helps identify the useful variables.

Why is Feature Selection Important?

  • Reduces the number of input variables.
  • Can reduce model training time.
  • Can make models easier to interpret.
  • Can reduce the effect of irrelevant or redundant variables.
  • Can help reduce overfitting when irrelevant features are removed.
  • Can simplify machine learning pipelines.

2. Feature Selection vs Feature Extraction

Feature Selection Feature Extraction
Selects existing features from the dataset. Creates new features from existing features.
Original feature meaning is retained. New transformed variables may be less directly interpretable.
Examples: Chi-Square, RFE, SelectKBest. Examples: PCA, ICA, NMF.
Important: PCA is generally considered a dimensionality-reduction / feature-extraction technique rather than conventional feature selection, because it transforms the original variables into new components.

3. Main Types of Feature Selection

šŸ”µ Filter Methods

Features are evaluated using statistical or information-based measures, usually independently of a particular ML model.

🟣 Wrapper Methods

Different feature subsets are evaluated using a machine learning model.

🟢 Embedded Methods

Feature selection happens as part of model training, such as through regularization or tree-based importance.

4. Filter Methods

Filter methods evaluate features using properties of the data, rather than repeatedly training a particular predictive model.

4.1 Correlation

Correlation measures the strength and direction of association between numerical variables. Highly correlated predictor variables can contain redundant information.

Pearson Correlation: r = Cov(X,Y) / (σX × ĻƒY)
```
import pandas as pd

df = pd.DataFrame({
    "Age": [20,21,22,23,24],
    "StudyHours": [2,4,5,7,8],
    "Score": [45,55,65,78,88]
})

print(df.corr())
```
```
             Age  StudyHours  Score
Age         1.00       0.99    0.99
StudyHours  0.99       1.00    0.99
Score       0.99       0.99    1.00
```

4.2 Chi-Square Test

The Chi-Square test is commonly used for testing the relationship between categorical features and a categorical target. In scikit-learn, chi2 can be used with non-negative feature values.

χ² = Ī£ (O − E)² / E
```
from sklearn.feature_selection import SelectKBest, chi2
from sklearn.datasets import load_iris

X, y = load_iris(return_X_y=True)

selector = SelectKBest(score_func=chi2, k=2)

X_new = selector.fit_transform(X, y)

print("Original shape:", X.shape)
print("Selected shape:", X_new.shape)
```
```
Original shape: (150, 4)
Selected shape: (150, 2)
```

4.3 Mutual Information

Mutual information measures the amount of information that one variable provides about another. It can detect nonlinear relationships that simple correlation may not capture.

```
from sklearn.feature_selection import mutual_info_classif
from sklearn.datasets import load_iris

X, y = load_iris(return_X_y=True)

scores = mutual_info_classif(X, y, random_state=42)

for i, score in enumerate(scores):
    print("Feature", i + 1, ":", round(score, 4))
```

4.4 ANOVA F-Test

The ANOVA F-test can be used to evaluate the relationship between numerical input features and a categorical target.

```
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.datasets import load_iris

X, y = load_iris(return_X_y=True)

selector = SelectKBest(f_classif, k=2)

X_new = selector.fit_transform(X, y)

print(X_new.shape)
```

4.5 Variance Threshold

A feature with almost no variation across observations may provide little information. VarianceThreshold removes features whose variance is below a specified threshold.

```
from sklearn.feature_selection import VarianceThreshold

X = [
    [1, 10, 5],
    [1, 20, 5],
    [1, 30, 5],
    [1, 40, 5]
]

selector = VarianceThreshold(threshold=0)

X_new = selector.fit_transform(X)

print(X_new)
```
```
[[10]
 [20]
 [30]
 [40]]
```

5. Wrapper Methods

Wrapper methods evaluate feature subsets by training and testing a chosen machine learning model. They can be computationally expensive because many candidate subsets may need to be evaluated.

5.1 Forward Selection

Forward selection starts with no selected features and adds features one at a time according to a chosen evaluation criterion.

Basic idea:
Start → Select the best feature → Add another useful feature → Continue until the desired number of features is reached.

5.2 Backward Elimination

Backward elimination starts with all available features and removes features step by step according to the selected evaluation criterion.

5.3 Recursive Feature Elimination — RFE

RFE repeatedly trains a model, ranks features according to model importance, and removes less important features until the requested number remains.

```
from sklearn.datasets import load_iris
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression

X, y = load_iris(return_X_y=True)

model = LogisticRegression(max_iter=1000)

rfe = RFE(
    estimator=model,
    n_features_to_select=2
)

rfe.fit(X, y)

print("Selected:", rfe.support_)
print("Ranking:", rfe.ranking_)
```
```
Selected: [False False  True  True]
Ranking:  [3 2 1 1]
```

5.4 Exhaustive Feature Selection

Exhaustive selection evaluates many or all possible feature combinations within a specified range and chooses a subset according to a model-performance criterion.

Limitation: If there are many features, the number of possible combinations can become extremely large, making exhaustive search computationally expensive.

6. Embedded Methods

Embedded methods perform feature selection during the process of fitting a model. The model itself provides information about feature relevance.

6.1 L1 Regularization

L1 regularization adds a penalty based on the absolute values of model coefficients. For some linear models, this can drive coefficients exactly to zero, effectively removing corresponding features.

```
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression

X, y = load_iris(return_X_y=True)

model = LogisticRegression(
    penalty="l1",
    solver="liblinear",
    max_iter=1000
)

model.fit(X, y)

print(model.coef_)
```

6.2 Tree-Based Feature Importance

Decision trees and ensemble methods such as Random Forest can provide feature-importance measures derived from the fitted trees.

```
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier

X, y = load_iris(return_X_y=True)

model = RandomForestClassifier(
    n_estimators=100,
    random_state=42
)

model.fit(X, y)

for name, importance in zip(
    load_iris().feature_names,
    model.feature_importances_
):
    print(name, round(importance, 4))
```

7. Dimensionality Reduction and Feature Transformation

Some techniques reduce the dimensionality of data by creating a smaller representation of the original variables. These techniques should be distinguished from selecting original columns.

7.1 Principal Component Analysis — PCA

PCA transforms correlated numerical variables into a smaller set of principal components. The components are ordered according to the variance they explain.

```
from sklearn.datasets import load_wine
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

wine = load_wine()

X = wine.data

X_scaled = StandardScaler().fit_transform(X)

pca = PCA(n_components=2)

X_pca = pca.fit_transform(X_scaled)

print("Original:", X.shape)
print("After PCA:", X_pca.shape)

print("Explained variance:")
print(pca.explained_variance_ratio_)
```
```
Original: (178, 13)
After PCA: (178, 2)

Explained variance:
[approximately 0.36, approximately 0.19]
```

7.2 ICA

Independent Component Analysis attempts to represent data using statistically independent components. It is particularly associated with signal separation and source-separation problems.

7.3 NMF

Non-negative Matrix Factorization decomposes a non-negative data matrix into lower-dimensional non-negative matrices. It can be useful for topics, images and other non-negative datasets.

7.4 t-SNE

t-SNE is primarily a nonlinear dimensionality-reduction and visualization technique. It is commonly used to visualize high-dimensional data in two or three dimensions rather than as a conventional feature-selection method.

7.5 Autoencoders

An autoencoder is a neural network trained to reconstruct its input. Its lower-dimensional bottleneck representation can be used as a learned representation of the original data.

8. Complete Python Example — SelectKBest

The following example demonstrates a simple feature-selection workflow using the Iris dataset.

```
from sklearn.datasets import load_iris
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif

# Load dataset
iris = load_iris()

X = iris.data
y = iris.target

# Select the best two features
selector = SelectKBest(
    score_func=f_classif,
    k=2
)

X_selected = selector.fit_transform(X, y)

# Display results
print("Original shape:", X.shape)
print("Selected shape:", X_selected.shape)

print("\nSelected features:")

for feature, selected in zip(
    iris.feature_names,
    selector.get_support()
):
    if selected:
        print(feature)
```
```
Original shape: (150, 4)
Selected shape: (150, 2)

Selected features:
petal length (cm)
petal width (cm)
```

9. Recommended Feature Selection Workflow

Step 1

Understand the dataset and identify the target variable.

Step 2

Remove obvious identifiers or data-leakage variables.

Step 3

Handle missing values and encode categorical variables appropriately.

Step 4

Split the data into training and test sets.

Step 5

Perform feature selection using only the training data.

Step 6

Train the final model using the selected features.

Step 7

Evaluate performance on unseen test data.

Important — Data Leakage: Feature selection should normally be fitted inside the training process, especially when cross-validation is being used. Selecting features using the complete dataset before validation can allow information from the validation/test data to influence the selection.

10. Comparison of Feature Selection Methods

Method Uses ML Model? Main Idea Typical Advantage Typical Limitation
Correlation No Measures association Simple and fast May miss nonlinear relationships
Chi-Square No Statistical association Useful for categorical classification problems Requires appropriate non-negative feature representation
Mutual Information No Measures information dependence Can detect nonlinear dependency Scores can require careful interpretation
Forward Selection Yes Add features progressively Model-specific Can be computationally expensive
Backward Elimination Yes Remove features progressively Model-specific Can require many model fits
RFE Yes Recursively eliminate features Works with many estimators Repeated model fitting
L1 Regularization Yes Penalizes coefficients Can produce sparse models Depends on model and regularization
Random Forest Importance Yes Uses tree-based importance Captures nonlinear relationships Importance measures require interpretation
PCA No target required Creates principal components Strong dimensionality reduction Components are transformed variables

11. Advantages of Feature Selection

  • šŸ“‰ Reduces dimensionality.
  • ⚡ May reduce computational cost.
  • šŸŽÆ Can focus the model on informative variables.
  • 🧠 Can improve interpretability.
  • šŸ›”️ Can help control overfitting when irrelevant variables are removed.
  • šŸ“Š Can simplify visualization and analysis.

12. Limitations

  • A selected feature may be useful only in combination with another feature.
  • Different methods can produce different feature subsets.
  • Wrapper methods can require substantial computation.
  • Feature selection can be affected by preprocessing choices.
  • Feature selection does not automatically guarantee better test performance.
  • Selection must be performed carefully to avoid data leakage.

13. Quick Revision

Question Answer
What is feature selection? Selecting useful input variables from the original feature set.
Three major supervised categories? Filter, Wrapper and Embedded methods.
Example of a filter method? Chi-Square, correlation, mutual information or ANOVA F-test.
Example of a wrapper method? RFE, forward selection or backward elimination.
Example of an embedded method? L1 regularization or tree-based feature importance.
What does RFE mean? Recursive Feature Elimination.
What does PCA do? Transforms data into principal components with reduced dimensionality.
Main purpose? Reduce unnecessary information and build a simpler, potentially more effective model.
```

Friday, September 25, 2026

šŸ”„ Iterative Thresholding

šŸ”„ Iterative Thresholding

B.Sc. Computer Science Honours | Digital Image Processing & Image Segmentation

šŸ“˜ 1. Introduction

Iterative Thresholding, also called the Iterative Selection Method, is an image segmentation technique used to automatically determine a suitable threshold value from the intensity distribution of an image.

Instead of choosing the threshold manually, the algorithm starts with an initial estimate and repeatedly improves the threshold until the value becomes stable.

Core idea: Divide the image into two groups using an initial threshold, calculate the mean intensity of both groups, and use those means to calculate a new threshold.
Grayscale
Image
→
Divide into
Two Groups
→
Calculate
Means
→
New
Threshold
↻
Stable
Threshold

⚙️ 2. Basic Principle

Let the grayscale image contain pixel intensities represented by f(x,y).

Choose an initial threshold T. The pixels are divided into two groups:

G₁ = {f(x,y) > T}
G₂ = {f(x,y) ≤ T}

Calculate the mean intensity of each group:

μ₁ = Mean(G₁)      μ₂ = Mean(G₂)

Then calculate a new threshold:

Tnew = (μ₁ + μ₂) / 2

The process continues until the threshold becomes stable.

🧠 3. Iterative Thresholding Algorithm

Step 1: Convert the image into a grayscale image.
Step 2: Select an initial threshold T.
Step 3: Divide the pixels into two groups G₁ and G₂.
Step 4: Calculate the mean intensity μ₁ of G₁.
Step 5: Calculate the mean intensity μ₂ of G₂.
Step 6: Calculate the new threshold: Tnew = (μ₁ + μ₂) / 2.
Step 7: Compare the new threshold with the previous threshold.
Step 8: If the difference is sufficiently small, stop. Otherwise repeat the process.

šŸ” 4. Complete Flow of Iterative Thresholding

Initial
T
→
G₁ & G₂
→
μ₁ & μ₂
→
Tnew
→
Compare
If the threshold has not converged: repeat the process. If it has converged: produce the segmented image.

šŸ”¢ 5. Numerical Example

Consider the following simplified set of grayscale pixel values:

20, 30, 40, 50, 60, 150, 160, 170, 180, 190

Assume the initial threshold is:

T₀ = 100

Iteration 1

Using T = 100:

Group Pixel Values Mean
G₁ > 100 150, 160, 170, 180, 190 170
G₂ ≤ 100 20, 30, 40, 50, 60 40

New threshold:

T₁ = (170 + 40) / 2 = 105

Iteration 2

Using T = 105, the groups remain unchanged.

μ₁ = 170      μ₂ = 40
T₂ = (170 + 40) / 2 = 105
Since: T₂ = T₁ = 105, the threshold has converged.
Final Threshold = 105

šŸŽÆ 6. Convergence Condition

The algorithm stops when the difference between consecutive threshold values becomes sufficiently small.

|Tnew − Told| < ε

Here, ε is a small tolerance value.

In a simple implementation, the algorithm can also stop when Tnew = Told.

šŸ“ 7. Mathematical Formulation

Let the image contain N pixels and let the threshold at iteration k be Tk.

The two groups are:

G₁(Tā‚–) = {f(x,y) | f(x,y) > Tā‚–}
G₂(Tā‚–) = {f(x,y) | f(x,y) ≤ Tā‚–}

The group means are:

μ₁(Tā‚–) = Mean[G₁(Tā‚–)]
μ₂(Tā‚–) = Mean[G₂(Tā‚–)]

Then:

Tā‚–₊₁ = [μ₁(Tā‚–) + μ₂(Tā‚–)] / 2

🧪 8. Interactive Iterative Thresholding Calculator

Enter pixel values and click Calculate Iterations.

🧩 9. 8×8 Image Matrix Demonstration

The following interactive matrix represents a simplified grayscale image. Iterative thresholding will automatically calculate a threshold from the matrix.

Generate a matrix and run the algorithm.

šŸ 10. Beginner Python Implementation

The following Python program implements iterative thresholding without using a built-in automatic thresholding function.

import cv2 import numpy as np # Read image image = cv2.imread("input.jpg") # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Initial threshold T = 128 while True: # Group 1: pixels greater than threshold G1 = gray[gray > T] # Group 2: pixels less than or equal to threshold G2 = gray[gray <= T] # Calculate means if len(G1) == 0 or len(G2) == 0: break mean1 = np.mean(G1) mean2 = np.mean(G2) # Calculate new threshold new_T = (mean1 + mean2) / 2 print("Old T:", T) print("Mean G1:", mean1) print("Mean G2:", mean2) print("New T:", new_T) print("----------------") # Check convergence if abs(new_T - T) < 0.5: T = new_T break T = new_T # Convert threshold to integer T = int(round(T)) print("Final Threshold:", T) # Create binary image _, binary = cv2.threshold( gray, T, 255, cv2.THRESH_BINARY ) cv2.imshow("Original", image) cv2.imshow("Iterative Threshold", binary) cv2.waitKey(0) cv2.destroyAllWindows()

šŸ 11. Python Code Explanation

cv2.imread(): Reads the input image.
cv2.cvtColor(): Converts the image into grayscale.
G1: Contains pixels greater than the current threshold.
G2: Contains pixels less than or equal to the current threshold.
np.mean(): Calculates the average intensity of each group.
new_T: New threshold obtained from the two group means.
cv2.threshold(): Produces the final binary image.

šŸ“Š 12. Example Iteration Table

Iteration Old T μ₁ μ₂ New T
1 100 170 40 105
2 105 170 40 105
The algorithm stops because the threshold has become stable.

šŸ“Š 13. Global vs Iterative Thresholding

Feature Global Thresholding Iterative Thresholding
Threshold Usually manually selected Calculated iteratively
Process Single threshold operation Repeated refinement
Automatic Selection Not necessarily Yes, from image statistics
Computation Low Higher than one-pass thresholding
Result Binary segmentation Binary segmentation using converged T

šŸ“Š 14. Iterative Thresholding vs Otsu's Method

Feature Iterative Thresholding Otsu's Method
Basic Idea Repeatedly updates T using group means Selects T using a histogram-based class-separation criterion
Starting Value Usually requires an initial T Evaluates candidate thresholds
Iterations Yes Not iterative in the same sense
Statistics Two class means Class probabilities and variances
Automatic Yes Yes

šŸŒ 15. Applications

šŸ“„ Document Processing

Separating text and background in scanned documents.

šŸ”¢ OCR

Preparing characters for optical character recognition.

🧬 Medical Image Analysis

Separating regions of interest based on intensity.

šŸ­ Industrial Inspection

Separating objects or defects from backgrounds.

šŸ›°️ Remote Sensing

Intensity-based separation of image regions.

šŸ”¬ Scientific Images

Segmenting objects with distinguishable intensity ranges.

✅ 16. Advantages

1. Automatically estimates a threshold from image statistics.
2. Simple mathematical concept.
3. Does not require testing every possible threshold as its basic operation.
4. Easy to implement using NumPy and OpenCV.
5. Useful when foreground and background have reasonably distinct intensity distributions.

⚠️ 17. Limitations

1. The method depends on the initial threshold and image intensity distribution.
2. It may perform poorly when foreground and background intensities overlap strongly.
3. Uneven illumination can reduce segmentation quality.
4. Noise can influence the calculated group means.
5. It is fundamentally a two-class thresholding approach in its basic form.

⏱️ 18. Computational Consideration

If the image contains N pixels and the algorithm performs K iterations, a straightforward implementation requires approximately:

O(N × K)

In practice, the number of iterations is usually relatively small for many simple images, but it depends on the image distribution, initial threshold and stopping condition.

šŸ“ 19. Algorithm in Short

Choose
T₀
→
Create
G₁,G₂
→
Find
μ₁,μ₂
→
Tnew = (μ₁+μ₂)/2
→
Converged?
No → Repeat      Yes → Segment Image

šŸŽ“ 20. Important Examination Points

1. Iterative thresholding automatically estimates a threshold from image intensity statistics.
2. The image is divided into two groups using the current threshold.
3. The means of the two groups are calculated.
4. The new threshold is: Tnew = (μ₁ + μ₂) / 2.
5. The process continues until the threshold converges.
6. It is useful for image segmentation when foreground and background have reasonably different intensity distributions.

šŸ“Œ 21. Quick Revision Table

Concept Key Point
Initial Threshold Starting estimate of T.
G₁ Pixels greater than T.
G₂ Pixels less than or equal to T.
μ₁ Mean intensity of G₁.
μ₂ Mean intensity of G₂.
New Threshold Tnew = (μ₁ + μ₂) / 2.
Stopping Condition |Tnew − Told| < ε.
Final Result Thresholded / segmented image.

šŸŒ“ Thresholding in Digital Image Processing

šŸŒ“ Thresholding in Digital Image Processing

B.Sc. Computer Science Honours | Image Segmentation

šŸ“˜ 1. Introduction

Thresholding is one of the simplest and most important techniques used in Digital Image Processing for separating an object from its background.

The basic idea is to compare the intensity value of each pixel with a selected threshold value T.

Basic idea: Pixels are divided into different classes according to whether their intensity is below or above the threshold.
Grayscale
Image
→
Threshold
T
→
Pixel
Comparison
→
Binary
Image

⚙️ 2. Basic Principle

Let the grayscale intensity of a pixel be represented by f(x,y) and let T be the threshold.

g(x,y) = { 1, if f(x,y) ≥ T
    0, if f(x,y) < T }

Here:

  • f(x,y) = original grayscale pixel value
  • T = threshold value
  • g(x,y) = thresholded output
  • 1 = foreground/object
  • 0 = background
For an 8-bit grayscale image, pixel values normally range from 0 to 255.

šŸ”¢ 3. Numerical Example

Consider the following grayscale pixel values:

20, 60, 100, 140, 180, 220

Suppose the threshold is:

T = 128
Pixel Value Comparison Output
20 20 < 128 0
60 60 < 128 0
100 100 < 128 0
140 140 ≥ 128 1
180 180 ≥ 128 1
220 220 ≥ 128 1
Therefore, the output becomes: 0 0 0 1 1 1

šŸ“š 4. Types of Thresholding

1️⃣ Global Thresholding

Uses one threshold value for the entire image.

2️⃣ Local Thresholding

Uses threshold values that can vary across different regions of an image.

3️⃣ Adaptive Thresholding

Automatically calculates a threshold for local neighborhoods.

4️⃣ Otsu's Thresholding

Automatically selects a global threshold by maximizing the separation between two intensity classes.

šŸŒ 5. Global Thresholding

In global thresholding, one threshold value is applied throughout the complete image.

T = Constant

Example:

T = 128
If the object and background have clearly different intensity values, global thresholding can work effectively.

šŸ” 6. Local Thresholding

In local thresholding, different regions of an image can use different threshold values.

Image
→
Divide into
Regions
→
Calculate
Local T
→
Binary
Image

Local thresholding is useful when illumination is not uniform across the image.

🧠 7. Adaptive Thresholding

Adaptive thresholding calculates the threshold based on the local neighborhood of each pixel.

Two commonly used approaches are:

Mean Adaptive Thresholding

Threshold is calculated using the mean of neighboring pixels.

Gaussian Adaptive Thresholding

Uses a weighted average where nearby pixels receive greater importance.

šŸ“Š 8. Otsu's Thresholding

Otsu's method is an automatic threshold-selection technique commonly used for separating an image into two classes.

It searches for a threshold that gives strong separation between the foreground and background classes.

Otsu's method is particularly useful when the image histogram has two relatively distinct intensity groups.

Basic Idea

Step 1: Calculate the grayscale histogram.
Step 2: Consider possible threshold values.
Step 3: Divide pixels into two classes.
Step 4: Calculate within-class or between-class variance.
Step 5: Select the threshold providing the desired maximum separation criterion.

šŸ“ˆ 9. Histogram and Thresholding

A grayscale histogram represents the frequency of different intensity levels in an image.

Image
→
Histogram
→
Select T
→
Segmented
Image
When foreground and background have different intensity distributions, the histogram can help identify a suitable threshold.

⚫⚪ 10. Binary Image Formation

Thresholding commonly converts a grayscale image into a binary image.

Grayscale Image → Threshold → Binary Image

Black Pixel

Usually represented by intensity 0.

White Pixel

Usually represented by intensity 255.

🧪 11. Interactive Thresholding Demonstration


Set a pixel value and threshold, then click Apply Threshold.

🧩 12. Thresholding on an Image Matrix

Consider an 8×8 grayscale image represented by pixel intensities. Thresholding converts every value into either foreground or background.

Click New Matrix to generate a grayscale matrix.

šŸ 13. Beginner Python Code

The following example demonstrates simple global thresholding using OpenCV.

import cv2 # Read image image = cv2.imread("input.jpg") # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply threshold T = 128 ret, binary = cv2.threshold( gray, T, 255, cv2.THRESH_BINARY ) # Display images cv2.imshow("Original", image) cv2.imshow("Binary Image", binary) cv2.waitKey(0) cv2.destroyAllWindows()
Explanation:
cv2.threshold() compares the grayscale pixel values with the threshold value. Pixels satisfying the threshold condition are assigned the maximum value, here 255, while the others become 0.

šŸ 14. Beginner Python Code – Otsu Thresholding

import cv2 # Read image image = cv2.imread("input.jpg") # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Otsu thresholding ret, binary = cv2.threshold( gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU ) print("Selected Threshold:", ret) cv2.imshow("Original", image) cv2.imshow("Otsu Binary Image", binary) cv2.waitKey(0) cv2.destroyAllWindows()
Important: With Otsu's method, the threshold is selected automatically rather than manually specifying a fixed threshold such as 128.

šŸ 15. Beginner Python Code – Adaptive Thresholding

import cv2 # Read image image = cv2.imread("input.jpg") # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Adaptive threshold binary = cv2.adaptiveThreshold( gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2 ) cv2.imshow("Original", image) cv2.imshow("Adaptive Threshold", binary) cv2.waitKey(0) cv2.destroyAllWindows()

šŸ“Š 16. Comparison of Thresholding Methods

Method Threshold Suitable Situation
Global One fixed T Relatively uniform illumination
Local Region dependent Different image regions
Adaptive Calculated locally Uneven illumination
Otsu Automatically selected Images with two dominant intensity classes

🧠 17. Thresholding Algorithm

Step 1: Read the image.
Step 2: Convert the image into grayscale if necessary.
Step 3: Select or calculate a threshold value T.
Step 4: Compare every pixel with T.
Step 5: Assign the required output intensity.
Step 6: Obtain the binary or segmented image.

šŸŒ 18. Applications

šŸ“„ Document Processing

Separating text from paper backgrounds.

šŸ”¢ OCR

Preparing scanned documents for Optical Character Recognition.

🧬 Medical Images

Isolating regions of interest in some medical images.

šŸ­ Industrial Inspection

Detecting objects, defects or regions in manufactured products.

šŸ›°️ Satellite Images

Separating selected regions based on intensity information.

šŸŽ„ Object Segmentation

Separating foreground objects from suitable backgrounds.

✅ 19. Advantages

1. Simple and easy to implement.
2. Computationally inexpensive compared with many advanced segmentation techniques.
3. Produces a simple binary representation.
4. Useful as a preprocessing step for OCR and object analysis.
5. Automatic methods such as Otsu reduce the need to manually choose T.

⚠️ 20. Limitations

1. Global thresholding may fail when illumination is uneven.
2. Noise can affect the thresholded result.
3. A poor threshold can remove useful object information.
4. Some images contain overlapping foreground and background intensity distributions.
5. Adaptive methods can require additional computation.

šŸ” 21. Thresholding vs Edge Detection

Feature Thresholding Edge Detection
Main Purpose Separate regions/classes Find intensity boundaries
Basic Principle Compare pixel intensity with T Measure intensity changes
Output Usually binary regions Usually edge map
Common Methods Global, Otsu, Adaptive Sobel, Prewitt, Canny

šŸŽ“ 22. Important Examination Points

1. Thresholding is an image segmentation technique.
2. The threshold value is generally represented by T.
3. Global thresholding uses one threshold for the whole image.
4. Adaptive thresholding calculates thresholds locally.
5. Otsu's method automatically selects a threshold using a class-separation criterion.
6. Thresholding is widely used in OCR, document processing, object segmentation and image analysis.

šŸ“Œ 23. Quick Revision Table

Concept Key Point
Threshold Value used to separate intensity classes.
Binary Image Image containing two main intensity levels.
Global Threshold One threshold for the complete image.
Local Threshold Threshold depends on an image region.
Adaptive Threshold Threshold calculated from local neighborhoods.
Otsu Automatic threshold selection based on class separation.
Application Segmentation, OCR, inspection and image analysis.
``` This follows the same **Digital Image Processing educational layout** as your previous topics and is ready to paste directly into the **Blogger HTML editor**.