Sub topic 5
Multilabel outputs with independent sigmoids
This chapter assumes you know binary logistic regression, the sigmoid function, and binary cross-entropy for a single yes/no target. It also assumes you can read a NumPy array of shape (n_samples, n_labels). The chapter covers the output layer and loss for multilabel problems. Turning scores into predictions and the metrics are covered in later chapters.
The core idea: K separate yes/no questions
In a multilabel problem, each sample can have any subset of K labels. A news article can be tagged politics, economy, and europe at once. The target is a multi-hot row such as [1, 1, 0, 1, 0].
The model therefore answers K binary questions: "Is label k present?" Each question gets its own score (a logit) z_k. Each logit goes through its own sigmoid:
p_k = 1 / (1 + exp(-z_k))
Each p_k lies between 0 and 1 and estimates P(label k is present | x). The values p_1 ... p_K do not interact. They need not sum to 1. They can all be near 0 (no label applies) or all near 1 (every label applies).
Softmax versus sigmoid on the same scores
Softmax makes scores compete for a fixed budget of probability. That is correct when exactly one class is true. It is wrong when several labels can be true at once, because raising one label's probability forces the others down.
import numpy as np
logits = np.array([2.0, 1.0, -1.0])
# Multiclass: softmax makes the scores compete and sum to 1.
exp = np.exp(logits - logits.max())
softmax = exp / exp.sum()
# Multilabel: each score gets its own sigmoid, with no competition.
sigmoid = 1.0 / (1.0 + np.exp(-logits))
print("softmax:", softmax.round(3), "sum =", softmax.sum().round(3))
print("sigmoid:", sigmoid.round(3), "sum =", sigmoid.sum().round(3))
print("multiclass prediction:", softmax.argmax())
print("multilabel prediction:", (sigmoid >= 0.5).astype(int))The softmax output sums to 1 and has a single winner. The sigmoid output sums to about 1.9 here, and the first two labels are both above 0.5. Those are the two behaviors that define multiclass and multilabel outputs.
The loss: binary cross-entropy per label
For one sample with target bits y_k in {0, 1}, the loss is the binary cross-entropy summed or averaged over labels:
loss = -(1/K) * sum_k [ y_k * log(p_k) + (1 - y_k) * log(1 - p_k) ]
Over a batch, you average over samples as well. Each label contributes its own term, so a mistake on one label never changes the loss on another.
The gradient of this loss with respect to each logit is p_k - y_k, scaled by 1/K. The same simple form appears in binary logistic regression. A confident wrong answer produces a large gradient, and a correct one produces a small gradient.
Compute it from logits
Computing log(sigmoid(z)) directly can overflow or return -inf for large |z|. Deep learning libraries therefore offer a combined "BCE with logits" function. This version uses the same algebra:
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def bce_with_logits(z, y):
# Stable form of -(y*log(sigmoid(z)) + (1-y)*log(1-sigmoid(z)))
return np.maximum(z, 0) - z * y + np.log1p(np.exp(-np.abs(z)))
logits = np.array([[2.0, 1.0, -1.0],
[-3.0, 0.5, 2.5]])
Y = np.array([[1, 1, 0],
[0, 0, 1]])
loss = bce_with_logits(logits, Y) # shape (n_samples, n_labels)
print("per-label mean loss:", loss.mean(axis=0).round(3))
print("total mean loss: ", loss.mean().round(3))
# Check against the textbook formula.
p = sigmoid(logits)
naive = -(Y * np.log(p) + (1 - Y) * np.log(1 - p))
print("matches naive formula:", np.allclose(loss, naive))
# Extreme logits: the stable form stays finite.
print("stable, z=1000, y=0:", bce_with_logits(np.array([1000.0]), np.array([0])))Looking at the loss per label before averaging is a useful diagnostic. A label with a much higher mean loss than the others is either hard or poorly represented in the data.
Using it in practice
Some scikit-learn estimators handle a multi-hot target directly. MLPClassifier is one of them. When it sees a 2-D indicator matrix, it uses a sigmoid output layer with one unit per label and a log-loss objective.
from sklearn.datasets import make_multilabel_classification
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
X, Y = make_multilabel_classification(
n_samples=1000, n_features=20, n_classes=5, n_labels=2, random_state=0
)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, random_state=0)
mlp = MLPClassifier(hidden_layer_sizes=(32,), max_iter=500, random_state=0)
mlp.fit(X_train, Y_train)
proba = mlp.predict_proba(X_test)
print("proba shape:", proba.shape)
print("first row:", proba[0].round(3), "sum =", proba[0].sum().round(3))
print("predict shape:", mlp.predict(X_test).shape)The probability matrix has shape (n_samples, n_labels), and its rows do not sum to 1. Most linear models in scikit-learn do not accept a multi-hot target on their own. For those, you wrap them in OneVsRestClassifier, which trains one independent binary model per column. That approach is called binary relevance and is covered in a later chapter. It gives the same independent-probability output, but each label has its own parameters and its own training run. A shared network trains one model whose hidden layers are shared across labels.
What "independent" does and does not mean
The independence applies to the output layer and the loss. The sigmoids do not compete, and the loss is a sum of per-label terms. It does not mean the labels are statistically independent in your data.
- With a shared hidden layer, labels still influence each other through the shared features the network learns.
- With a separate model per label, labels share nothing, so correlated labels such as
tennisandsportcannot help each other. - Because the model assumes each
p_kis a function ofxalone, it can predict combinations that never occur in training, for examplep(sport)=0.1withp(tennis)=0.9.
A sound summary: independent sigmoids model each marginal probability P(y_k = 1 | x). They do not model the joint probability of the whole label set.
Common errors
- Softmax on a multi-hot target. The loss rewards putting all the probability on one label, so the model cannot learn that two labels are both present. Use sigmoid with binary cross-entropy.
argmaxat prediction time.argmaxalways returns exactly one label. It silently discards the multilabel structure. Use a threshold on each probability instead.- Labels as a list of strings or indices. Most libraries expect a binary indicator matrix. Convert with
MultiLabelBinarizerfirst. - Applying a sigmoid twice. If a library's loss expects logits, do not pass probabilities. Applying sigmoid first and then a "with logits" loss gives a flat, weak gradient and slow training.
- Reading
p_kas a calibrated probability. Raw sigmoid outputs are often over- or under-confident, especially for rare labels. Calibration is a separate step. - Ignoring rare labels. With 1,000 samples and a label that appears 10 times, the loss for that label is dominated by negatives, and the model learns to output a low
p_kfor everything. Imbalance handling is covered in a later chapter.
Exercises
Exercise
A model outputs logits [0.0, 0.0, 0.0] for three labels. What are the probabilities under softmax and under per-label sigmoid, and what does each say about the model's belief?
Show answer
Softmax gives [1/3, 1/3, 1/3], which sums to 1 and says "exactly one label is present, and I have no preference". Sigmoid gives [0.5, 0.5, 0.5], which sums to 1.5 and says "each label is present with 50% chance, independently of the others". Under a 0.5 threshold, the sigmoid outputs sit exactly on the boundary.
Exercise
For a sample with target [1, 0] and logits [3.0, 3.0], which label contributes more to the binary cross-entropy loss, and why? Give the gradient with respect to each logit (use sigmoid(3.0) ≈ 0.953).
Show answer
Label 2 contributes more. Its target is 0 but the model gives it probability 0.953, so the term is -log(1 - 0.953) ≈ 3.05. Label 1 is correct, and its term is -log(0.953) ≈ 0.048. The gradients are p - y: about -0.047 for label 1 (a small push upward) and about +0.953 for label 2 (a large push downward). Both are divided by K if the loss is averaged over labels.