Skip to content
All posts
Machine Learning8 April 2026·15 min read

Machine Learning Fundamentals: From Linear Regression to Random Forests

A comprehensive exploration of machine learning concepts including regression, classification, decision trees, and data preprocessing techniques.

Linear Regression

Evaluation Metrics

  • Mean Squared Error (MSE)
  • Mean Absolute Error (MAE)
  • Root Mean Squared Error (RMSE)
  • R² → How much variance in Y does the model explain

RSS/TSS

RSS/TSS

print(df.corr()) = checking the correlation

Multiple Linear Regression

  • It gets its adjective "Multiple"
  • Negative association = negatively affect the price

Polynomial Regression

  • Curved line
  • y = a + bx + bx² + bx³ + ….. extra features for better quality of data
  • Understand simple linear regression

Simple Logistic Regression

  • Yes/no is classification
  • S shaped curve
  • Sigmoid function
  • y = 1/1
  • Evaluation Metrics
  • Confusion Matrix
  • True positive = Class is true - algorithm is true
  • False positive = Class is false

Confusion Matrix

  • True Positive Count = 10 10:3
  • 1:6
  • Accuracy/Precision and Recall
  • Accuracy = TP + TN / TP + TN + FP + FN
  • Precision = TP / TP + FP
  • Recall = TP / TP + FN
  • Reproducible - make sure this can be used for everyone
  • Generalise as much as you can
  • Virtual environment
  • Install package into only this environment
  • Based on the project the versioning changes
  • .. is going into main directory
  • Logic regression → function comes under Scikit-learn

Questions to Ask

  • Confusion Matrix
  • The terms we are using such as log_reg, I understand it's logistical regression but is this the standard terms used across the world
  • I don't understand this bit of code which give the output
  • {df["Expensive"].mean():.1%} what does this define?

---

Week 5 COMP 648 Session 9

Multicollinearity

  • 2 or more features = strong relationships
  • Reducing the same feature that can correlate to make the ML better
  • Training, validation and test sets
  • Training = 80 | Validation = 10 | Test = 10
  • Removing the highly correlated so that it doesn't affect the modeling

K-Nearest Neighbour

  • Euclidean Distance
  • k = Number of neighbours (which points are closest to each other)
  • Nearest neighbour = predict the value of the datapoint added
  • Non-parametric
  • Euclidean Distance = Extended to any dimension
  • Lazy learner = Training - there is no any immediate learning
  • Small k = May overfit → No predicting to it - it's okay good for my dataset
  • Larger k = It make stable predictions by averaging lot of examples maybe underfit
  • Overfit and underfit

Hyperparameters = we have to set as users (eg: Polynomial Regression)

  • We turn with different K = we have to define it
  • Logistic Regression = default also a hyperparameters
  • Try with training set vs validation set and see if they are closely

---

Week 5 COMP 648 Session 10

Decision Trees - Easy to Interpret | can be used for classification and Regression

  • Root node
  • Branch
  • Internal Node
  • Leaf Node
  • Decision Trees is known as Greedy Learner

Gini Impurity = Scikit-learn

  • Higher Gini = Less pure the nodes
  • Gini = Perfectly pure node.
  • Weighted Gini = Average gini impurity

If tree grows then it's overfitting

  • Decision tree can have a max depth to split
  • Only focus on the features = Easy visualisation, interpreted
  • No Feature normalisation or scaling needed
  • Darker the colour is purity is HIGH

Random Forest = Has multiple Decision Trees = Separate training dataset

  • Bootstrap Sampling
  • Replacement dataset = subset 1
  • Bootstrap sample = only n number of features work
  • Design Choices
  • How many trees should the forest have
  • Usually it's 100 trees and increase if it's performance is still improving
  • M = number of features
  • Less interpretable
  • sklearn.ensemble meaning
  • Ensemble means aggregated predictions from several models - voting, averaging, bagging, boosting
  • Use n-Estimator to understand which number of trees would work the best

---

Week 5 COMP 648 Tutorial

Binary = 2

Multiple class > 2

Why train and test data, splitting it for training and other part for testing

What is random state = 42 is the default

Importance features

Why validation Dataset = Hyper parameters

KNN required scaling data

  • Scaler is required in train and test dataset

---

Week 6 COMP 648 Session 11

Real world data is amplify, might be garbage in or garbage out

  • ML is data prep is important

Steps

#### First Pass = EDA

  • Content columns
  • Missing Value = Why data is missing
  • Mean or mode simple one = Works well for smaller sample
  • Details might be missing in there
  • More mean would help to get an output for it for NaN
  • Creating a Biased
  • KNN or Imputation etc for adding it
  • K nearest neighbours
  • If multiple missing data then go one at a time to fill it up
  • Group of value that controls it then that could help to resource the information
  • If there is more than 20% data is missing then don't use it
  • Unknown classes as a category is better
  • Outlier
  • Decide to Remove, Keep or Transform etc Normalize

#### Data Type Conversion

  • Encoding -
  • One-hot = Categorical to Binary
  • Ordinal/Label = categories into Integers (label Encoding) - has distance problem
  • Advanced Encoding - finding Average area
  • Binary coding with Column
  • Frequency in Coding = number of times they repeat

#### Data Transformation

  • Improve model performance sooner
  • Stabilise variance
  • Scaling = if dataset is 0 - 10,000 to 0 to 1 Ratio

x = x - xmin / xmax - xmin this keeps the value 0 to 1

  • Image data normalise
  • Neural net

#### Standardisation - zscore scaling

---

Week 6 COMP 648 Session 12

Read

#### Data Preprocessing Guide

Data preprocessing transforms raw data into model-ready format, covering imputation, outlier detection, encoding, scaling, skewness correction, dimensionality reduction, and imbalance handling. This compact synthesis draws from scikit-learn docs and referenced guides.

#### Missing Value Imputation

Use scikit-learn's SimpleImputer for basic strategies like mean/median/mode: SimpleImputer(strategy='mean').fit_transform(X) fills NaNs with column means. For multivariate cases, IterativeImputer models features as functions of others (e.g., rounds [,[6,np.nan]] to [,]). Combine with pipelines for robust pipelines.

#### Outlier Detection

Scikit-learn offers unsupervised methods: IsolationForest(contamination=0.05) isolates anomalies via tree ensembles; LocalOutlierFactor(n_neighbors=20) computes local densities; OneClassSVM(nu=0.05) fits hyperplanes; EllipticEnvelope assumes Gaussian data. Visualize outliers in red on scatter plots (e.g., Iris sepal features).

#### Categorical Encoding

One-hot encoding via OneHotEncoder creates binary columns for nominal data; label encoding for ordinal. Target encoding averages targets per category, reducing dimensionality but risking leakage—use cross-validation [cite from letsdatascience]. Avoid on high-cardinality features without grouping.

#### Feature Scaling

Standardization (z-score: (x - mean)/std) suits normal-like data, robust to outliers (StandardScaler) [web: from letsdatascience]. Normalization (min-max: (x - min)/(max - min)) bounds, ideal for gradients (MinMaxScaler). Choose by model: SVMs prefer standardization; neural nets tolerate both [web: from letsdatascience].

#### Skewness Correction

Apply log (np.log1p), square root, or Box-Cox/Yeo-Johnson (PowerTransformer) to normalize right-skewed features (e.g., income) [web: from machinelearningmastery skewness]. Check post-transform skewness <0.5; combine with scaling.

#### Dimensionality Reduction

PCA (PCA(n_components=0.95)) projects via SVD, retaining variance (centers but doesn't scale input). Use for visualization or speed-up; explained_variance_ratio_ shows component importance.

#### Imbalanced Classes with SMOTE

SMOTE oversamples minority class by interpolating synthetics between neighbors (imblearn.over_sampling.SMOTE()), avoiding duplicates. Apply post-split: fit on train, transform train/test. Risks overfitting/noise; pair with undersampling.

TechniqueKey ToolWhen to UsePitfalls
ImputationSimpleImputerUnivariate gapsAssumes MCAR
OutliersIsolationForestAny dataTuning contamination
EncodingOneHotEncoderNominal catsCurse of dimensionality
ScalingStandardScalerLinear modelsSensitive to outliers
Skew FixPowerTransformerNon-normalInterpretability loss
PCAPCAHigh dimsLinearity only
SMOTESMOTERare eventsSynthetic artifacts

Pipeline all via ColumnTransformer for production. Test impacts on CV scores.

---

Week 6 COMP 648 Session 12 (continued)

Feature Engineering

  • Features = short cutting the techniques
  • Good features to simpler, stronger, faster-to-train models
  • Poor features leads to overfitting, noise and shit

#### Methods

##### Filter methods

  • Correlation Matrix
  • Chi-square test
  • Chi‑square goodness‑of‑fit test: checks whether one categorical variable's observed distribution matches an expected distribution (e.g., "Are births equally spread across months?
  • ANOVA

ANOVA compares two types of variability:

  • Variation between groups (how different the group averages are from each other).
  • Variation within groups (how spread out the data points are inside each group).

##### Wrapper methods

  • Forward selection
  • Backward elimination

##### Embedded methods

  • Ridge vs Lasso

#### Correlational Matrix

#### Domain Knowledge = Try to simplify this dataset instead of two column, make it one

#### Aggregation =

#### Binning = Make the easier for the model to learn outliners

#### Data leakage = info from outside the data come into the dataset

For evaluation

  • Train models on original features set and also enhanced and feature set
  • Compare

Dimensionality Reduction

  • Reducing number of features
  • While preserving information

#### Methods

  • Feature selection
  • Feature extraction

#### PCA

  • Principle Component analysis

Imbalanced data

  • Model contains biases

#### Methods

  • Oversampling
  • Undersampling
  • Stratified splitting
  • SMOTE = handle imbalance dataset in classification | Synthetic data

#### Code

  • Recursive Feature Elimination
  • Regularisation (Lasso) = ML technique to identify which phase to ignore
  • Regulation (L2 Ridge)

#### Log Transformation

  • Normal distribution
  • qcut = quartile cut
  • cutting Lot area into smaller bins is problem
  • PCA
  • take a variable, find the most range, x and y 1 and 2 range

Add this to the learnings please

Keep exploring

Subscribe to new posts

Get notified when I publish new learnings. No spam, unsubscribe anytime.