Choosing an ML Algorithm: A Comparative Guide

How to pick between linear models, trees, ensembles, SVMs, k-NN, naive Bayes, k-means and PCA, and how to compare candidates fairly on your own data.

AI & ML

This series has covered nine algorithms, one at a time. Each article showed where its algorithm shines. The question you face on a real project is the opposite one: you have a dataset and a goal, and you need to decide which of those nine to try first, which to try second, and when to stop.

No algorithm wins everywhere. That is not a platitude; it is the reason the choice depends on your data and your constraints rather than on a ranking. The good news is that the decision is narrower than it looks. The problem type rules out most options, a few properties of the data rule out more, and a short, fair comparison settles the rest.

This article pulls the series together. It starts with the questions that narrow the field, summarizes how the algorithms differ, then runs them side by side on the same data so you can see what a fair comparison looks like and what it tells you. If you skipped the earlier articles, key concepts and terminologies in ML covers the vocabulary used here.

Start with the problem, not the algorithm

The first cut comes from what you are trying to predict, if anything.

  • You have a label and it is a number (monthly cost, latency, demand). That is regression: linear regression, decision trees, random forests, k-NN and SVMs all have regression versions.
  • You have a label and it is a category (spam or not, churn or stay, which of five failure types). That is classification: logistic regression, decision trees, random forests, SVMs, k-NN and naive Bayes.
  • You have no label and want to find structure. Grouping similar rows is clustering, where k-means is the usual starting point. Compressing many correlated columns into a few is dimensionality reduction, where PCA is the standard tool.

The supervised vs. unsupervised learning article goes deeper on that split. Once you know the task, a few practical questions do most of the remaining work.

flowchart TD
    A["Do you have a label?"] -->|No| U["Find groups or compress?"]
    U -->|Groups| KM["k-means"]
    U -->|Compress| PCA["PCA"]
    A -->|Yes| I["Must a person read the model?"]
    I -->|Yes| LIN["Linear or logistic regression, shallow tree"]
    I -->|No| S["Mostly text or word counts?"]
    S -->|Yes| NB["Naive Bayes, then logistic regression"]
    S -->|No| N["Over about 100k rows?"]
    N -->|Yes| GB["Gradient boosting, random forest"]
    N -->|No| ALL["Compare: linear, forest, boosting, SVM, k-NN"]

Treat the chart as a way to pick a shortlist, not a final answer. A linear model is worth including in nearly every comparison, even when the chart points elsewhere, because it is cheap and tells you how much the more complex models are actually adding.

The questions that narrow the field

How much data do you have?

With a few hundred rows, simple models with strong assumptions tend to do well: logistic regression, naive Bayes, a shallow tree. Flexible models have room to memorize the training set, and there is not enough data to stop them.

With tens of thousands of rows or more, flexible models have room to work. Tree ensembles usually pull ahead on tabular data here. Kernel SVMs, on the other hand, start to struggle: training time grows somewhere between quadratically and cubically with the number of rows, so a model that trains in seconds on 5,000 rows can take hours on 500,000.

How many features, and what kind?

Many features relative to rows (thousands of word counts per document, for example) favor linear models and naive Bayes, which handle high dimensions well. k-NN degrades as dimensions grow, because distances between points become similar and “nearest” stops meaning much. Reducing dimensions with PCA first can help k-NN, as the PCA article showed.

Feature type matters too. Trees and forests accept a mix of scales and don’t care about units. Distance- and margin-based models (k-NN, SVM, k-means) need features on comparable scales, and so does regularized logistic regression. Text counts suit multinomial naive Bayes.

Is the relationship roughly linear?

If the target moves more or less in proportion to each feature, a linear model will be hard to beat, and it will be easier to explain. If there are thresholds and interactions (“high CPU matters only when memory is also high”), trees and ensembles find them on their own, and kernel SVMs and k-NN can follow curved boundaries. You rarely know this up front, which is one reason to compare.

Does a person need to understand the model?

A credit decision, a medical triage rule or an alert that operators must trust often needs a model whose reasoning you can show. Linear and logistic regression give a coefficient per feature. A shallow decision tree gives rules you can print. A random forest of 300 trees or an RBF SVM does not, and while post-hoc explanation tools exist, they explain the model approximately rather than exactly.

What are the costs at prediction time?

Some models are cheap to train and expensive to use. k-NN does almost no work at training time, but it stores the whole training set and searches it for every prediction. A random forest with hundreds of deep trees can be large on disk. A logistic regression model is a list of numbers and predicts in microseconds. If the model runs in a request path with a latency budget, check this early.

Your model must answer within a few milliseconds and the training set has 50 million rows. Which algorithm is the weakest fit for that constraint?

  • Logistic regression
  • k-nearest neighbors
  • A shallow decision tree

Correct! k-NN keeps every training row and searches them at prediction time, so its prediction cost grows with the training set.

The algorithms side by side

The table below summarizes the series. “Needs scaling” means the results change when features are on different scales, so you should standardize them first.

AlgorithmTasksInterpretableNeeds scalingHandles nonlinearityMain weakness
Linear regressionRegressionYes, coefficientsWith regularizationNo, unless you add featuresMisses curves and interactions
Logistic regressionClassificationYes, coefficientsYes, with regularizationNo, unless you add featuresSame as linear
Decision treeBothYes, if shallowNoYesOverfits when deep, unstable
Random forestBothPartly, feature importanceNoYesLarger, slower to predict
Support vector machineBothLinear kernel onlyYesYes, with kernelsSlow on large row counts
k-nearest neighborsBothPer prediction, by neighborsYesYesSlow predictions, weak in high dimensions
Naive BayesClassificationYes, per-feature probabilitiesNoLimitedIndependence assumption, poor probabilities
k-meansClusteringYes, centroidsYesNo, assumes round clustersMust choose k, sensitive to outliers
PCADimensionality reductionPartly, loadingsYesNo, linear onlyKeeps variance, not relevance

One algorithm missing from the series deserves a mention: gradient-boosted trees (XGBoost, LightGBM, and scikit-learn’s HistGradientBoostingClassifier and HistGradientBoostingRegressor). Like a random forest, it combines many trees, but it builds them one after another, each correcting the errors of the ones before. On medium and large tabular datasets it is often the most accurate option out of the box, and it handles missing values natively. It belongs on most shortlists, which is why it appears in the comparison below.

Matching common problems to a shortlist

ProblemStart withThen try
Predict monthly cloud spend from usageLinear regressionGradient boosting, random forest
Flag spam or classify support tickets by textNaive BayesLogistic regression on TF-IDF features
Predict customer churn from account dataLogistic regressionGradient boosting, random forest
Approve or decline with an explanation requiredLogistic regression, shallow treeStop there if accuracy is acceptable
Recommend items similar to one a user viewedk-NN on embeddingsApproximate nearest neighbor search at scale
Group VMs by usage pattern for right-sizingk-means on scaled metricsPCA first if there are many correlated metrics
Small dataset with a curved class boundarySVM with RBF kernelk-NN, random forest

Comparing candidates fairly

A shortlist is a hypothesis. The comparison is the test, and it only means something if every candidate gets the same treatment. Four rules cover most of it:

  1. Use the same splits for every model. Fix the cross-validation folds with a seed so differences come from the models, not from which rows landed in which fold.
  2. Put preprocessing inside the pipeline. If you fit a scaler on the whole dataset before splitting, information from the test folds leaks into training. A scikit-learn Pipeline refits the scaler inside each fold.
  3. Include a baseline. A model that always predicts the majority class, or the mean, tells you what “no skill” looks like. On imbalanced data it can score a surprisingly high accuracy.
  4. Look at the spread, not just the mean. If two models differ by less than the variation across folds, you have not shown that one is better.

The model training and evaluation article covers cross-validation and metrics in more detail.

flowchart LR
    D["Dataset"] --> H["Hold out a final test set"]
    H --> CV["Fixed 5-fold CV on the rest"]
    CV --> P["Same folds for each pipeline"]
    P --> M["Scaler + model, fit per fold"]
    M --> R["Mean and spread of the metric"]
    R --> C["Pick a model, tune it"]
    C --> T["Score once on the held-out test set"]

A worked comparison

The script below compares seven classifiers and a baseline on the breast cancer dataset that ships with scikit-learn: 569 rows, 30 numeric features, and a binary label (malignant or benign), with about 63 percent of rows in the larger class. Models that need scaled features get a StandardScaler in their pipeline. Every model sees the same five folds.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB

X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)

models = {
    "baseline (majority)": DummyClassifier(strategy="most_frequent"),
    "logistic regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
    "decision tree": DecisionTreeClassifier(max_depth=4, random_state=0),
    "random forest": RandomForestClassifier(n_estimators=300, random_state=0),
    "gradient boosting": HistGradientBoostingClassifier(random_state=0),
    "SVM (RBF)": make_pipeline(StandardScaler(), SVC()),
    "k-NN (k=5)": make_pipeline(StandardScaler(), KNeighborsClassifier()),
    "naive Bayes": GaussianNB(),
}

print(f"{'model':<22}{'accuracy':>10}{'std':>7}{'fit s':>8}")
for name, model in models.items():
    r = cross_validate(model, X, y, cv=cv, scoring="accuracy")
    print(f"{name:<22}{r['test_score'].mean():>10.3f}{r['test_score'].std():>7.3f}{r['fit_time'].mean():>8.3f}")

With scikit-learn 1.9, the output is:

model                   accuracy    std   fit s
baseline (majority)        0.627  0.004   0.000
logistic regression        0.979  0.014   0.004
decision tree              0.926  0.025   0.004
random forest              0.958  0.017   0.391
gradient boosting          0.970  0.012   0.168
SVM (RBF)                  0.977  0.007   0.004
k-NN (k=5)                 0.965  0.021   0.002
naive Bayes                0.939  0.020   0.001

The accuracy figures are reproducible with the same seed; the fit times depend on your machine and are only useful relative to each other.

A few things are worth reading out of this:

  • The baseline is 62.7 percent. Any model must clear that by a clear margin to be useful. All of them do.
  • The simplest strong model wins. Logistic regression, at 97.9 percent, is level with the RBF SVM and slightly ahead of gradient boosting. The differences between the top three are smaller than the fold-to-fold spread, so the data does not justify calling any of them better. Given a tie, take the one that is cheapest to run and easiest to explain.
  • The single tree is the weakest real model, and its spread is the largest. That matches what the decision tree article showed: one tree is easy to read but unstable.
  • The forest takes about 100 times longer to fit than logistic regression here, for lower accuracy. On 569 rows nobody will notice, but that ratio carries over to bigger data.

This dataset is close to linearly separable, so linear models do well. That is a property of this data, not a general ranking, and the next example shows the opposite case.

Model A scores 0.979 with a fold standard deviation of 0.014. Model B scores 0.970 with 0.012. What is the most defensible conclusion?

  • Model A is clearly better and should be deployed
  • Model B is better because its variance is lower
  • The difference is within the noise, so choose on cost and interpretability

Correct! A 0.009 gap is smaller than either model's spread across folds, so the comparison does not separate them.

When the boundary is curved

make_moons generates two interleaved half circles, a boundary no straight line can follow. Here are four candidates on 1,000 noisy points, using the same fold setup:

from sklearn.datasets import make_moons
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.neighbors import KNeighborsClassifier

X, y = make_moons(n_samples=1000, noise=0.25, random_state=0)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for name, m in [
    ("logistic regression", make_pipeline(StandardScaler(), LogisticRegression())),
    ("SVM (RBF)", make_pipeline(StandardScaler(), SVC())),
    ("k-NN (k=15)", make_pipeline(StandardScaler(), KNeighborsClassifier(15))),
    ("gradient boosting", HistGradientBoostingClassifier(random_state=0)),
]:
    print(f"{name:<20} {cross_val_score(m, X, y, cv=cv).mean():.3f}")
logistic regression  0.849
SVM (RBF)            0.937
k-NN (k=15)          0.938
gradient boosting    0.926

Now logistic regression trails by about nine points, and the flexible models are close to each other. With only two features, distance-based methods are in their element. The lesson is not that SVMs beat logistic regression; it is that the same shortlist, run the same way, gives a different answer on differently shaped data. That is why you run it.

Preprocessing changes the ranking

Scaling is part of the model choice for some algorithms and irrelevant for others. Running the breast cancer comparison again, with and without a StandardScaler:

k-NN           raw 0.932   scaled 0.965
SVM (RBF)      raw 0.921   scaled 0.977
random forest  raw 0.958   scaled 0.958

Without scaling, the SVM drops from near the top of the table to below the random forest. A comparison that skipped scaling would have ruled out the SVM for the wrong reason. Trees split on one feature at a time using thresholds, so units don’t affect them, and the forest’s score is identical either way.

The general point: when you compare algorithms, give each one the preprocessing it needs. Otherwise you are comparing preprocessing choices, not algorithms.

After you have a shortlist

Once one or two candidates stand out, a few steps turn them into a usable model.

Tune the leaders, not everything. Hyperparameter search is expensive. Run it on the top two candidates with GridSearchCV or RandomizedSearchCV, using the same folds. Defaults are often within a point or two of a tuned model, so check that tuning earns its cost.

Pick the metric that matches the cost of mistakes. Accuracy was fine above because the classes are only mildly imbalanced. For fraud or failure prediction, where positives are rare, use precision, recall, F1 or the area under the precision-recall curve, and pass it as scoring= so every model is judged on the same terms.

Score once on the held-out test set. Cross-validation scores were used to make choices, so they are slightly optimistic. The untouched test set gives the honest final number. If you go back and change things after looking at it, it stops being a test set.

Weigh the operational cost. Model size, prediction latency, how often it must be retrained, and whether someone has to explain its decisions all count. A model that is 0.3 points more accurate and ten times more expensive to serve is usually the wrong choice.

Letting the cloud run the comparison

The major clouds offer automated ML (AutoML) services that do this search for you on tabular data: they try several algorithm families and preprocessing steps, tune them, and rank the results on a held-out set.

ServiceWhere it livesInterface
Amazon SageMaker Canvas and the Autopilot AutoML APIAWSNo-code UI in Canvas; the AutoML API for code
Vertex AI AutoML for tabular dataGoogle CloudConsole or API; also tabular workflows with more control
Automated ML in Azure Machine LearningAzureStudio UI or the Python SDK

AWS moved the Autopilot user interface into SageMaker Canvas in late 2023; the Autopilot API remains available for code-based use. Azure lets you allow or block specific algorithms in a run, which is useful when you already know that, for example, interpretability rules some out.

AutoML is a good way to get a strong benchmark quickly, especially when you are unsure where to start. The same rules still apply: give it clean, leak-free data, choose the metric deliberately, and check the winning model on data it has never seen. Training also bills for compute time, so set a budget limit. The setting up a simple ML project article covers the platforms more generally.

Further reading:

Key takeaways

  • The problem type picks the family: regression, classification, clustering or dimensionality reduction. Data size, feature type, interpretability and prediction cost narrow it to a shortlist.
  • Include a simple linear model and a trivial baseline in every comparison. They tell you whether the complex models are earning their cost.
  • Compare fairly: the same folds for every model, preprocessing inside a pipeline, and the spread across folds, not just the mean.
  • Give each algorithm the preprocessing it needs. Unscaled features made a top SVM look worse than a random forest in the example above.
  • When scores are within the noise, choose the model that is cheaper to run and easier to explain.
  • On tabular data, gradient-boosted trees are usually worth a place on the shortlist, even though the series did not cover them.
  • AutoML services on AWS, Google Cloud and Azure automate the search, but the same rules about leakage, metrics and a held-out test set still apply.

Part 10 of 10 · Machine Learning Algorithms

  1. 01Linear Regression: Predicting Outcomes
  2. 02Logistic Regression: Understanding Probabilities
  3. 03Decision Trees: Making Decisions Using Data
  4. 04Random Forest: An Ensemble Learning Method
  5. 05Support Vector Machines: Classifying Data
  6. 06K-Nearest Neighbors: Finding Similar Data Points
  7. 07Naive Bayes: Applying Probability in ML
  8. 08K-Means Clustering: Grouping Similar Data
  9. 09Principal Component Analysis: Dimensionality Reduction
  10. 10Choosing an ML Algorithm: A Comparative Guide
Ready to check your understanding?Take the Artificial Unintelligence quiz
esc

Type to search all articles · ↑↓ to move · ↵ to open