Skip to main content

01 - Types of Machine Learning: Which One Fits Your Problem

Machine Learning in three families: supervised, unsupervised and reinforcement learning, with runnable scikit-learn listings and a rule for choosing.

What do you think about this article?

At a Glance

Machine Learning in three families: supervised, unsupervised and reinforcement learning, with runnable scikit-learn listings and a rule for choosing.

Three ways of learning from data, and how to tell which one you need

Machine Learning is the way to build a program when you cannot write the rules, but you have examples. Take a spam filter: writing by hand "if the word winner appears then it is spam" works for a week, then the spammers change the word. If instead you show an algorithm ten thousand emails that are already classified, it works out by itself which signals separate the two classes, and it updates them when you show it new examples. The result is a model: a mathematical function whose parameters are chosen from the data, able to answer on inputs it has never seen.

There are three families of approaches, and the choice does not depend on the algorithm you like best but on what you have in hand: examples with the right answer next to them, examples without an answer, or an environment that rewards or punishes your actions. This article opens the series and gives you the map; the next ones go into the algorithms, starting from linear and logistic regression. To follow the listings you only need the basics of Python and the ability to read a NumPy array: no statistics prerequisite.

The workflow of a project, and why the order matters

Whatever algorithm you pick, the project goes through the same six stages: data collection, preprocessing (cleaning, missing values, scaling), feature engineering (choosing or building the informative variables), training, evaluation on data not used for training, and finally deployment, that is putting the model into production to make predictions on real data. The stages are not interchangeable. Evaluation only makes sense if the test data was set aside before you looked at it: if you compute the mean used to scale the columns on the whole dataset, the model has already "seen" part of the test set and the final score is inflated. This leak of information is called data leakage and it is the most frequent mistake in beginners' projects; the scikit-learn guide to common pitfalls devotes a whole section to it (you will find it in the sources).

A figure that circulates often, "80% of the time is spent on data", has no primary source to support it and I do not repeat it here. What you can check for yourself is the effect: in the next articles you will see a model change its score by several points just because the inputs change. Stages 2 and 3 are covered in Feature Engineering and Data Preprocessing, stage 5 in Evaluation Metrics, stage 6 in End-to-End ML Pipeline.

Supervised learning: learning from examples with the answer

In the supervised case every example comes with its label, the correct answer, and the model learns the function that leads from the input to the label. If the label is a category (spam or not spam, species of flower) the problem is one of classification; if it is a continuous number (the price of a house) it is one of regression. The practical question that lets you recognize the case is: "do I have a column I want to predict, and is it already filled in for the past data?". If yes, you are here.

The listing below uses the Iris dataset, included in scikit-learn: 150 flowers, four measurements each (length and width of sepal and petal), three species. train_test_split sets aside 20% of the flowers, that is 30, which the model will not see during training; random_state=42 makes the split repeatable, otherwise every run would give a different number. I added two things compared with the usual "accuracy 1.0": a DummyClassifier that always answers with the most frequent class, to know which score you start from, and a five-fold cross-validation, which repeats training and testing on five different splits instead of trusting a single one.

Python - Supervised classification with baseline and cross-validation
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score

iris = load_iris()
X, y = iris.data, iris.target

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
model = RandomForestClassifier(n_estimators=100, random_state=42).fit(X_train, y_train)

print("baseline:", round(accuracy_score(y_test, baseline.predict(X_test)), 3))
print("random forest:", round(accuracy_score(y_test, model.predict(X_test)), 3))

scores = cross_val_score(RandomForestClassifier(random_state=42), X, y, cv=5)
print("cross-validation:", scores.round(3), "mean", round(scores.mean(), 3))

# Output:
# baseline: 0.3
# random forest: 1.0
# cross-validation: [0.967 0.967 0.933 0.967 1.   ] mean 0.967

Accuracy is the fraction of correct answers. The model built with fit is a forest of one hundred decision trees, which article 3 covers; for now it is a box with two methods, fit to learn and predict to answer. Read the numbers in the order in which they appear in the output: the baseline, which guesses the most frequent class, gets 0.3, that is 9 flowers out of 30 (in the whole dataset the three species are in equal parts, but in the random test set the most frequent one weighs 30%); it is the floor below which a model is worth nothing. The forest on the 30-flower test set does better, but 30 examples are few: one more or one fewer wrong flower moves the result by more than three points. That is why cross-validation is more honest, and it shows that the stable value lies between 0.93 and 1.00 depending on the fold. The detail to distrust is a "1.00" obtained on a small test set: it says that that split was easy, not that the model is perfect.

Unsupervised learning: looking for structure without answers

Without labels there is no answer to imitate. The algorithm looks for the structure of the data on its own: groups of similar elements (clustering, for example K-Means or DBSCAN), a more compact version of the variables (dimensionality reduction, for example PCA), or the elements that look like no other (anomaly detection). The typical case is customer segmentation: you have annual spend and number of purchases, you have no "customer type" label, and you want to understand whether there are groups with different behaviors.

K-Means fixes the number of groups k in advance, places k centers and alternates two steps: it assigns each point to the nearest center, then moves each center to the mean of its points, until nothing changes. The criterion it minimizes is called inertia, the sum of the squared distances from the centers. Since it relies on distances, the columns must be brought to the same scale: in the listing the spend is in the order of thousands and the purchases in the order of tens, and without StandardScaler the spend alone would decide. The listing prints the standard deviation before and after, so you see the effect instead of believing it.

Python - Clustering with K-Means and scaling
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler

# Customers: annual spend in euros and number of purchases (invented data for the example)
X = np.array([
    [15000, 35], [16000, 40], [14500, 30],
    [3000, 5], [2500, 3], [3500, 8],
    [8000, 15], [9000, 20], [7500, 18],
])

X_scaled = StandardScaler().fit_transform(X)
print("standard deviation before:", X.std(axis=0).round(1))
print("standard deviation after:  ", X_scaled.std(axis=0).round(1))

kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
etichette = kmeans.fit_predict(X_scaled)
print("groups:", etichette)
print("silhouette:", round(silhouette_score(X_scaled, etichette), 2))
print("inertia:", round(kmeans.inertia_, 2))

# Output:
# standard deviation before: [5017.3   12.5]
# standard deviation after:   [1. 1.]
# groups: [1 1 1 0 0 0 2 2 2]
# silhouette: 0.75
# inertia: 0.59

The first pair of lines shows the reason for scaling: before, the spend has a dispersion of thousands and the purchases of about a dozen, after, both are 1. The inertia printed at the end (0.59 on scaled data) is the value the algorithm minimizes: by itself it has no interpretable unit, it serves to compare two solutions on the same data. n_init=10 restarts the algorithm from ten initial positions of the centers and keeps the solution with the lowest inertia, because a bad start can stop at a mediocre result. The group numbers (0, 1, 2) are arbitrary labels: by changing random_state the same customers may end up in "group 2" instead of "group 0", and what matters is who is with whom. Here the three blocks of three customers are separated just as I invented them. The silhouette measures how much closer a point is to its own group than to the nearest of the others: it goes from -1 to 1, and a high value says the groups are well separated. On real data it will rarely be so clean, and choosing k becomes the real problem; article 5 deals with it.

Reinforcement learning: learning from consequences

In reinforcement learning there is no dataset but an agent acting in an environment. At each step it observes the state, chooses an action, receives a reward (possibly negative), and must learn a policy, that is a rule "in this state do this", that maximizes the total reward over time. The decisive difference from the supervised case is that nobody tells you which action was the right one: you find out afterwards, and sometimes much later, from the sum of the rewards. That is why reinforcement learning is used where actions have chained consequences: board games, robot control, resource management. The reference text is the book by Sutton and Barto, freely available online.

The minimal case that already contains the central dilemma is the multi-armed bandit: three slot machines with different winning probabilities, which the agent does not know. Each pull gives 1 with the probability of the lever, otherwise 0. If it always pulls the lever that seems best so far, it risks never discovering the one that is really best; if it tries at random, it wastes pulls. The epsilon-greedy strategy settles the trade-off with a coin: with probability epsilon it tries a random lever (explores), otherwise it uses the best estimated one (exploits). The probabilities 0.30, 0.50 and 0.65 are values I chose for the example.

Python - An epsilon-greedy agent on three levers
import numpy as np

VERE = np.array([0.30, 0.50, 0.65])   # true winning probabilities, hidden from the agent

def gioca(epsilon, seed, giri=2000):
    rng = np.random.default_rng(seed)
    stima = np.zeros(3)
    n = np.zeros(3)
    for _ in range(giri):
        if rng.random() < epsilon:
            a = int(rng.integers(3))          # explore: a random lever
        else:
            a = int(np.argmax(stima))         # exploit: the lever that looks best
        r = float(rng.random() < VERE[a])     # reward 1 with probability VERE[a], otherwise 0
        n[a] += 1
        stima[a] += (r - stima[a]) / n[a]     # running mean updated step by step
    return stima, n

for eps in (0.0, 0.1):
    scelte = [int(np.argmax(gioca(eps, seed)[1])) for seed in range(10)]
    print("epsilon", eps, "most used lever in 10 trials:", scelte)

stima, n = gioca(0.1, 0)
print("estimates with epsilon 0.1:", stima.round(2), "pulls:", n.astype(int))

# Output:
# epsilon 0.0 most used lever in 10 trials: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# epsilon 0.1 most used lever in 10 trials: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
# estimates with epsilon 0.1: [0.31 0.46 0.65] pulls: [  81   72 1847]

The line that learns is stima[a] += (r - stima[a]) / n[a]: it updates the mean reward of the lever without keeping the history, moving it by a fraction of the error. In the output, with epsilon = 0 the agent uses lever 0 in all ten trials, even though it is the worst: the estimates start from zero, lever 0 wins the argmax tie, as soon as it pays once its estimate becomes positive and no alternative ever overtakes it, because they are never tried. With epsilon = 0.1 lever 2, the best one, is the most used in all the trials, and in the last line you see the estimates approaching the true values (0.65 for lever 2) while the poor levers were tried only 81 and 72 times out of 2000. The price of exploration is exactly that 10% of random pulls. A real problem has states that change with every action and delayed rewards, and it is much harder, but the balance between exploring and exploiting stays the same.

How to choose the paradigm

Three questions, in order, are almost always enough. The table summarizes where each answer leads.

Your situationParadigmWhat you produce
I have past examples with the right answerSupervisedA prediction: category (classification) or number (regression)
I only have data, no answersUnsupervisedGroups, a compact representation, or anomalous points
I can act and observe the result of the actionsReinforcementA policy: which action in which state

In professional practice the first case is by far the most frequent, because companies have histories of orders, tickets, transactions with a known outcome; the following articles will be almost all supervised. Unsupervised learning often serves as exploration before building a model, and reinforcement learning requires an environment in which mistakes cost little or which can be simulated. A common trap is using clustering to "predict" something: the groups have no guaranteed meaning, and if you have the labels, using them almost always pays more.

scikit-learn: the API you will meet throughout the series

scikit-learn is the Python library for classical Machine Learning, that is everything that is not deep learning. Its design choice is a uniform interface: every estimator has fit(X, y) to learn, predict(X) to answer and, for supervised models, score(X, y) to measure; every transformer has fit and transform. Once you have learned one algorithm, the others are used in the same way. The listing puts scaling and model together in a Pipeline, and passes it to cross_val_score: at each fold the scaler is fitted only on the training data of that fold, and it is the practical answer to the data leakage described above.

Python - Pipeline with scaling and cross-validation
from sklearn.datasets import load_wine
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)

pipeline = Pipeline([
    ("scaler", StandardScaler()),
    ("classifier", LogisticRegression(max_iter=1000)),
])

scores = cross_val_score(pipeline, X, y, cv=5, scoring="accuracy")
print("accuracy per fold:", scores.round(3))
print(f"mean {scores.mean():.3f}, standard deviation {scores.std():.3f}")

# Output:
# accuracy per fold: [0.972 0.972 1.    0.971 1.   ]
# mean 0.983, standard deviation 0.014

I used the Wine dataset (178 wines, 13 chemical measurements, three cultivars) because it has columns on very different scales, so scaling really matters. The parameter max_iter=1000 raises the iteration limit of the logistic regression optimizer, 100 by default: on the scaled data the limit is enough (in my tests no warning appears), while on the same data without scaling the lbfgs optimizer reports that it did not converge, confirming that scaling is not a cosmetic detail. The output reports five accuracies, one per fold, their mean and the standard deviation: the latter is the information the mean alone hides, because it tells you how much the result depends on the split. The ecosystem is wider: TensorFlow and PyTorch for deep learning, pandas for tabular data, XGBoost and LightGBM for boosting. In this series you will only need scikit-learn, NumPy and pandas.

What you can do now

Faced with a new problem you can ask the question that decides everything: do I have the answer for past cases, do I only have the data, or can I act and observe? You know that a score only makes sense next to the baseline and a repeated validation, that test data is isolated before every transformation, and that exploring and exploiting are two costs that balance each other. The next step is the first real model: linear and logistic regression.

Frequently asked questions

What is the difference between supervised and unsupervised learning?

In supervised learning every training example has the correct answer (the label) and the model learns to predict it; in unsupervised learning there are no labels and the algorithm looks for structure in the data, for example groups of similar elements.

When is reinforcement learning worth it?

When you can act in an environment, simulated or real, receive a reward and repeat many times, and the actions have consequences over time. If you already have examples with the right answer, supervised learning is almost always simpler.

Why is the baseline important in an ML project?

Because it gives the starting score: on three balanced classes, always guessing the most frequent one is worth roughly a third, and a model is useful only if it beats that value by a clear margin.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects