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 and the target is modeled as:
Where:
- : Predicted output
- : Input feature vector
- : Coefficients (weights) for each feature
- : Intercept (bias term)
Loss Function
Linear Regression minimizes the error between predicted values and actual values using the MSE (Mean Squared Error):
Where:
- : Number of data points
- : Actual value
- : Predicted value
Goal
Find the optimal and 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 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., , ).
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:
Where:
- : Sigmoid function that maps any real number to a value between 0 and 1
- : Input feature vector
- : Model weights
- : Bias term
Loss Function
Logistic Regression minimizes the Binary Cross-Entropy Loss:
Where:
- : Number of data points
- : Actual class (0 or 1)
- : Predicted probability
Goal
Find the optimal and 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):
Where:
- : Number of points in cluster k
- : Data point i
- : Center of cluster k
Algorithm Steps:
- Initialize K cluster centers randomly
- 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
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:
Where:
- : Total number of samples at parent node
- : Number of samples at child node j
- : Number of child nodes
Loss Function
For classification, commonly uses Gini Impurity or Entropy:
Where:
- : Number of classes
- : 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
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:
Where:
- : Number of trees
- : Individual decision tree
- : Weight of tree m
- : Input features
Loss Function
Boosted Trees minimize a differentiable loss function with gradient descent:
Where:
- : Number of samples
- : Actual value
- : Predicted value
- : 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
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
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.