Sub topic 15
Beyond the two: semi-supervised, self-supervised, and reinforcement learning
This chapter assumes you know the difference between supervised and unsupervised learning. It also assumes you can read basic scikit-learn code and know what a loss function and a held-out test set are. Earlier chapters covered those ideas.
Supervised and unsupervised learning are the two main paradigms, but real projects often fall between them or need something different. Three more paradigms come up often enough that you should recognize them: semi-supervised, self-supervised, and reinforcement learning. This chapter explains what each one does, how it relates to the two you already know, and when it fits.
Why the two-way split is not enough
The two-way split is based on one question: does the training data include labels? That question has more than two answers in practice.
- Labels may exist for only a small part of the data.
- Labels may be created automatically from the data itself.
- There may be no fixed dataset at all, only an environment that gives feedback after each action.
Each of these situations leads to a different paradigm. The table summarizes them before we look at each in turn.
| Paradigm | What the training signal is | Typical data | Typical use |
|---|---|---|---|
| Supervised | A human-provided label for every example | Fully labeled table | Spam detection, price prediction |
| Unsupervised | None. The model looks for structure | Unlabeled table | Customer segments, compression |
| Semi-supervised | Labels for a few examples, plus many unlabeled ones | Mostly unlabeled, a small labeled part | Classification when labeling is expensive |
| Self-supervised | Labels derived automatically from the data | Large unlabeled collections such as text | Pretraining language and vision models |
| Reinforcement | A reward received after actions | Interaction with an environment | Games, robotics, control |
Semi-supervised learning
Semi-supervised learning uses a small set of labeled examples together with a larger set of unlabeled examples. It is a good fit when collecting examples is cheap but labeling them is slow or costly. Medical images are a typical case. Scans are plentiful, but each label needs an expert's time.
The unlabeled data helps because it shows the shape of the input space. If two groups of points are clearly separated, a decision boundary should probably run through the gap between them, even if only one point in each group has a label.
Self-training
The simplest method is self-training, also called pseudo-labeling.
- Train a model on the labeled examples.
- Predict labels for the unlabeled examples.
- Keep the predictions the model is most confident about and treat them as if they were true labels.
- Retrain on the labeled and pseudo-labeled examples.
- Repeat until no confident predictions remain.
scikit-learn provides this as SelfTrainingClassifier. Unlabeled examples are marked with the label -1. The example below hides 90% of the iris labels and compares a model trained on the few remaining labels with a self-training model that also sees the unlabeled rows.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.semi_supervised import SelfTrainingClassifier
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
# Hide 90% of the training labels. -1 means "unlabeled".
rng = np.random.default_rng(0)
hidden = rng.random(len(y_train)) < 0.9
y_partial = y_train.copy()
y_partial[hidden] = -1
labeled = ~hidden
print("labeled examples:", labeled.sum(), "of", len(y_train))
# Baseline: use only the labeled examples.
baseline = LogisticRegression(max_iter=200)
baseline.fit(X_train[labeled], y_train[labeled])
print("labeled only:", baseline.score(X_test, y_test))
# Self-training: also use the unlabeled examples.
self_training = SelfTrainingClassifier(
LogisticRegression(max_iter=200), threshold=0.8
)
self_training.fit(X_train, y_partial)
print("self-training:", self_training.score(X_test, y_test))The test labels are never used during training. With so few labels, the result can change from one random split to another. Treat a single run as an illustration, not as proof that self-training always wins.
Failure modes
Semi-supervised learning can also make a model worse.
- Confirmation bias. If the model makes a confident mistake, that mistake becomes a pseudo-label. Retraining then reinforces it.
- Class imbalance. Confident predictions often come from the majority class, so the pseudo-labeled set can drift further toward it.
- Distribution mismatch. If the unlabeled data comes from a different source than the labeled data, it can pull the model in the wrong direction.
Self-supervised learning
Self-supervised learning creates its own labels from the data. No human annotates anything. The task is set up so that part of each example becomes the target and the rest becomes the input. This is why it is sometimes described as supervised learning with free labels.
Some common setups:
- Next-token prediction. Given the words so far, predict the next word. The text itself supplies the answer.
- Masked prediction. Hide some words in a sentence, or some patches of an image, and predict what was hidden.
- Contrastive learning. Two altered versions of the same image should get similar representations, and versions of different images should get different ones.
The loss function and training loop are the same as in supervised learning. Only the origin of the labels is different.
A small example of generated labels
The next snippet builds a self-supervised dataset from a plain list of numbers. The input is three consecutive values and the target is the value that follows. No one labeled anything.
import numpy as np
from sklearn.linear_model import LinearRegression
series = np.sin(np.linspace(0, 20, 200))
window = 3
X = np.array([series[i:i + window] for i in range(len(series) - window)])
y = series[window:] # the "label" is simply the next value
split = 150
model = LinearRegression().fit(X[:split], y[:split])
print("test R^2:", model.score(X[split:], y[split:]))The split is by position, not random, because the data is ordered in time. A random split would let the model train on values that sit between test values, which makes the score too optimistic.
Why it matters
The main use of self-supervised learning is pretraining. A model first learns general-purpose representations from a very large unlabeled collection. It is then fine-tuned with a small labeled set for a specific task. Large language models and many modern vision models follow this pattern. The pretraining step plays a role similar to unsupervised learning, since it learns structure without human labels. The difference is that the training objective is a prediction task with a definite right answer.
Reinforcement learning
Reinforcement learning (RL) differs the most from the other paradigms. There is no table of examples. An agent interacts with an environment. At each step the agent observes a state, chooses an action, and receives a reward, a number that says how good the outcome was. The goal is to learn a policy, which is a rule for choosing actions, that maximizes the total reward over time.
Three features set RL apart.
- Delayed feedback. A move in a game may only prove good or bad many steps later. The agent must work out which earlier actions deserve credit. This is called the credit assignment problem.
- Data depends on the agent. The agent's own choices decide which states it sees. A poor policy gathers poor data.
- Exploration versus exploitation. The agent must sometimes try unfamiliar actions to learn about them, and sometimes repeat the best known action to collect reward.
A minimal bandit example
The simplest RL setting is a multi-armed bandit. There is one state and several actions, called arms, each with an unknown average reward. The agent uses an epsilon-greedy policy: with probability epsilon it explores a random arm, otherwise it picks the arm with the best estimate so far.
import numpy as np
rng = np.random.default_rng(0)
true_means = np.array([0.2, 0.5, 0.8]) # unknown to the agent
n_arms = len(true_means)
estimates = np.zeros(n_arms)
counts = np.zeros(n_arms)
epsilon = 0.1
total_reward = 0.0
for step in range(2000):
if rng.random() < epsilon:
arm = int(rng.integers(n_arms)) # explore
else:
arm = int(np.argmax(estimates)) # exploit
reward = rng.normal(true_means[arm], 0.1)
counts[arm] += 1
# running average of rewards seen for this arm
estimates[arm] += (reward - estimates[arm]) / counts[arm]
total_reward += reward
print("estimates:", np.round(estimates, 2))
print("pulls per arm:", counts)
print("average reward:", total_reward / 2000)The estimates move toward the true means, and most pulls go to the best arm. Full RL adds states that change after each action. Methods such as Q-learning and policy gradients handle that case, but the explore-or-exploit trade-off stays the same.
Common errors with rewards
- Reward hacking. The agent finds a way to score high that the designer did not intend. A cleaning robot rewarded for "no visible mess" might learn to hide the mess.
- Sparse rewards. If reward only arrives at the end of a long task, learning can be extremely slow.
- Unsafe exploration. Trying random actions is fine in a simulator and risky on real equipment.
Choosing among the five
Start from what you have, not from what sounds advanced.
- If you have enough labeled examples for the question you are asking, use supervised learning.
- If you have no labels and want to discover groups or compress features, use unsupervised learning.
- If you have a few labels and many unlabeled rows from the same source, try semi-supervised learning, and keep a supervised baseline for comparison.
- If you have a very large unlabeled collection and a prediction task can be derived from it, consider self-supervised pretraining, often by reusing a model that someone has already pretrained.
- If the problem is a sequence of decisions where actions change what happens next, and you can get reward feedback, consider reinforcement learning.
Exercise
You have 50,000 product reviews, but only 300 are labeled as positive or negative. The reviews all come from the same website. Which paradigm would you try first, and what must you compare it against to know it helped?
Show answer
Try semi-supervised learning, for example self-training, since there are few labels and many unlabeled examples from the same source. Compare it against a supervised model trained only on the 300 labeled reviews, with both scored on a separate labeled test set that neither used for training.
Exercise
A model is trained by hiding a random 15% of the words in each sentence and predicting the hidden words from the rest. Which paradigm is this, and where do the labels come from?
Show answer
It is self-supervised learning. The labels are the hidden words themselves, so they come from the data and need no human annotation.
Exercise
In the bandit example, what would happen if epsilon were set to 0, and why is that a problem?
Show answer
The agent would never explore. It would pick whichever arm looked best after its first pulls and keep choosing it. Since estimates start at zero and rewards here are positive on average, it could lock onto a poor arm and never discover that another arm pays more.