Key ML Algorithms

Let’s learn about some foundational ML algorithms. We’ll focus on a conceptual understanding of each one.

For some of the algorithms we’ll talk about here (in particular, linear regression, K-Means clustering, and decision trees), you can refer to the previous lesson to see Python examples of the scikit-learn implementations.

This Lesson Will Cover
  • πŸ“ˆ Linear Regression
  • πŸ“Š Logistic Regression
  • πŸ” KMeans Clustering
  • 🌳 Decision Trees
  • πŸš€ Boosted Trees

Linear Regression

  • Objective: Linear Regression aims to model the relationship between input variables and a continuous output variable by fitting a straight line (or hyperplane for higher dimensions).
  • Key Idea: The algorithm assumes a linear relationship, meaning changes in the input variables lead to proportional changes in the output.
  • Application: Often used in scenarios such as predicting prices, demand forecasting, or understanding trends in data.

Model

The relationship between input features XX and the target yy is modeled as:

y=w1x1+w2x2+β‹―+wnxn+bor compactlyy=wTx+b y = w_1x_1 + w_2x_2 + \dots + w_nx_n + b \quad \text{or compactly} \quad y = \mathbf{w}^T \mathbf{x} + b

Where:

  • yy: Predicted output
  • x\mathbf{x}: Input feature vector
  • w\mathbf{w}: Coefficients (weights) for each feature
  • bb: Intercept (bias term)

Loss Function
Linear Regression minimizes the error between predicted values y^\hat{y} and actual values yy using the MSE (Mean Squared Error):

MSE=1Nβˆ‘i=1N(yiβˆ’y^i)2 \text{MSE} = \frac{1}{N} \sum_{i=1}^{N} (y_i - \hat{y}_i)^2

Where:

  • NN: Number of data points
  • yiy_i: Actual value
  • y^i\hat{y}_i: Predicted value

Goal
Find the optimal w\mathbf{w} and bb that minimize the MSE using techniques like gradient descent.

Assumptions:

  • The residuals (differences between actual and predicted values) are normally distributed and independent.
  • The relationship between input and output is linear.

Points to Note:

  • Simple yet powerful: Linear Regression provides a baseline for regression tasks and helps understand relationships between variables.
  • Interpretability: Coefficients w\mathbf{w} indicate the importance and impact of each feature on the target variable.
  • Extensibility: Can be extended to handle non-linear relationships by incorporating polynomial features (e.g., x2x^2, x3x^3).
Linear Regression Fit On Synthetic Data
A linear model (green) fit to synthetic data points (red).

Logistic Regression

  • Objective: Logistic Regression predicts binary outcomes by estimating the probability that an input belongs to a particular class.
  • Key Idea: Transforms linear regression outputs using a sigmoid function to produce probabilities between 0 and 1.
  • Application: Commonly used in binary classification tasks like spam detection, disease diagnosis, or customer churn prediction.

Python Example: Classifying Emails as Spam

This example shows logistic regression predicting if an email is spam.

from sklearn.linear_model import LogisticRegression
import numpy as np

# Training data: [email_length, contains_urgent, contains_money]
X = np.array([
    [100, 0, 0],  # Normal email
    [850, 1, 1],  # Spam email
    [300, 0, 0],  # Normal email
    [600, 1, 1],  # Spam email
    [400, 0, 0],  # Normal email
])
y = np.array([0, 1, 0, 1, 0]) # Spam (1) or Not Spam (0)

# Train the model
model = LogisticRegression()
model.fit(X, y)

# Predict spam for a new email with feature values [500, 0, 0]
prediction = model.predict([[500, 0, 0]])
print("Spam" if prediction[0] == 1 else "Not Spam")

# Output:
# Not Spam

Model

The probability of an input belonging to class 1 is modeled as:

P(y=1∣x)=11+eβˆ’(wTx+b)=Οƒ(wTx+b) P(y=1|\mathbf{x}) = \frac{1}{1 + e^{-(\mathbf{w}^T \mathbf{x} + b)}} = \sigma(\mathbf{w}^T \mathbf{x} + b)

Where:

  • Οƒ(z)=11+eβˆ’z\sigma(z) = \frac{1}{1 + e^{-z}}: Sigmoid function that maps any real number to a value between 0 and 1
  • x\mathbf{x}: Input feature vector
  • w\mathbf{w}: Model weights
  • bb: Bias term
Sigmoid Curve Illustrating Logistic Regression Probabilities
The S-shaped purple sigmoid converts raw model scores into probabilities; the dashed yellow threshold at 0.5 shows where predictions flip from 'not-spam' to 'spam.'

Loss Function
Logistic Regression minimizes the Binary Cross-Entropy Loss:

BCE=βˆ’1Nβˆ‘i=1N[yilog⁑(y^i)+(1βˆ’yi)log⁑(1βˆ’y^i)] \text{BCE} = -\frac{1}{N} \sum_{i=1}^{N} [y_i \log(\hat{y}_i) + (1-y_i) \log(1-\hat{y}_i)]

Where:

  • NN: Number of data points
  • yiy_i: Actual class (0 or 1)
  • y^i\hat{y}_i: Predicted probability

Goal
Find the optimal w\mathbf{w} and bb that minimize the Binary Cross-Entropy Loss using optimization techniques like gradient descent.

Assumptions:

  • Features are independent
  • Linear relationship between features and log-odds of the outcome
  • No multicollinearity among features

Points to Note:

  • Probabilistic Output: Provides probability estimates for class membership
  • Interpretability: Coefficients can be interpreted as log-odds, showing feature importance
  • Efficiency: Computationally efficient and works well for linearly separable data

KMeans Clustering

  • Objective: KMeans Clustering groups similar data points into K distinct clusters by minimizing the distance between points and their assigned cluster centers.
  • Key Idea: Iteratively assigns points to nearest cluster center and updates centers based on mean of assigned points.
  • Application: Used for customer segmentation, image compression, anomaly detection, and pattern recognition.

Model

Loss Function

The algorithm aims to minimize the WCSS (Within-Cluster Sum of Squares):

WCSS=βˆ‘k=1Kβˆ‘i=1Nkβˆ₯xiβˆ’ΞΌkβˆ₯2 \text{WCSS} = \sum_{k=1}^{K} \sum_{i=1}^{N_k} \|x_i - \mu_k\|^2

Where:

  • NkN_k: Number of points in cluster k
  • xix_i: Data point i
  • ΞΌk\mu_k: Center of cluster k

Algorithm Steps:

  1. Initialize K cluster centers randomly
  2. Repeat until convergence:
    • Assign each point to nearest cluster center
    • Update cluster centers as mean of assigned points

Goal
Find optimal cluster assignments and centroids that minimize the WCSS through iterative optimization.

Assumptions:

  • Clusters are spherical and equally sized
  • Variance of features is similar across dimensions
  • Data points can be meaningfully assigned to exactly one cluster

Points to Note:

  • Simplicity: Easy to understand and implement
  • Scalability: Efficient for large datasets
  • Limitations: Requires pre-specified K value and sensitive to initial centroid placement
  • Convergence: Guaranteed to converge but may find local optima
K-Means Clustering With Three Clusters
Centroids of a K-Means model fit to a random three-cluster dataset.

Decision Tree

  • Objective: Decision Trees create a tree-like model of decisions by recursively splitting data based on feature values to make predictions.
  • Key Idea: Breaks down complex decisions into simpler choices, creating a flowchart-like structure where each node represents a decision based on a feature.
  • Application: Used in classification and regression tasks, recommendation systems, and decision support systems.

Model

The tree structure consists of nodes that split the data based on feature values to minimize impurity:

Split Quality=Parent Node Impurityβˆ’βˆ‘j=1mNjNChild Node Impurityj \text{Split Quality} = \text{Parent Node Impurity} - \sum_{j=1}^m \frac{N_j}{N} \text{Child Node Impurity}_j

Where:

  • NN: Total number of samples at parent node
  • NjN_j: Number of samples at child node j
  • mm: Number of child nodes

Loss Function
For classification, commonly uses Gini Impurity or Entropy:

Gini=1βˆ’βˆ‘i=1c(pi)2 \text{Gini} = 1 - \sum_{i=1}^{c} (p_i)^2
Entropy=βˆ’βˆ‘i=1cpilog⁑2(pi) \text{Entropy} = -\sum_{i=1}^{c} p_i \log_2(p_i)

Where:

  • cc: Number of classes
  • pip_i: Proportion of class i in the node

Goal
Find optimal splits that maximize information gain or minimize impurity at each node to create a tree structure that accurately predicts target values.

Assumptions:

  • Features are independent
  • The underlying pattern in data can be captured by hierarchical decisions
  • The data contains meaningful patterns that can be learned through recursive partitioning

Points to Note:

  • Interpretability: Easy to understand and visualize decision-making process
  • Flexibility: Can handle both numerical and categorical data
  • No Feature Scaling: Does not require feature normalization
  • Limitations: Can overfit without proper pruning and may create complex trees
Decision Boundary Of A Shallow Decision Tree
Background color blocks (cyan vs. pink) display the tree's predicted class for every coordinate, and the training points illustrate how hierarchical splits carve the space.

Boosted Decision Tree Ensemble

  • Objective: Boosted Trees combine multiple decision trees sequentially, where each tree learns to correct errors made by previous trees.
  • Key Idea: Builds trees iteratively, with each new tree focusing on the samples that were misclassified by previous trees.
  • Application: Used in various prediction tasks, ranking systems, and competitions due to their high accuracy and robustness.

Python Example: Predicting Fraud with XGBoost

This example shows a boosted tree predicting if a transaction is fraud.

from xgboost import XGBClassifier
import numpy as np

# Training data: [transaction amount, number of transactions, time since last transaction]
X = np.array([[100, 10, 24], [200, 15, 48], [50, 5, 1], [300, 20, 72]])
y = np.array([0, 0, 1, 1])  # Fraudulent (1) or Legitimate (0)

# Train the model
model = XGBClassifier(use_label_encoder=False, eval_metric="logloss")
model.fit(X, y)

# Predict fraud for a transaction with amount=150, transactions=12, time=36
prediction = model.predict([[150, 12, 36]])
print("Fraudulent" if prediction[0] == 1 else "Legitimate")

# Output:
# Legitimate

Model

The ensemble prediction is formed by summing predictions from individual trees:

F(x)=βˆ‘m=1MΞ³mhm(x) F(x) = \sum_{m=1}^{M} \gamma_m h_m(x)

Where:

  • MM: Number of trees
  • hm(x)h_m(x): Individual decision tree
  • Ξ³m\gamma_m: Weight of tree m
  • xx: Input features

Loss Function
Boosted Trees minimize a differentiable loss function LL with gradient descent:

L(y,F(x))=βˆ‘i=1Nl(yi,F(xi)) L(y, F(x)) = \sum_{i=1}^{N} l(y_i, F(x_i))

Where:

  • NN: Number of samples
  • yiy_i: Actual value
  • F(xi)F(x_i): Predicted value
  • ll: Base loss function (e.g., squared error, log loss)

Goal
Iteratively build trees that minimize the residual error of previous trees through gradient descent optimization.

Assumptions:

  • Base learners (individual trees) are weak but better than random guessing
  • Training data contains meaningful patterns that can be learned incrementally
  • Loss function is differentiable

Points to Note:

  • High Performance: Generally provides better accuracy than single decision trees
  • Robustness: Less prone to overfitting compared to single deep trees
  • Feature Importance: Can provide reliable feature importance scores
  • Computational Cost: More computationally intensive than single trees
  • Hyperparameters: Requires careful tuning of learning rate and number of trees
Gradient Boosting Learning Curve Log-Loss
The loss of a gradient-boosted classifier as a function of the number of boosted trees in the ensemble (i.e., each point along the the x-axis represents a step in the algorithm, as subsequent trees are added). The downward-sloping pink line shows how each additional tree reduces ensemble error, illustrating the boosting principle of correcting predecessors' mistakes.

Conclusion

We tossed around a lot of algorithms and math equations here, but we didn’t take any time to explore them. That’s because (a) we have so much more ground to cover, and (b) we are more focused on practical applications of ML in this course.

If found this section of the course interesting, and you want to dig more into ML Algorithms, then I encourage you to dig deeper[1].

Key Takeaways

πŸ“Š Core Algorithms: Linear Regression predicts continuous values, Logistic Regression handles classification, KMeans finds data clusters, and Trees make flowchart-like predictions.

πŸ” Model Selection: Each algorithm has unique strengthsβ€”consider accuracy, interpretability, and computational needs when choosing.

πŸ“‘ Data Quality: Success depends on proper data preparation and understanding each algorithm’s assumptions.

βš™οΈ Implementation: Modern frameworks like scikit-learn and XGBoost provide optimized versions of these algorithms.

Next: Data Preparation

These algorithms form the foundation of many machine learning applications, but their success heavily depends on proper data preparation.

So in our next section, we’ll talk about how to prepare data for ML, including cleaning, normalization, and feature engineering.

Footnotes


  1. For a deep dive on ML algos that’s highly accessible and practical as well, I’d recommend the book Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow. Make sure you pick up the second edition. β†©οΈŽ

Comments (0)

No comments yet.