Module 1 · Beginner · Getting started with machine learning

Types of machine learning, with examples

Types of machine learning explained with examples and Python code: supervised (regression and classification), unsupervised, self-supervised and reinforcement.

By theprogrammers team · · 7 min read

Every machine learning problem starts with one question: what kind of data do you have, and what do you want the model to do? The answer decides which type of machine learning you need.

There are three main types, supervised, unsupervised and reinforcement learning, plus two in-between types that power modern AI: semi-supervised and self-supervised learning. This guide explains each one with real examples and short Python code, then gives you a simple way to choose.

The three main types at a glance

TypeLearns fromGoalExample
SupervisedExamples with answers (labels)Predict the answer for new examplesPredict a house price
UnsupervisedExamples without answersFind structure or groupsGroup customers by behaviour
ReinforcementRewards and penalties from trying thingsLearn the best actionsTeach a robot to walk

Each type splits into smaller families. Here's the whole map before we look at each branch:

A tree with machine learning at the top and three branches. Supervised learning learns from labelled examples and splits into regression, which predicts a number such as a house price, and classification, which predicts a category such as spam. Unsupervised learning finds patterns without labels: clustering and dimensionality reduction. Reinforcement learning learns from rewards and is used for games, robots and tuning chatbots.

1. Supervised learning: learning with an answer key

In supervised learning, every training example comes with the correct answer, called the label or target. It's like studying with a book of solved problems: after seeing enough examples, the model can answer new questions by itself.

The inputs are called features. For predicting a house price, the features might be area, bedrooms and location, and the label is the price.

Supervised learning comes in two flavours, depending on what you predict.

Regression: predicting a number

The answer is a quantity: a price, a temperature, a number of sales.

import pandas as pd
from sklearn.linear_model import LinearRegression

houses = pd.DataFrame({
    "area":  [600, 850, 1000, 1200, 1500, 1800],    # square feet
    "price": [30, 42, 50, 61, 74, 90],              # lakh rupees
})

model = LinearRegression()
model.fit(houses[["area"]], houses["price"])        # learn from examples

new_house = pd.DataFrame({"area": [1100]})
print(model.predict(new_house).round(1))            # [54.9]

fit is where learning happens: the model finds the line that best matches area to price. predict uses that line on a house it has never seen.

Classification: predicting a category

The answer is a class: spam or not spam, fraud or genuine, cat, dog or bird.

  • Binary classification has two classes: will this customer cancel, yes or no?
  • Multi-class classification has more: which digit, 0 to 9, is in this image?

Classification models usually give a probability for each class, such as "87% spam", and you decide the cut-off.

More supervised examples: email spam filters, loan approval, disease diagnosis from scans, delivery-time estimates, face recognition.

The catch: labels are expensive. Someone has to mark thousands of emails as spam or label thousands of X-rays, and the model is only as good as those labels.

2. Unsupervised learning: finding hidden patterns

In unsupervised learning, there are no labels. The model looks for structure on its own. It's like being handed a box of mixed buttons and sorting them into piles without being told what the piles should be.

Clustering: grouping similar things

import pandas as pd
from sklearn.cluster import KMeans

customers = pd.DataFrame({
    "visits": [2, 3, 2, 25, 30, 28, 12, 14],
    "spend":  [500, 700, 400, 9000, 12000, 10500, 3000, 3500],
})

kmeans = KMeans(n_clusters=3, n_init=10, random_state=0)
customers["group"] = kmeans.fit_predict(customers)
print(customers["group"].tolist())    # [1, 1, 1, 0, 0, 0, 2, 2]

K-means found three groups: occasional shoppers, loyal big spenders and regular mid-range customers. Nobody told it those groups existed. (The group numbers themselves are arbitrary; only which customers share a number matters.) A marketing team can now send each group a different offer.

Other unsupervised tasks

  • Dimensionality reduction: squeeze many features into a few while keeping the important information, for visualisation or speed. PCA is the classic method.
  • Anomaly detection: learn what "normal" looks like and flag anything unusual, such as a strange login or a faulty machine sensor.
  • Association rules: "people who buy bread and butter often buy jam", used in shop layouts and recommendations.

The catch: with no answer key, it's harder to measure whether the result is "right". You judge it by whether the groups are useful.

3. Reinforcement learning: learning by trial and error

In reinforcement learning (RL), an agent takes actions in an environment and receives rewards or penalties. Over many attempts, it learns a policy: which action to take in each situation to earn the most reward in the long run.

It's how you'd train a dog: no answer key, just treats for good behaviour.

  • A game-playing agent gets +1 for winning and -1 for losing, and plays millions of games against itself.
  • A robot arm gets rewards for picking up objects without dropping them.
  • A recommendation system can treat clicks as rewards.

Reinforcement learning also helps fine-tune large language models so their answers better match what people find helpful, a technique called RLHF (reinforcement learning from human feedback).

The catch: RL needs huge numbers of attempts, so it usually trains in simulations, and it's the hardest type to get working. Most beginners should learn it last.

Semi-supervised and self-supervised learning

These sit between supervised and unsupervised learning:

  • Semi-supervised learning uses a small set of labelled examples plus a large set of unlabelled ones. Label 1,000 X-rays, then let the model learn from 100,000 unlabelled ones too.
  • Self-supervised learning creates labels from the data itself. Hide the next word in a sentence and ask the model to predict it: the real next word is the label, so no human labelling is needed. This is how large language models are pre-trained on huge amounts of text, and why they could be trained at such scale.

How to choose the right type

Ask these questions in order:

  1. Do you need to learn actions through trial and error, with rewards? → Reinforcement learning.
  2. Do you have the correct answers for your past examples? - Yes, and the answer is a number → supervised regression. - Yes, and the answer is a category → supervised classification.
  3. No answers, but you want groups or unusual cases? → Unsupervised learning: clustering or anomaly detection.
  4. A few answers and lots of unlabelled data? → Semi-supervised learning.

Key takeaways

  • Supervised learning learns from labelled examples: regression predicts numbers, classification predicts categories.
  • Unsupervised learning finds structure in unlabelled data: clusters, anomalies, fewer dimensions.
  • Reinforcement learning learns actions from rewards through trial and error.
  • Self-supervised learning creates its own labels from raw data, and is how LLMs are pre-trained.
  • Most real business problems are supervised learning on tables.

Practice

Name the type of machine learning, and for supervised problems say whether it's regression or classification.

  1. Predicting tomorrow's maximum temperature from the past week's weather.
Show the answer

Supervised regression: past data includes the actual temperatures (labels), and the answer is a number.

  1. Splitting 50,000 news articles into topics, with no topics given in advance.
Show the answer

Unsupervised learning: clustering (or topic modelling). There are no labels to learn from.

  1. Flagging credit card transactions as fraud, using past transactions that were marked fraud or genuine.
Show the answer

Supervised classification, specifically binary classification. If no past fraud labels existed, you could use unsupervised anomaly detection instead.

  1. Teaching a program to play a racing game by giving it points for speed and penalties for crashes.
Show the answer

Reinforcement learning: the agent learns from rewards and penalties, not from labelled examples.

  1. Change the house-price example to predict the price of an 1,800 square foot house. Does the result make sense?
Show the answer
print(model.predict(pd.DataFrame({"area": [1800]})).round(1))

It predicts about 89.8 lakh, close to the real 90 lakh in the training data, so the line fits well.

Interview questions

What is the difference between supervised and unsupervised learning?

Supervised learning trains on labelled data, where each input has a known output, to predict outputs for new inputs. Unsupervised learning works on unlabelled data to discover structure, such as clusters or a lower-dimensional representation.

What is the difference between regression and classification?

Both are supervised. Regression predicts a continuous number, such as a price. Classification predicts a discrete category, such as spam or not spam, often via class probabilities.

What is self-supervised learning?

A form of learning where the training labels are generated automatically from the data itself, for example predicting a masked word or the next word in text. It lets models learn from huge unlabelled datasets and is how LLMs are pre-trained.

Give an example where reinforcement learning is the right choice.

Problems involving sequences of decisions with delayed rewards, where correct answers aren't known in advance: game playing, robotics control, traffic-signal timing or resource scheduling. The agent learns a policy by interacting with an environment.

What to learn next

  1. Plan your learning with the machine learning roadmap.
  2. Then set up your machine learning environment and run these examples yourself.