Stop 01 · Machine Learning FoundationsTopics · 4/10

Machine Learning Algorithms Explained: List, Types and When to Use Each

Part of the Machine Learning Roadmap

In short

Linear regression, random forests, k-means, XGBoost, neural networks: the list of algorithm names feels endless. The good news is that they fall into a few families, and once you know which family a problem needs, picking a sensible first algorithm takes minutes, not weeks.

A machine learning algorithm is the recipe that learns from data, like linear regression, decision trees, k-means or a neural network, and the trained result is the model. Algorithms fall into families by task (regression, classification, clustering) and suit different data sizes, shapes and needs for explanation.

The jaadu kneels beside an open wooden carpenter's toolbox in a small workshop, holding up a saw in one hand and a hammer in the other, with a chisel, a drill and a measuring tape laid out neatly on the floor in front of a half-built chair.

Think of it like this

The carpenter's toolbox

A carpenter making a chair does not ask 'which tool is the best?' He asks what the job is. A saw cuts, a chisel shapes joints, a drill makes holes, a tape measures. ML algorithms are the same: regression tools predict numbers, classifiers pick categories, clustering tools find groups. The wood you feed in is your data, and the finished chair is the trained model.

Watch it happen

The main families of ML algorithms

ML algorithms
Supervised (has labels)
Regression: linear, ridge
Classification: logistic, KNN, SVM
Ensembles: random forest, XGBoost
Unsupervised (no labels)
Clustering: k-means, DBSCAN
Dimensionality reduction: PCA
Neural networks (deep learning)

1/6Every algorithm is a recipe for turning data into a model. The first question is whether you have labels.

The big ideas

What you need to know

Start from the task

Predicting a number, picking a category and finding groups need different algorithm families. Name the task before the algorithm.

Algorithm vs model

The algorithm is the recipe, like 'decision tree'. The model is what you get after fitting it on your data, with its learned splits or weights.

Every choice is a trade-off

Simple algorithms are fast and easy to explain. Complex ones can be more accurate but need more data, tuning and compute.

Trees rule tabular data

For spreadsheets of customers, loans or orders, random forests and gradient boosting are usually the ones to beat.

How it works

Picking a first algorithm

  1. 1

    Name the target

    Is there a label? Is it a number or a category? No label means unsupervised.

  2. 2

    Build a baseline

    Start with something simple, like linear or logistic regression, to get a score to beat.

  3. 3

    Try a stronger family

    Fit a random forest or gradient boosting model and compare on the same test set.

  4. 4

    Weigh the trade-offs

    Pick the one that balances accuracy, speed and how easily you can explain it to others.

See it in code

Walk through the code

python
1from sklearn.datasets import load_iris2from sklearn.model_selection import train_test_split3from sklearn.linear_model import LogisticRegression4from sklearn.neighbors import KNeighborsClassifier5from sklearn.tree import DecisionTreeClassifier6from sklearn.cluster import KMeans7 8X, y = load_iris(return_X_y=True)9X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)10 11# Supervised: three algorithms, one API12for algo in [LogisticRegression(max_iter=1000), KNeighborsClassifier(), DecisionTreeClassifier(random_state=0)]:13    model = algo.fit(X_train, y_train)          # algorithm + data = model14    print(type(algo).__name__, model.score(X_test, y_test))15 16# Unsupervised: no y at all17kmeans = KMeans(n_clusters=3, n_init=10, random_state=0).fit(X)18print(kmeans.labels_[:10])

1/4Each import is a different algorithm from a different family: linear, nearest neighbours, trees and clustering.

Three classification algorithms and one clustering algorithm on the same flower measurements. scikit-learn gives them all the same fit and predict style.

Save yourself the pain

Common mistakes

Oops

Jumping straight to deep learning or XGBoost because it sounds advanced.

Do this instead

Start with a simple baseline. If a fancy algorithm only beats it slightly, the simple one may be the better product choice.

Oops

Memorising a long list of algorithms without knowing which task each solves.

Do this instead

Group them by family and use case. Interviewers ask when you would use an algorithm, not just what it is.

Oops

Comparing algorithms on different splits or on training data.

Do this instead

Compare every algorithm on the same held-out test set, or better, with the same cross-validation folds.

Your mission

Your algorithm cheat sheet

~25 min

Quick check

A bank wants to group its customers into segments but has no labels saying which segment anyone belongs to. Which algorithm fits?

Go deeper

  1. 1Make a one-page table of ten common algorithms with their type and one use case each, then revisit it as you reach Phases 7 to 12.
  2. 2Train LogisticRegression, DecisionTreeClassifier and RandomForestClassifier on scikit-learn's breast cancer dataset and compare their test accuracy.
  3. 3Read the scikit-learn 'Choosing the right estimator' flowchart and trace which path your own project would follow.

What is a machine learning algorithm?

A machine learning algorithm is a procedure that learns patterns from data. You give it examples, it adjusts internal numbers to fit those examples, and the result can then make predictions on new data. Linear regression, decision trees, k-means and neural networks are all ML algorithms.

There are dozens of ML algorithms, but they fall into a few families. The family depends on the task: predicting a number (regression), predicting a category (classification), finding groups without labels (clustering), simplifying many columns into a few (dimensionality reduction), or learning complex patterns in images, audio and text (neural networks). Learn the families first and the long list of names becomes much easier to remember.

ML model vs algorithm: what is the difference?

People often use the two words as if they mean the same thing, but they do not. The algorithm is the recipe. The model is what you get after running that recipe on your data.

For example, 'random forest' is an algorithm. When you call fit() on your customer data, it builds a specific set of trees with specific splits, and that trained object is your ML model. Two teams using the same algorithm on different data end up with different models. When people talk about machine learning models in production, they mean these trained objects, saved to a file and loaded by an app to make predictions.

AlgorithmModel
What it isA general method for learning from dataThe trained result of that method on one dataset
ExampleLogistic regressionA churn classifier with learned weights for 20 customer features
When it existsBefore you have any dataOnly after training
What you shipNothing on its ownThe saved model file, used to make predictions

Machine learning algorithms list: the master table

This table covers the machine learning algorithms you will meet most often, from simple baselines to the ones that win competitions. Use it as a quick reference before you go deeper into each one.

AlgorithmTypeTypical use caseStrengthsWeaknesses
Linear regressionSupervised, regressionPredicting price, sales or demandFast, easy to explain, a strong baselineAssumes a straight-line relationship; sensitive to outliers
Ridge, Lasso, Elastic NetSupervised, regressionRegression with many or correlated featuresReduces overfitting; Lasso can drop useless featuresStill linear; needs scaled features and a tuned penalty
Logistic regressionSupervised, classificationChurn, default risk, spam detectionGives probabilities, quick, explainable coefficientsMisses complex non-linear patterns unless you engineer features
K-nearest neighbors (KNN)Supervised, classification or regressionSimple recommendations, small datasetsNo training step, easy to understandSlow on large data; hurt by irrelevant or unscaled features
Naive BayesSupervised, classificationText classification, spam filtersVery fast, works with little data and many wordsAssumes features are independent, so probabilities can be off
Support vector machine (SVM)Supervised, classification or regressionMedium-sized data with clear margins, textHandles high dimensions; kernels capture curvesSlow on very large datasets; needs scaling and tuning
Decision treeSupervised, classification or regressionRules a business can read, quick baselinesEasy to visualise, handles mixed feature typesOverfits easily; small data changes alter the tree
Random forestSupervised, ensemble (bagging)General tabular problems, feature importanceAccurate with little tuning, resists overfittingLarger and slower than one tree; harder to explain
Gradient boosting (XGBoost, LightGBM, CatBoost)Supervised, ensemble (boosting)Churn, fraud, ranking, most tabular dataOften the most accurate choice on tablesMore hyperparameters; can overfit if not tuned
K-meansUnsupervised, clusteringCustomer segmentationSimple and fastYou must pick K; assumes round, similar-sized clusters
DBSCANUnsupervised, clusteringLocation data, clusters of odd shapes, noiseFinds any shape; marks outliers as noiseStruggles when clusters have very different densities
Hierarchical clusteringUnsupervised, clusteringSmall datasets where a tree of groups helpsNo need to fix K in advance; dendrogram viewSlow on large data
PCAUnsupervised, dimensionality reductionCompressing features, visualisationRemoves redundancy, speeds up later modelsNew components are hard to interpret; only linear
Isolation ForestUnsupervised, anomaly detectionFraud and fault detectionWorks well on many features, fastNeeds a guess of how rare anomalies are
Neural networks (MLP, CNN, RNN, Transformer)Supervised or self-supervised, deep learningImages, speech, text, very large datasetsLearns complex patterns and its own featuresNeeds lots of data and compute; hard to explain

Supervised learning algorithms: regression and classification

Supervised learning algorithms learn from rows where the answer is already known. They are the most used type of machine learning algorithms because most business data comes with historical outcomes.

Regression algorithms predict a continuous number. Linear regression fits a straight line (or flat plane) through the data and is the first thing to try. Polynomial regression bends that line by adding squared or interaction terms. Ridge, Lasso and Elastic Net add a penalty on large weights to stop the model memorising noise. Phase 7 of this roadmap covers all of these, along with regression metrics like MAE, RMSE and R squared.

Machine learning classification algorithms predict a category. Logistic regression is the standard baseline and outputs a probability between 0 and 1. K-nearest neighbors labels a new point by looking at the closest training points. Naive Bayes applies Bayes' theorem and is a classic for spam and text. Support vector machines find the boundary with the widest gap between classes, and kernels let them draw curved boundaries. Phase 8 covers these classifiers and the metrics that judge them, such as precision, recall, F1 and ROC-AUC.

Ensembles, unsupervised algorithms and neural networks

Ensemble methods combine many models into one stronger model. Bagging trains many decision trees on random samples of the data and averages them, which is how a random forest works. Boosting trains trees one after another, each fixing the mistakes of the previous ones, which is the idea behind gradient boosting, XGBoost, LightGBM and CatBoost. On structured, spreadsheet-style data, gradient boosting is very often the strongest choice. Phase 9 covers decision trees, random forests, boosting, stacking and feature importance.

Unsupervised algorithms work without labels. K-means, hierarchical clustering, DBSCAN and Gaussian mixture models find groups. PCA, t-SNE and UMAP reduce many columns to a few. Isolation Forest finds anomalies, and Apriori finds items that are often bought together. Phase 11 walks through each of these, ending with a customer segmentation project.

Neural networks are layers of simple units that each compute a weighted sum and pass it through an activation function. Stack many layers and you get deep learning. Convolutional neural networks (CNNs) suit images, and transformers now lead in text and many other areas. Most of the AI algorithms in the news today, from chatbots to image generators, are large neural networks. Phase 12 teaches how they learn with backpropagation in PyTorch, and Phase 13 applies them to computer vision and NLP.

How to choose a machine learning algorithm

There is no single best algorithm for every problem. Instead, follow a short checklist and let your validation scores decide.

  • Define the task. A number target means regression, a category means classification, and no target means clustering or another unsupervised method.
  • Look at the data type. Tables of rows and columns usually suit linear models and tree ensembles. Images, audio and free text usually suit neural networks.
  • Check the data size. With a few hundred rows, simple models and strong regularisation are safer. Deep learning normally needs far more examples.
  • Decide how much explanation you need. If a bank must justify every rejection, logistic regression or a shallow tree may beat a slightly more accurate black box.
  • Start with a baseline, then try a stronger family. Logistic or linear regression first, then random forest and gradient boosting, all compared with the same cross-validation.
  • Tune only the best one or two. Hyperparameter search on every algorithm wastes time. Phase 10 covers cross-validation, tuning with grid search and Optuna, and choosing between models fairly.

Compare 3 classifiers in scikit-learn

This snippet compares logistic regression, a decision tree and a random forest on scikit-learn's built-in breast cancer dataset using 5-fold cross-validation. The logistic regression sits inside a pipeline with a scaler, because it trains better on standardised features. Run it in Google Colab and see which one wins on your machine.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier

X, y = load_breast_cancer(return_X_y=True)

models = {
    "Logistic regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
    "Decision tree": DecisionTreeClassifier(max_depth=4, random_state=42),
    "Random forest": RandomForestClassifier(n_estimators=300, random_state=42),
}

for name, model in models.items():
    scores = cross_val_score(model, X, y, cv=5, scoring="accuracy")
    print(f"{name}: {scores.mean():.3f} (+/- {scores.std():.3f})")

Frequently asked questions

Supervised algorithms for regression and classification, unsupervised algorithms for clustering, dimensionality reduction and anomaly detection, ensemble methods that combine many models, and neural networks for deep learning. Reinforcement learning algorithms form a separate family for decision-making agents.

None is best for everything. On tabular data, gradient boosting and random forests are often the most accurate, while neural networks lead on images, audio and text. Always compare a simple baseline with a few stronger options using cross-validation.

An ML model is the trained output of an algorithm. After an algorithm like logistic regression learns its weights from your data, the resulting object, which you can save and use to make predictions, is the model.

Start with linear regression, logistic regression, k-nearest neighbors, decision trees, random forests and k-means. They cover regression, classification and clustering, and they teach the ideas that more advanced algorithms build on.

Not exactly. AI also includes search, planning and rule-based methods that do not learn from data. Machine learning algorithms are the part of AI that learns from examples, and they power most AI products today.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge