10 Machine Learning Algorithms Explained With Worked Examples

What ten classic machine learning algorithms actually compute, from linear and logistic regression to random forests, gradient boosting, k-NN, SVM, naive Bayes, k-means, PCA and association rules, each with a small worked example checked by code, plus which one to use when.

10 Machine Learning Algorithms Explained With Worked Examples

A machine learning algorithm is a procedure that learns a rule from example data instead of having the rule written by hand. The ten you will meet first are linear and logistic regression, decision trees, random forests and gradient boosting, k-nearest neighbours, support vector machines, naive Bayes, k-means, principal component analysis and association rules. Below, each one is worked through with a small set of numbers you can check by hand.

In short (as of 23 Nov 2026)

  • Three families: supervised algorithms learn from labelled examples (predict a number or a category), unsupervised ones find structure in unlabelled data, and reinforcement learning learns from rewards.
  • On tables of data, trees still win: in a 45-dataset benchmark, tree-based models such as XGBoost and random forests stayed state-of-the-art on medium-sized tabular data of about 10,000 samples (Grinsztajn et al., NeurIPS 2022).
  • The standard toolkit: scikit-learn was the most popular ML framework in Kaggle's 2022 survey of 23,997 practitioners; its current release is 1.9 (June 2026, 1.9.1 in September).
  • Worked numbers in this guide: a regression that predicts 11.99 mm of spring extension at 60 N, a tree split that cuts Gini impurity from 0.48 to 0.317, and a k-means run that converges in two updates (Skill-Lync calculations, 23 Nov 2026).

This guide is for engineering students and early-career engineers who want to understand what each common algorithm actually computes, not just its name. It replaces our April 2023 overview. Every example uses a tiny made-up engineering dataset so the arithmetic fits on a page; the numbers were computed and cross-checked by a Python script that Skill-Lync keeps with this article. For the bigger picture of what machine learning is, start with our worked introduction to machine learning.

What are the main types of machine learning algorithms?

There are three main types. Supervised learning trains on examples that already carry the right answer, such as past readings labelled "faulty" or "OK". Unsupervised learning gets no answers and looks for groups or structure. Reinforcement learning learns by trial and error from a reward signal. Semi-supervised learning mixes a few labels with many unlabelled examples.

Within supervised learning, the question is what you are predicting. A number (extension in mm, price in ₹, remaining life in hours) is a regression problem. A category (pass/fail, spam/not spam, defect type) is a classification problem. Within unsupervised learning, you are usually grouping similar rows (clustering), compressing many columns into a few (dimensionality reduction) or finding items that occur together (association). The map below puts the ten algorithms in this guide on those branches.

Decision map: labelled data and a number to predict leads to linear regression then random forest or gradient boosting; labelled data and a category leads to logistic regression, decision tree, k-NN, SVM or naive Bayes; unlabelled data leads to k-means for groups, PCA to reduce columns and association rules for items bought together
Start from the data you have and the question you are asking. Drawn by Skill-Lync, following the task split in the scikit-learn user guide.

1. Linear regression: how does it predict a number?

Linear regression fits the straight line that makes the squared vertical errors between the line and the data as small as possible. Given five spring readings, it finds a slope of 0.199 mm per newton and predicts 11.99 mm of extension at 60 N. It is the baseline every regression problem should start with.

Data: loads of 10, 20, 30, 40 and 50 N gave extensions of 2.1, 3.9, 6.2, 7.8 and 10.1 mm. The least-squares slope and intercept are:

The prediction at 60 N is mm, and : the line explains 99.7% of the variation in the readings. The slope also has a physical meaning: the spring stiffness is about N/mm. That is the point of a simple model: you can read it. The catch is in the name. If the true relationship curves, a straight line will be confidently wrong outside the range you measured. You can try other fits on your own data with our curve fitting calculator.

Five spring readings from 10 to 50 N with a fitted line y = 0.05 + 0.199x, R squared 0.9973, and a predicted extension of 11.99 mm at 60 N
The least-squares line through five readings, and its prediction at 60 N. Skill-Lync calculation, 23 Nov 2026.

2. Logistic regression: how does it predict a yes or no?

Logistic regression predicts the probability of a yes/no outcome by passing a linear score through an S-shaped sigmoid curve, so the output always lies between 0 and 1. Fitted to ten bearings, it gives a 46.8% chance of failure at 82 °C and crosses 50% at 82.5 °C. Despite the name, it is a classification algorithm.

Data: ten bearings ran at 60, 65 … 105 °C; the ones at 80, 90, 95, 100 and 105 °C failed within 30 days. Maximising the likelihood (here by Newton's method, checked against plain gradient descent) gives:

At 82 °C, and . The 50% point is where : °C. Each extra degree multiplies the odds of failure by . Notice the 85 °C bearing that survived and the 80 °C one that failed: real data overlaps, and logistic regression handles that by giving probabilities rather than hard rules. You choose the cut-off (50%, or lower if a missed failure is expensive).

S-shaped logistic curve of failure probability against bearing temperature from 55 to 110 degrees C, crossing 50 percent at 82.5 degrees C, with ten bearings plotted at 0 or 1
The fitted probability curve and the ten bearings it was fitted to. Skill-Lync calculation, 23 Nov 2026.

3. Decision tree: how does it choose where to split?

A decision tree asks a sequence of yes/no questions about the features and picks, at each step, the question that makes the resulting groups purest. Purity is usually measured by Gini impurity. Splitting ten parts on "surface roughness Ra ≤ 1.6 µm" cuts the impurity from 0.48 to 0.317, a gain of 0.163.

Gini impurity for a group with class shares is . It is 0 for a pure group and 0.5 for a 50/50 two-class mix. The ten parts are 6 pass and 4 fail:

The algorithm tries every feature and every threshold, keeps the split with the lowest weighted impurity, and repeats inside each branch. The result reads like a checklist a quality engineer could follow, which is why trees are popular when a decision must be explained. Left to grow, a single tree memorises noise (overfitting), so in practice you limit its depth or, better, use many trees.

4. Random forest and gradient boosting: why do many trees beat one?

Ensembles combine many trees. A random forest trains each tree on a random resample of the data and lets them vote, which averages away the noise any one tree learns. Gradient boosting builds trees one after another, each fitted to the errors left by the trees before it. On tabular data these two are usually the strongest off-the-shelf choice.

Random forest, worked: each tree sees a bootstrap sample, rows drawn with replacement from . The chance a given row is left out is , which for is 0.368, about . So every tree misses roughly 37% of the data, those "out-of-bag" rows give a free validation set, and the trees differ from each other. If 3 of 5 trees say "fail", the forest predicts fail with a vote share of 0.6.

Gradient boosting, worked: three targets are 3, 5 and 10. Start by predicting the mean, 6. The residuals are −3, −1 and +4. A one-split tree fits them with leaf values −2 (for the first two) and +4. With a learning rate of 0.1, the new predictions are 5.8, 5.8 and 6.4, and the mean squared error falls from 8.667 to 7.147. Hundreds of such small steps make the model; the small learning rate is what stops it overfitting quickly. XGBoost, LightGBM and scikit-learn's HistGradientBoosting are all implementations of this idea. Our post on ensemble techniques covers bagging, boosting and stacking in more depth.

Why this matters: Grinsztajn, Oyallon and Varoquaux benchmarked deep networks against tree ensembles on 45 tabular datasets and found tree-based models still state-of-the-art on medium-sized data of about 10,000 rows, even before counting their speed advantage (NeurIPS 2022). For spreadsheet-like engineering data, start here before reaching for a neural network.

5. k-nearest neighbours: how does it classify a new reading?

k-nearest neighbours (k-NN) stores the training examples and labels a new point by majority vote among the k closest ones. It learns nothing in advance, so all the work happens at prediction time. A pump reading of 5.0 mm/s vibration at 75 °C has three faulty neighbours out of three, so k-NN with k = 3 calls it faulty.

The six training readings are (vibration mm/s, temperature °C): OK at (2.0, 60), (2.5, 65), (3.0, 62); faulty at (6.5, 80), (7.0, 85), (6.0, 78). Because millimetres per second and degrees are on different scales, both features are first min-max scaled to 0–1 (vibration over 2.0–7.0, temperature over 60–85). After scaling, the distances from the query to the three faulty readings are 0.233, 0.361 and 0.566; the nearest OK reading is 0.640 away.

Skip the scaling step and temperature, with its bigger numbers, would dominate the distance: the most common k-NN mistake. k-NN works well with few features and modest data; with many features, distances become less meaningful and prediction gets slow. Our dedicated k-NN article walks through choosing k.

6. Support vector machine: what is the margin?

A support vector machine (SVM) separates two classes with the boundary that leaves the widest possible gap, the margin, to the nearest points on each side. Those nearest points are the support vectors. For the margin width is units.

The classifier labels a point by the sign of its score. With and , the point (2, 2) scores , which is positive, so it belongs to the positive class. Training maximises the margin, which is the same as minimising , while allowing a penalised number of points inside it (the C parameter). With a kernel, such as the radial basis function, the same idea draws curved boundaries. SVMs are strong on small and medium datasets with many features (text, spectra) but scale poorly to millions of rows.

7. Naive Bayes: how does it classify text?

Naive Bayes applies Bayes' theorem, assuming every feature is independent of the others given the class. The assumption is rarely true, but the classifier is fast, needs little data and works well on text. If 20% of maintenance notes are urgent, it turns the word "leak" into a 75% probability that a note is urgent.

Suppose "leak" appears in 60% of urgent notes and 5% of routine ones. Bayes' theorem gives:

With several words, naive Bayes multiplies their likelihoods (in practice it adds logarithms to avoid tiny numbers). It is the classic spam filter and still a good first model for sorting tickets, reviews or inspection remarks.

8. k-means clustering: how does it find groups without labels?

k-means splits unlabelled data into k groups by repeating two steps: assign each point to its nearest centroid, then move each centroid to the mean of its points. It stops when nothing changes. Six points split into two clusters with centroids at (1.25, 1.50) and (4.00, 5.25) after two updates.

The six points are (1, 1), (1.5, 2), (3, 4), (5, 7), (3.5, 5) and (4.5, 5), and the starting centroids are the first two points. In the first pass, only (1, 1) is nearest the first centroid, so it stays at (1, 1) while the second moves to the mean of the other five, (3.5, 4.6). In the second pass (1.5, 2) switches to the first cluster and the centroids move to (1.25, 1.50) and (4.00, 5.25). A third pass changes nothing. The within-cluster sum of squared distances (inertia) is 7.875.

Six points split by k-means into two clusters; centroid A moves from (1, 1) to (1.25, 1.50) and centroid B from (1.5, 2) through (3.5, 4.6) to (4.00, 5.25); inertia 7.875
How the two centroids travel before the assignments settle. Skill-Lync calculation, 23 Nov 2026.

You must choose k yourself (the "elbow" in inertia against k, or a silhouette score, helps), and k-means assumes roughly round clusters of similar size. Engineers use it to group machines with similar duty cycles or customers with similar orders before building separate models for each.

9. Principal component analysis: how does it reduce the number of features?

Principal component analysis (PCA) rotates the data onto new axes ordered by how much variance they capture, so you can keep the first few and drop the rest. On five correlated two-feature points, the first component carries 97.0% of the variance: one number per point keeps almost all the information.

PCA centres the data, computes the covariance matrix and takes its eigenvalues. For the five points (2.5, 2.4), (0.5, 0.7), (2.2, 2.9), (1.9, 2.2) and (3.1, 3.0):

The script checks the eigenvalues against a singular value decomposition, the way libraries compute PCA. In practice PCA turns 100 correlated sensor channels into a handful of components before clustering or regression. Scale the features first, or the one with the largest units dominates.

10. Association rules: what do support, confidence and lift mean?

Association rule mining (the Apriori algorithm is the classic) finds items that occur together and scores each rule by support, confidence and lift. In five purchase orders, "bearing → grease" has 60% support and 75% confidence, yet its lift is 0.94: buying a bearing does not make grease more likely.

The orders are {bearing, grease, seal}, {bearing, grease}, {bearing, seal}, {grease, bolt} and {bearing, grease, bolt}. Bearings appear in 4 of 5 orders, grease in 4 of 5, both in 3 of 5:

Lift above 1 means the items go together more than chance; below 1, less. Here grease is simply in most orders, so a 75% confidence is unremarkable. Always check lift before acting on a rule. Retailers and spare-parts teams use these rules for bundling and stocking.

What about neural networks and reinforcement learning?

Neural networks stack many weighted sums with non-linear functions between them and learn the weights by gradient descent. They dominate images, audio, language and other unstructured data, and transformer architectures were gaining ground in Kaggle's 2022 survey. On tables of engineering data, they usually need more data and tuning than tree ensembles to match them.

Reinforcement learning trains an agent by reward rather than labelled answers: a controller tries actions, gets a score and gradually prefers actions that pay off. It is used in robotics, game playing and some control problems, but it needs a simulator or many safe trials. Semi-supervised learning fills the gap when labelling is expensive, for example when only a few hundred of thousands of inspection images have been tagged. Our comparison of types of machine learning algorithms covers these families side by side.

Which machine learning algorithm should a beginner learn first?

Learn linear and logistic regression first, then decision trees and random forests, then k-means and PCA. That order covers regression, classification and unsupervised learning, and every later method builds on the ideas of a loss function, overfitting and validation that these five teach. Python with scikit-learn implements all ten algorithms in this guide.

A practical routine for any new problem: split off a test set first, fit the simplest sensible model as a baseline, then try a tree ensemble and keep it only if it beats the baseline on data it has not seen. Measure classification with a confusion matrix, not accuracy alone, especially when failures are rare. For engineering applications, see machine learning for mechanical engineers.

Learn machine learning algorithms with Skill-Lync

Skill-Lync's 12-week course Introduction to Machine Learning Algorithms and their Implementation in Python implements these algorithms in code. If you want the maths underneath, from linear algebra to probability, take Math behind Machine Learning & AI using Python. For a full career track, there is the 24-week Post Graduate Program in Data Science and Machine Learning. Unsure which fits your background? Talk to a Skill-Lync counsellor.

Frequently asked questions

What is the difference between an algorithm and a model in machine learning?

The algorithm is the learning procedure; the model is what it produces from your data. Linear regression is an algorithm; "extension = 0.05 + 0.199 × load" is the model it learned from five spring readings. Train the same algorithm on different data and you get a different model.

Which machine learning algorithm is the most accurate?

None is best for every problem. On tabular data, gradient boosting and random forests are usually the strongest starting point; a 2022 benchmark of 45 datasets found tree-based models still ahead of deep learning on medium-sized tables. For images, audio and text, neural networks lead. Always compare against a simple baseline on held-out data.

Is linear regression really machine learning?

Yes. It learns its slope and intercept from data and is judged on predictions for data it has not seen, which is exactly what machine learning means. It is also the simplest model to interpret, which is why it remains the first baseline for any prediction of a number.

Do I need to scale features before training?

For distance- and gradient-based algorithms, yes: k-NN, k-means, SVM, PCA and regularised regression all change their answers when one feature is measured in larger units. Tree-based algorithms (decision trees, random forests, gradient boosting) split on thresholds and are not affected by scaling.

How much maths do I need to learn these algorithms?

To use them well, school-level algebra plus basic statistics (mean, variance, probability) is enough, as the worked examples here show. To understand why they work and to tune them, add linear algebra (vectors, matrices, eigenvalues) and differential calculus for gradient descent.

Which programming language is used for machine learning algorithms?

Python, by a wide margin. scikit-learn covers the classic algorithms in this guide, XGBoost and LightGBM cover gradient boosting, and PyTorch covers neural networks. Kaggle's 2022 survey found scikit-learn the most popular ML framework, with PyTorch growing year on year.

Sources and further reading

Want this on your résumé?

Talk to a counsellor.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.