The short version
- Classical machine learning (linear models, decision trees, random forests, gradient boosting) is still the best choice for most tabular business data — spreadsheets, transactions, customer records. It is fast, cheap and explainable.
- Deep learning (neural networks with many layers) wins when the input is raw and unstructured — images, audio, sensor signals — and you have lots of data.
- Transformers are a deep-learning architecture built on attention. They power modern language models and are the default for text, and increasingly for images and audio too — usually by fine-tuning or prompting a pre-trained model rather than training from scratch.
- Start with the simplest model that could work, and move up only when the data or the task demands it.
"Should we use AI for this?" usually hides a more useful question: which kind of AI? The three families covered here are not rivals so much as layers. Deep learning is a subset of machine learning, and transformers are a subset of deep learning. Each layer adds capability — and cost. Picking the wrong layer is one of the most common and expensive mistakes I see in real projects: a team spends weeks fine-tuning a large model for a problem a gradient-boosted tree would have solved in an afternoon, or forces a random forest onto raw images it can never understand.
This guide explains how each family works, what it needs, where it shines, and how to decide — with small code examples you can run yourself.
How the three fit together
Think of three nested circles:
- Machine learning (ML) — any system that learns patterns from data instead of following hand-written rules.
- Deep learning (DL) — machine learning with multi-layer neural networks that learn their own features from raw input.
- Transformers — a specific neural-network architecture, introduced in the 2017 paper "Attention Is All You Need", that relates every part of the input to every other part through a mechanism called self-attention.
When people say "classical" or "traditional" ML, they mean the methods outside the deep-learning circle. That's how this article uses the term.
1. Classical machine learning
How it learns
Classical models learn a mapping from features — columns you prepare, such as age, income, number of late payments — to a target. The key point is that humans usually design the features. The model's job is to find the best way to combine them.
The workhorses:
- Linear and logistic regression — a weighted sum of features. Simple, fast and easy to explain ("each late payment raises the risk score by X").
- Decision trees — a sequence of yes/no questions. Very interpretable, but a single tree overfits easily.
- Random forests — many trees trained on random subsets of data and features, then averaged. Robust and hard to break.
- Gradient boosting (XGBoost, LightGBM, CatBoost, scikit-learn's HistGradientBoosting) — trees added one at a time, each correcting the errors of the previous ones. Often the most accurate option on tabular data.
- Support vector machines, k-nearest neighbours, Naive Bayes — useful in specific situations, such as small datasets or text with simple word counts.
Try it
Here are three classical models on a small medical dataset that ships with scikit-learn (569 patients, 30 numeric features), evaluated with 5-fold cross-validation:
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.ensemble import RandomForestClassifier, HistGradientBoostingClassifier
X, y = load_breast_cancer(return_X_y=True) # 569 rows, 30 numeric features
models = {
"Logistic Regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
"Random Forest": RandomForestClassifier(n_estimators=300, random_state=0),
"Gradient Boosting": HistGradientBoostingClassifier(random_state=0),
}
for name, model in models.items():
scores = cross_val_score(model, X, y, cv=5, scoring="accuracy")
print(f"{name:20} {scores.mean():.3f}")
When I ran this, it printed:
Logistic Regression 0.981
Random Forest 0.963
Gradient Boosting 0.965
All three train in a few seconds on an ordinary laptop CPU. Notice that the simplest model won here. On small, clean tabular data that's common — and a good reminder to always try a simple baseline first. My kidney disease prediction case study walks through a full classical-ML project on messier real data.
Strengths and limits
- Strengths: works well with hundreds to millions of rows; trains in seconds or minutes on a CPU; easy to explain to managers, auditors and regulators; cheap to deploy.
- Limits: needs meaningful features. It cannot look at a raw photo, audio clip or paragraph and figure out what matters on its own. Feature engineering takes domain knowledge and time.
2. Deep learning
How it learns
A neural network stacks layers of simple computational units. Each layer transforms its input a little, and with enough layers the network learns its own representations: in an image model, early layers detect edges, middle layers detect shapes, and later layers detect objects. This is the big shift from classical ML — the model learns the features itself, straight from raw data, by adjusting millions of weights with gradient descent and backpropagation.
Before transformers, the main deep-learning architectures were:
- Multi-layer perceptrons (MLPs) — fully connected layers; the basic building block.
- Convolutional neural networks (CNNs) — slide small filters across images, so the same pattern is recognised wherever it appears. They dominated computer vision for most of the 2010s.
- Recurrent neural networks (RNNs, LSTMs, GRUs) — read sequences one step at a time while carrying a memory. They were the standard for text, speech and time series before transformers. I used a bidirectional LSTM in my online sexism detection project.
Try it
A small CNN that classifies handwritten digits (the classic MNIST dataset) in Keras:
from tensorflow import keras
from tensorflow.keras import layers
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train, x_test = x_train[..., None] / 255.0, x_test[..., None] / 255.0
model = keras.Sequential([
keras.Input(shape=(28, 28, 1)),
layers.Conv2D(32, 3, activation="relu"),
layers.MaxPooling2D(),
layers.Conv2D(64, 3, activation="relu"),
layers.MaxPooling2D(),
layers.Flatten(),
layers.Dropout(0.3),
layers.Dense(10, activation="softmax"),
])
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(x_train, y_train, epochs=3, batch_size=128, validation_split=0.1)
model.evaluate(x_test, y_test)
Networks like this typically reach around 99% accuracy on MNIST after a few epochs. The model sees only raw pixel values — nobody told it what a "loop" or a "stroke" is. A random forest on the same raw pixels can do reasonably well on a dataset this simple, but the gap grows quickly on real photographs, where CNNs and transformers are far ahead.
Strengths and limits
- Strengths: learns directly from images, audio, signals and text; keeps improving as you add more data; can be pre-trained once and adapted to new tasks.
- Limits: needs much more data (often tens of thousands of examples or more, unless you start from a pre-trained model); training benefits from GPUs; harder to explain; more hyperparameters to tune; easy to overfit on small datasets. On ordinary tabular data, well-tuned gradient boosting very often matches or beats it.
3. Transformers
How they work
RNNs read a sentence word by word, so information from early words has to survive a long chain of steps, and training can't be parallelised well. Transformers replaced that with self-attention: every token (a word or piece of a word) looks at every other token at once and decides how much each one matters for understanding it.
Take the sentence "The bank approved the loan because it had a strong record." Attention lets the model connect "it" to "bank" directly, in a single step, however far apart the words are. Stack many attention layers with feed-forward layers in between, and the model builds a rich, context-aware representation of the whole input. Because all positions are processed in parallel, transformers train efficiently on GPUs — which is what made today's very large models practical.
Three broad shapes exist:
- Encoder-only (BERT, RoBERTa, XLM-R) — read the whole input and produce representations. Great for classification, search and named-entity recognition.
- Decoder-only (the GPT family, Llama, Claude and most chat models) — generate text one token at a time. The basis of large language models.
- Encoder-decoder (T5, BART) — read an input and generate an output. Good for translation and summarisation.
The same idea now works beyond text. Vision Transformers split an image into patches and treat them like words, and speech models such as Whisper use transformers for audio.
Try it
You almost never train a transformer from scratch. Instead, you download a pre-trained one and either use it directly, fine-tune it on your data, or call a large model through an API. With Hugging Face's transformers library:
from transformers import pipeline
classifier = pipeline(
"sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english",
)
print(classifier([
"The new mobile banking app is fast and easy to use.",
"I waited 40 minutes and the transfer still failed.",
]))
# -> a list with one {'label': ..., 'score': ...} per sentence
Three lines give you a working sentiment classifier, because the model has already learned English from a huge amount of text. Fine-tuning the same model on a few thousand labelled examples from your own domain usually improves it further. For larger language models, the main tools are prompting and retrieval-augmented generation — see how to build a RAG chatbot in Python.
Strengths and limits
- Strengths: state of the art for language and, increasingly, for vision and speech; pre-trained models transfer knowledge to new tasks with little data; one architecture handles many problems; large models can follow instructions without any task-specific training.
- Limits: expensive to train and run (attention cost grows with the square of the input length); large models need GPUs or paid APIs; outputs can be confidently wrong (hallucinations); harder to explain and audit; and English-centric tokenizers serve low-resource languages like Nepali less well — I cover that in NLP for the Nepali language.
Side-by-side comparison
| Classical ML | Deep learning (CNN/RNN) | Transformers | |
|---|---|---|---|
| Best input | Tabular, structured features | Images, audio, signals, sequences | Text; also images, audio, multimodal |
| Features | Designed by people | Learned from raw data | Learned; usually pre-trained |
| Data needed | Hundreds to millions of rows | Large, unless using a pre-trained model | Huge to pre-train; small to fine-tune or prompt |
| Hardware | Laptop CPU | GPU helps a lot | GPU or API for anything sizeable |
| Training time | Seconds to minutes | Minutes to days | Fine-tuning: minutes to hours; pre-training: weeks |
| Explainability | High (coefficients, feature importance, SHAP) | Low to medium | Low; attention maps help only partly |
| Running cost | Very low | Low to medium | Medium to high |
| Typical tools | scikit-learn, XGBoost, LightGBM | PyTorch, TensorFlow/Keras | Hugging Face, LLM APIs, PyTorch |
| Example uses | Credit scoring, churn, fraud rules, demand forecasting | Cheque and ID image checks, speech, sensor anomalies | Chatbots, document Q&A, summarisation, translation, search |
How to choose: a practical decision guide
- What does one example look like?
- A row of numbers and categories → start with classical ML (gradient boosting plus a logistic-regression baseline).
- An image, audio clip or raw signal → deep learning, ideally fine-tuning a pre-trained CNN or vision transformer.
- Free text (emails, chats, documents) → transformers. Try a pre-trained model or an LLM prompt first, then fine-tune if needed.
- How much labelled data do you have? With a few hundred examples, use classical ML on tabular data, or a pre-trained transformer with few-shot prompting for text. Avoid training deep networks from scratch.
- Must you explain each decision? In lending, insurance and healthcare, regulators and customers may need reasons. Interpretable classical models, or classical models alongside an explanation layer, are often required.
- What is your budget for latency and cost? A model that scores millions of transactions a day in milliseconds on a CPU is a gradient-boosting job, not an LLM job.
- Always build a baseline. Measure a simple model first. A complex model has to beat it by enough to justify its extra cost and risk.
They work best together
Real systems often combine all three. A typical pattern in banking and fintech:
- A transformer reads free-text complaint emails and turns them into a category, a sentiment score and extracted fields (account type, amount).
- Those outputs become features alongside transaction history.
- A gradient-boosted model uses all the features to predict which customers are likely to leave, and stays fast and explainable for the team that acts on it.
The same idea applies with embeddings: a transformer converts text or images into vectors, and a simple classical model or vector search works on top. You get the language understanding of a large model with the speed, cost and transparency of a small one.
Common mistakes
- Using an LLM for a spreadsheet problem. Predicting a number from structured columns is what gradient boosting is for.
- Training a deep network from scratch on a small dataset. Fine-tune a pre-trained model instead, or go classical.
- Judging models only by accuracy. Also look at latency, cost per prediction, explainability, and performance on the cases that matter most (often the rare class).
- Skipping data quality. No architecture fixes wrong labels or leaked features. See my pandas data-cleaning guide.
- Assuming English results carry over. For Nepali or code-mixed text, test multilingual models on your own data before committing.
Where to learn each
If you're building your skills, learn them in this order: classical ML first (statistics, scikit-learn, cross-validation, metrics), then neural-network fundamentals (PyTorch or Keras, CNNs, training dynamics), then transformers (Hugging Face, fine-tuning, embeddings, prompting and RAG). Each layer makes the next easier to understand. My 12-month roadmap to becoming an AI engineer in Nepal lays out the full path with project ideas.
Summary
Classical machine learning is the reliable, explainable workhorse for structured data. Deep learning learns from raw images, audio and signals when you have the data and compute. Transformers bring attention-based understanding to language and beyond, and are usually used pre-trained. None of them is "best" — the best engineers know all three and pick the simplest one that solves the problem well.
Spotted an error or have a question about this article? Send me a message — corrections are applied and noted with an updated date. See the editorial policy.