Deep Learning Notes - 3: Classification Models and Introduction to Deep Neural Networks - MuxiaoWFSkip to main content
This page was machine-translated and may contain errors or omissions. / 本页面为机器翻译,可能存在错漏。

Deep Learning Notes - 3: Classification Models and Introduction to Deep Neural Networks

Deep Learning Notes - 3, covering classification models (discriminant functions, logistic regression, softmax) and deep neural networks (activation functions, transfer learning, mixture density networks). Corresponding to Chapters 5-6 of "Deep Learning: Fundamentals and Concepts".

Mon Sep 01 2025
7489 words · 40 minutes

Part 3/8 of the series ← Previous | Next | Glossary

It is recommended to read Part 1 and Part 2 first. This part explains how to solve classification problems (from linear classifiers to neural networks), and why deep networks are stronger than shallow ones.

Chapter 5 Single-Layer Networks: Classification

In machine learning, the classification problem is one of the most fundamental and important tasks. This chapter introduces the basic principles of linear classification models, including core concepts such as discriminant functions, decision theory, generative classifiers, and discriminative classifiers.

Discriminant Functions

A discriminant function (a function that scores each class) defines a function yk(x)y_k(\mathbf{x}) for each class CkC_k. For an input x\mathbf{x}, it assigns it to the class with the highest discriminant function value:

assign x to Ck if yk(x)>yj(x) for all jk\text{assign } \mathbf{x} \text{ to } C_k \text{ if } y_k(\mathbf{x}) > y_j(\mathbf{x}) \text{ for all } j \neq k

Binary classification:

For a binary classification problem, we define the discriminant function y(x)=wTx+w0y(\mathbf{x}) = \mathbf{w}^T \mathbf{x} + w_0. The decision boundary (the “dividing line” that separates different classes) is given by y(x)=0y(\mathbf{x}) = 0 , which is a (D1)(D-1)-dimensional hyperplane (a “plane” in high-dimensional space — a straight line in 2D space, an ordinary plane in 3D space, and a hyperplane in even higher dimensions).

To simplify the notation, we often introduce an extra “input” x0=1x_0 = 1, and define the augmented weight vector w~=(w0,w)\tilde{\mathbf{w}} = (w_0, \mathbf{w}) and the augmented input vector x~=(x0,x)\tilde{\mathbf{x}} = (x_0, \mathbf{x}), so that:

y(x)=w~Tx~y(\mathbf{x}) = \tilde{\mathbf{w}}^T \tilde{\mathbf{x}}

In this case, the decision boundary passes through the origin of the augmented input space.

Binary classification

Binary classification

  • Red line: represents the decision boundary y(x)=0y(\mathbf{x}) = 0, and divides the entire space into two regions: R1R_1: the region where y>0y > 0 and R2R_2: the region where y<0y < 0
  • Green vector w\mathbf{w}: represents the weight vector (the normal vector of the decision boundary)
  • Blue vector x\mathbf{x}: represents the input sample
  • Black vector x\mathbf{x}_\perp: represents the projection of the input onto the decision boundary
  • w0w\frac{-w_0}{||\mathbf{w}||} is the distance from the origin to the decision boundary (the offset of the decision boundary)

Multi-class:

  • One-vs-rest classifier: train one classifier for each class CkC_k, distinguishing CkC_k from “not CkC_k”. This approach produces ambiguous regions, where some points are classified as positive by multiple classifiers or as negative by all classifiers.
  • One-vs-one classifier: train a binary classifier for each pair of classes, requiring a total of K(K1)/2K(K-1)/2 classifiers. A new sample’s class is decided by majority voting. This approach also produces ambiguous regions.

Multi-class (left: one-vs-rest classifier, right: one-vs-one classifier)

Multi-class (left: one-vs-rest classifier, right: one-vs-one classifier)

To avoid these problems, we adopt a single KK-class discriminant function consisting of KK linear functions:

yk(x)=wkTx+wk0,k=1,,Ky_k(\mathbf{x}) = \mathbf{w}_k^T \mathbf{x} + w_{k0}, \quad k=1,\dots,K

Assign x\mathbf{x} to the class CkC_k that maximizes yk(x)y_k(\mathbf{x}).

The decision boundary between classes CkC_k and CjC_j is defined by yk(x)=yj(x)y_k(\mathbf{x}) = y_j(\mathbf{x}), that is:

(wkwj)Tx+(wk0wj0)=0(\mathbf{w}_k - \mathbf{w}_j)^T \mathbf{x} + (w_{k0} - w_{j0}) = 0

This is a (D1)(D-1)-dimensional hyperplane.

Properties of the decision regions: The decision region RkR_k of such a KK-class linear discriminant function (i.e., the set of all points assigned to CkC_k) is simply connected and convex . This means that if any two points xA\mathbf{x}_A and xB\mathbf{x}_B within the region are connected, all points on the line segment between them also lie within the region.


**1-of-K encoding:**

In classification problems, the target variable tt is used to represent the class label.

  • Binary classification: use binary encoding, t{0,1}t \in \{0, 1\}. t=1t=1 indicates class C1C_1, and t=0t=0 indicates class C2C_2.
  • Multi-class (K>2K>2): use 1-of-K encoding (also called one-hot encoding). The target vector t\mathbf{t} is a vector of length KK , such that if the class is CjC_j, then tj=1t_j=1 and the remaining elements are 0.

For example, for K=5K=5 classes, the target vector for class 2 is:

t=(0,1,0,0,0)T\mathbf{t} = (0, 1, 0, 0, 0)^T

We can interpret tkt_k as the probability that the class is CkC_k (the extreme case where the value is 0 or 1).


Decision Theory

Decision theory helps us make optimal classification decisions given the posterior probability (the probability p(Ckx)p(C_k|\mathbf{x}) that, after seeing the data x\mathbf{x}, it belongs to a certain class), especially when different types of errors have different costs.

The loss matrix LkjL_{kj} defines the cost incurred when a sample whose true class is CkC_k is misclassified as CjC_j.

Lkj=(0L21L120)=(actually true, predicted trueactually true, predicted falseactually false, predicted trueactually false, predicted false)L_{kj} = \begin{pmatrix} 0 & L_{21} \\ L_{12} & 0 \end{pmatrix} = \begin{pmatrix} \text{actually true, predicted true} & \text{actually true, predicted false} \\ \text{actually false, predicted true} & \text{actually false, predicted false} \end{pmatrix}

where LkjL_{kj} represents the cost of “true class is CkC_k but predicted as CjC_j”. The diagonal entries are the cost of correct predictions (0), and the off-diagonal entries are the cost of making an error. L21L_{21} is a “miss” (true predicted as false), and L12L_{12} is a “false alarm” (false predicted as true). For example, in cancer screening: the cost L21L_{21} of misclassifying a cancer patient (C2C_2) as healthy (C1C_1) (false negative) may be far higher than the cost L12L_{12} of misclassifying a healthy person (C1C_1) as having cancer (C2C_2 ) (false positive).

Minimizing Expected Loss

The optimal decision is to choose the class that minimizes the expected loss. For an input x\mathbf{x}, the expected loss of classifying it as CjC_j is:

k=1KLkjp(Ckx)\sum_{k=1}^K L_{kj} p(C_k|\mathbf{x})

We should choose the class jj that minimizes this expected loss.

For a two-class problem, this is equivalent to comparing the posterior probability against a threshold determined by the loss ratio.


Reject Option

Sometimes, when the classifier is uncertain about its prediction, it is better to choose to “reject” the classification and hand the sample over to a human or another, more complex system.

We can set a threshold θ\theta, and if the maximum posterior probability p(Ckx)p(C_k|\mathbf{x}) is less than or equal to θ\theta, the sample is rejected.

  • θ=1\theta = 1: all samples are rejected.
  • θ<1/K\theta < 1/K: no samples are rejected (KK is the number of classes).

Adjusting θ\theta controls the proportion of rejected samples.

Reject option

Reject option

This criterion can also be extended to the case where the reject decision itself has a cost (loss).


Inference and Decision

Solving a classification problem is usually divided into two stages:

  1. Inference stage: learn the model from the training data to obtain the posterior probability p(Ckx)p(C_k|\mathbf{x}).
  2. Decision stage: use the posterior probability and decision theory (such as minimizing expected loss) to make the final class assignment.

Another approach is to directly learn a function from input x\mathbf{x} to a decision, called a discriminant function. The linear discriminant functions discussed in this chapter belong to this approach.

Three ways to solve the decision problem (in decreasing order of complexity):

  1. Generative model: first model the class-conditional density p(xCk)p(\mathbf{x}|C_k) (given the class, what the data looks like) and the prior probability p(Ck)p(C_k) (before seeing the data, the probability that each class occurs), then use Bayes’ theorem (deriving the probability of “cause → effect” from “effect → cause”) to compute the posterior p(Ckx)p(C_k|\mathbf{x}) . First understand what each class “looks like”, then judge which class a new sample most resembles based on its features. (A doctor diagnosing a disease first learns in detail the symptomatic characteristics of each disease, then looks at which symptoms the patient exhibits to determine the most likely disease.)
  2. Discriminative model: directly model the posterior probability p(Ckx)p(C_k|\mathbf{x}). Directly learn how to distinguish between different classes, without caring what each class specifically “looks like” . (To distinguish apples from oranges, you only need to know that apples are redder and oranges are more orange; you do not need to know all the biological characteristics of apples and oranges in detail.)
  3. Direct mapping: directly learn a function from x\mathbf{x} to a class label, such as the linear discriminant function in this chapter. Directly learn a decision rule without computing probabilities, outputting the class directly. (A simple rule: ” if an email contains ‘free’ it is spam”.)

Classifier Accuracy

The simplest performance measure is classification accuracy, i.e., the proportion of correctly classified test samples. However, when different errors have different costs, accuracy alone is insufficient.

Confusion Matrix

The confusion matrix provides a more detailed view of classification results. For a two-class problem, its form is as follows: (same as the loss matrix)

Predicted: HealthyPredicted: Cancer
Actual: HealthyNTNN_{TN}NFPN_{FP}
Actual: CancerNFNN_{FN}NTPN_{TP}
  • True Negative (TN): correctly predicted as healthy.
  • False Positive (FP): incorrectly predicted as cancer (Type I error).
  • False Negative (FN): incorrectly predicted as healthy (Type II error).
  • True Positive (TP): correctly predicted as cancer.

ROC Curve

The ROC curve is a powerful tool for evaluating the performance of a binary classifier. It plots the True Positive Rate (TPR) against the False Positive Rate (FPR).

  • Precision: NTPNTP+NFP\frac{N_{TP}}{N_{TP} + N_{FP}}
  • True Positive Rate (TPR) = Recall: NTPNTP+NFN\frac{N_{TP}}{N_{TP} + N_{FN}}
  • False Positive Rate (FPR): NFPNFP+NTN\frac{N_{FP}}{N_{FP} + N_{TN}}
  • False Discovery Rate: NFPNTP+NFP\frac{N_{FP}}{N_{TP} + N_{FP}}

By changing the threshold of the classification decision, different points on the ROC curve can be obtained.

  • Ideal classifier: the closer the point on the ROC curve is to the top-left corner, the better.
  • Random classifier: the ROC curve is a diagonal line from the bottom-left to the top-right corner.
  • Area Under the Curve (AUC): a single number that quantifies classifier performance. AUC = 0.5 indicates random guessing, and AUC = 1.0 indicates perfect classification.

The F-score is the harmonic mean of precision and recall, used to comprehensively evaluate classifier performance:

F=2×precision×recallprecision+recall=2NTP2NTP+NFP+NFNF = 2 \times \frac{\text{precision} \times \text{recall}}{\text{precision} + \text{recall}} = \frac{2N_{TP}}{2N_{TP} + N_{FP} + N_{FN}}
Exercise 1

In the validation set of a watermelon classification task, there are 10 examples in total, of which 3 examples are labeled “1”, indicating that the example is a good watermelon; and 7 examples are labeled “0”, indicating that the example is not a good watermelon. Due to limited learning ability, the method can only produce a classifier with accuracy 0.8 on the validation set.

  1. To obtain the best precision on the validation set, what prediction should the classifier make? What are the recall and F1 at this point?

An accuracy of 0.8 means 2 will be predicted incorrectly. To maximize precision P=TPTP+FPP = \frac{TP}{TP + FP}, the incorrect predictions should be placed in FN, i.e., predict positive examples as negative. At this point recall R=TPTP+FN=13R = \frac{TP}{TP + FN} = \frac{1}{3}, F1=2PRP+R=2TPN+TPTN=12F_{1} = \frac{2*P*R}{P + R} = \frac{2*TP}{N + TP - TN} = \frac{1}{2}

  1. To obtain the best recall on the validation set, what prediction should the classifier make? What are the precision and F1 at this point?

To maximize recall R=TPTP+FNR = \frac{TP}{TP + FN}, the incorrect predictions should be placed in FP, i.e., predict negative examples as positive. At this point precision P=TPTP+FP=35P = \frac{TP}{TP + FP} = \frac{3}{5}, F1=2PRP+R=2TPN+TPTN=34F_{1} = \frac{2*P*R}{P + R} = \frac{2*TP}{N + TP - TN} = \frac{3}{4}

Exercise 2

Suppose a dataset contains 8 examples, whose corresponding labels and the learner’s output values (sorted from largest to smallest) are shown in the table below. The task is a binary classification task, where a label of 1 or 0 indicates the true label being positive or negative. The learner’s output value represents the learner’s confidence that the example is positive (the probability that it considers the example to be positive).

ExampleX1X2X3X4X5X6X7X8
Label11010100
Learner output0.810.740.620.530.440.350.250.21
  1. Compute the coordinates of each endpoint on the P-R curve and plot it.

Predict each example as positive in descending order of output value

ID12345678
TP12233444
FP00112234
FN32211000
TN44332210
P110.6666670.750.60.6666670.5714290.5
R0.250.50.50.750.75111
  1. Compute the coordinates of each endpoint on the ROC curve and plot it; compute the AUC (Area Under the ROC Curve).
TPR0.250.50.50.750.75111
FPR000.250.250.50.50.751

AUC=0.5*0.25+0.75*0.25+1*0.5=0. 8125


Generative Classifiers

Generative classifiers follow the “generative model” path of decision theory (method 1 of “Inference and Decision” above): first model the data distribution p(xCk)p(\mathbf{x}|C_k) (class-conditional density) of each class and the prior probability p(Ck)p(C_k) of the class, then use Bayes’ theorem to compute the posterior probability p(Ckx)p(C_k|\mathbf{x}), and finally make a decision.

Continuous Inputs (Gaussian Class-Conditional Density)

Assume the input x\mathbf{x} is continuous, and the data of each class follows a Gaussian distribution (the normal distribution — see Part 2). This is the most common case.

  • Class-conditional density: for class CkC_k, we have

    p(xCk)=N(xμk,Σk)p(\mathbf{x}|C_k) = \mathcal{N}(\mathbf{x} | \mathbf{\mu}_k, \mathbf{\Sigma}_k)

    where μk\mathbf{\mu}_k is the mean vector (the “center” of the data), and Σk\mathbf{\Sigma}_k is the covariance matrix (describing the “shape” and “orientation” of the data — the correlations between dimensions).

  • Prior probability: p(Ck)p(C_k) can be estimated from the training data, for example, p(Ck)=Nk/Np(C_k) = N_k / N, where NkN_k is the number of samples in class CkC_k, and NN is the total number of samples.

According to Bayes’ theorem, the posterior probability is:

p(Ckx)=p(xCk)p(Ck)p(x)p(C_k|\mathbf{x}) = \frac{p(\mathbf{x}|C_k) p(C_k)}{p(\mathbf{x})}

where p(x)=jp(xCj)p(Cj)p(\mathbf{x}) = \sum_j p(\mathbf{x}|C_j) p(C_j) is the normalization constant.

To classify, we compare the posterior probabilities of different classes. Since the denominator p(x)p(\mathbf{x}) is the same for all classes, we only need to compare the numerator p(xCk)p(Ck)p(\mathbf{x}|C_k) p(C_k). Equivalently, we can compare their logarithms:

ak(x)=lnp(xCk)+lnp(Ck)a_k(\mathbf{x}) = \ln p(\mathbf{x}|C_k) + \ln p(C_k)

This ak(x)a_k(\mathbf{x}) is called the evidence or activation. We assign x\mathbf{x} to the class that maximizes ak(x)a_k(\mathbf{x}).


For a two-class problem, we define the discriminant function:

a(x)=a1(x)a2(x)=lnp(xC1)p(C1)p(xC2)p(C2)a(\mathbf{x}) = a_1(\mathbf{x}) - a_2(\mathbf{x}) = \ln \frac{p(\mathbf{x}|C_1) p(C_1)}{p(\mathbf{x}|C_2) p(C_2)}

If a(x)>0a(\mathbf{x}) > 0, assign to C1C_1; otherwise assign to C2C_2. The decision boundary is given by a(x)=0a(\mathbf{x}) = 0.


Linear Discriminant Analysis (LDA) is an important special case that assumes all classes share the same covariance matrix (i.e., the data of each class has the same “shape” and “orientation”, only the “center position” differs): Σ1=Σ2==Σ\mathbf{\Sigma}_1 = \mathbf{\Sigma}_2 = \dots = \mathbf{\Sigma}.

Under this assumption, substituting the Gaussian density expression into ak(x)a_k(\mathbf{x}) and performing the algebra, we find that the quadratic terms in x\mathbf{x} cancel out.

Ultimately, the discriminant function ak(x)a_k(\mathbf{x}) becomes a linear function of x\mathbf{x}:

ak(x)=wkTx+wk0a_k(\mathbf{x}) = \mathbf{w}_k^T \mathbf{x} + w_{k0}

where

wk=Σ1μk,wk0=12μkTΣ1μk+lnp(Ck)\mathbf{w}_k = \mathbf{\Sigma}^{-1} \mathbf{\mu}_k, \quad w_{k0} = -\frac{1}{2} \mathbf{\mu}_k^T \mathbf{\Sigma}^{-1} \mathbf{\mu}_k + \ln p(C_k)

Since the discriminant function is linear, the decision boundary is a hyperplane, hence the name “Linear Discriminant Analysis”.

Quadratic Discriminant Analysis: if we do not assume that all classes share the same covariance matrix, i.e., Σk\mathbf{\Sigma}_k can differ, then in the expression for ak(x)a_k(\mathbf{x}) , the quadratic terms in x\mathbf{x} will not cancel out.

In this case, the discriminant function ak(x)a_k(\mathbf{x}) is a quadratic function of x\mathbf{x}, and the decision boundary is a quadratic surface (such as an ellipse, hyperbola, etc.).

Quadratic Discriminant Analysis is more flexible than Linear Discriminant Analysis, but it requires estimating more parameters, so it may overfit on small datasets.


Discrete Inputs

When the input x\mathbf{x} is a discrete variable, a different class-conditional density model is needed.

A common example is the Naive Bayes classifier (“naive” because it makes a bold simplifying assumption), which assumes that, conditioned on class CkC_k, the input features xix_i are conditionally independent (once the class is known, the value of one feature does not affect the value of another feature):

p(xCk)=i=1Dp(xiCk)p(\mathbf{x}|C_k) = \prod_{i=1}^D p(x_i|C_k)

For binary inputs (xi{0,1}x_i \in \{0,1\}), p(xiCk)p(x_i|C_k) is usually modeled with a Bernoulli distribution.

Although the “naive” assumption (feature independence) rarely holds in reality, the Naive Bayes classifier often performs well in practice (such as in text classification).


Discriminative Classifiers

Discriminative classifiers follow the “discriminative model” path of decision theory (method 2 above): they directly model the posterior probability p(Ckx)p(C_k|\mathbf{x}), rather than first modeling the class-conditional density.


Fixed Basis Functions

When the decision boundary of the data is not a straight line (or hyperplane), a linear model cannot handle it well. To model nonlinear decision boundaries, we can map the original input x\mathbf{x} to a feature space ϕ(x)\mathbf{\phi}(\mathbf{x}) composed of fixed nonlinear basis functions (pre-defined nonlinear transformation functions).

Lego bricks vs. custom parts: fixed basis functions are like a pre-built set of Lego bricks — you can only assemble using the existing blocks, whether or not they fit your data. The advantage is easy assembly; the disadvantage is that when you encounter a special shape, the bricks do not match. The neural networks discussed later are like a machine that can “cast parts” on the spot — its basis function parameters are learnable and can automatically adjust their shape according to the data.

Specifically, the original input data x\mathbf{x} is mapped through some fixed nonlinear functions ϕ(x)\mathbf{\phi}(\mathbf{x}) to a new feature space, where the originally complex nonlinear relationship may become linearly separable.

Then, we assume that the posterior probability is a nonlinear transformation of a linear function of these features.


Logistic Regression

Binary classification:

We directly assume that the posterior probability of class C1C_1 has the following form:

p(C1x)=σ(a(x))p(C_1|\mathbf{x}) = \sigma(a(\mathbf{x}))

where σ()\sigma(\cdot) is the logistic sigmoid function — which we will see frequently:

σ(a)=11+exp(a)\sigma(a) = \frac{1}{1 + \exp(-a)}

and a(x)a(\mathbf{x}) is a linear function of x\mathbf{x} (or a linear function in the feature space ϕ(x)\mathbf{\phi}(\mathbf{x})):

a(x)=wTϕ(x)+w0a(\mathbf{x}) = \mathbf{w}^T \mathbf{\phi}(\mathbf{x}) + w_0

Therefore,

p(C1x)=σ(wTϕ(x)+w0)p(C_1|\mathbf{x}) = \sigma(\mathbf{w}^T \mathbf{\phi}(\mathbf{x}) + w_0)

The posterior probability of the other class is p(C2x)=1p(C1x)p(C_2|\mathbf{x}) = 1 - p(C_1|\mathbf{x}).

logistic sigmoid function (red)

The S-shaped curve of the logistic sigmoid function (red), mapping a real number a to the (0,1) interval

Parameter learning: learn the weights w\mathbf{w} through Maximum Likelihood Estimation (MLE, choosing the set of parameters that maximizes the probability of the observed data).

For the training set {ϕn,tn}\{\mathbf{\phi}_n, t_n\} (where tn{0,1}t_n \in \{0,1\} is 1-of-K encoding), the likelihood function is:

p(tw)=n=1Np(C1ϕn)tnp(C2ϕn)1tn=n=1Nyntn(1yn)1tnp(\mathbf{t}|\mathbf{w}) = \prod_{n=1}^N p(C_1|\mathbf{\phi}_n)^{t_n} p(C_2|\mathbf{\phi}_n)^{1-t_n} = \prod_{n=1}^N y_n^{t_n} (1-y_n)^{1-t_n}

where yn=p(C1ϕn)=σ(wTϕn+w0)y_n = p(C_1|\mathbf{\phi}_n) = \sigma(\mathbf{w}^T \mathbf{\phi}_n + w_0).

Maximizing the likelihood is equivalent to minimizing the cross-entropy (a measure of the difference between two probability distributions — the smaller it is, the more accurate the prediction) error function:

E(w)=n=1N[tnlnyn+(1tn)ln(1yn)]E(\mathbf{w}) = -\sum_{n=1}^N \left[ t_n \ln y_n + (1-t_n) \ln (1-y_n) \right]

This error function can be minimized by optimization algorithms such as gradient descent (updating parameters along the direction of fastest error decrease).


**Multi-class:**

For K>2K>2 classes, we use the softmax function (also called the normalized exponential function — it converts a set of arbitrary real numbers into a probability distribution, so that all outputs are positive and sum to 1; we will also see this frequently later) to convert the KK linear activations (the weighted input value of a certain neuron in the network) aka_k into posterior probabilities.

Define the activation of the kk-th class as:

ak(x)=wkTϕ(x)+wk0a_k(\mathbf{x}) = \mathbf{w}_k^T \mathbf{\phi}(\mathbf{x}) + w_{k0}

Then the posterior probability is:

p(Ckx)=exp(ak(x))j=1Kexp(aj(x))softmax(ak(x))p(C_k|\mathbf{x}) = \frac{\exp(a_k(\mathbf{x}))}{\sum_{j=1}^K \exp(a_j(\mathbf{x}))} \equiv \text{softmax}(a_k(\mathbf{x}))

The softmax function ensures that all p(Ckx)p(C_k|\mathbf{x}) lie in the (0,1) interval and sum to 1.

Suppose we have activations for three classes: a=[2.0,1.0,0.1]\mathbf{a} = [2.0, 1.0, 0.1]

Computation: exp(2.0)=7.39\exp(2.0) = 7.39, exp(1.0)=2.72\exp(1.0) = 2.72, exp(0.1)=1.11\exp(0.1) = 1.11, sum = 7.39+2.72+1.11=11.227.39 + 2.72 + 1.11 = 11.22

Softmax output: p(C1x)=7.3911.22=0.658p(C_1|\mathbf{x}) = \frac{7.39}{11.22} = 0.658, p(C2x)=2.7211.22=0.242p(C_2|\mathbf{x}) = \frac{2.72}{11.22} = 0.242, p(C3x)=1.1111.22=0.099p(C_3|\mathbf{x}) = \frac{1.11}{11.22} = 0.099


Parameter learning: again use maximum likelihood estimation.

For the target vector tn\mathbf{t}_n (1-of-K encoding), the likelihood is:

p(TW)=n=1Nk=1Kp(Ckϕn)tnkp(\mathbf{T}|\mathbf{W}) = \prod_{n=1}^N \prod_{k=1}^K p(C_k|\mathbf{\phi}_n)^{t_{nk}}

where tnkt_{nk} is the kk-th element of tn\mathbf{t}_n.

This corresponds to minimizing the multi-class cross-entropy error:

E(W)=n=1Nk=1KtnklnynkE(\mathbf{W}) = -\sum_{n=1}^N \sum_{k=1}^K t_{nk} \ln y_{nk}

where ynk=p(Ckϕn)y_{nk} = p(C_k|\mathbf{\phi}_n).

If the class-conditional density p(xCk)p(\mathbf{x}|C_k) belongs to the exponential family distribution, and all classes share the same basis function ϕ(x)\mathbf{\phi}(\mathbf{x}) , then the resulting posterior probability p(Ckx)p(C_k|\mathbf{x}) exactly has the form of softmax.


Probit Regression

Probit regression is another discriminative model, based on a “noisy threshold” model.

  • Compute a linear activation a=wTϕ(x)+w0a = \mathbf{w}^T \mathbf{\phi}(\mathbf{x}) + w_0.
  • Assume there is a random threshold θ\theta with probability density p(θ)p(\theta).
  • If a>θa > \theta, predict t=1t=1; otherwise predict t=0t=0.

Then, the probability of predicting t=1t=1 is the probability that aa is greater than the random threshold θ\theta, that is:

p(t=1a)=ap(θ)dθ=Φ(a)p(t=1|a) = \int_{-\infty}^a p(\theta) d\theta = \Phi(a)

where Φ(a)\Phi(a) is the cumulative distribution function (CDF) of p(θ)p(\theta) — the cumulative probability from negative infinity to aa (see Part 2).

If p(θ)p(\theta) is the standard normal distribution N(0,1)N(0,1), then Φ(a)\Phi(a) is called the probit function. It has a shape similar to the logistic sigmoid function, but with slightly different tails.

Reject option

Reject option

On the left is the probability density p(θ)p(\theta) of the threshold θ\theta (blue), and on the right is its cumulative distribution function Φ(a)\Phi(a) (red). The figure illustrates how p(t=1a)p(t=1|a) is determined by the cumulative area of p(θ)p(\theta)


Chapter 5 Summary

One-sentence version: The essence of the classification problem is to draw a line (or a surface) to separate data of different classes. How is this line drawn? It can be drawn directly (discriminant function), or by first understanding what each class of data looks like and then drawing (generative model), or by directly learning a probability (discriminative model). How well it is drawn is measured by metrics such as ROC and AUC.

Knowledge map:

Discriminant functions
├── Binary classification: a linear function y = w^T x + w0, decision boundary is a hyperplane
└── Multi-class: K linear functions, softmax / one-vs-rest / one-vs-one
Decision theory
├── Loss matrix: different error types have different costs (e.g., misclassifying cancer vs normal)
├── Minimize expected loss: choose the class that minimizes expected loss
└── Reject option: hand to human when uncertain
Three classification approaches
├── Generative model: first learn p(x|Ck) and p(Ck), then use Bayes' theorem
│ ├── Linear Discriminant Analysis (LDA): shared covariance → linear boundary
│ └── Quadratic Discriminant Analysis (QDA): different covariance → quadratic boundary
├── Discriminative model: directly learn p(Ck|x)
│ ├── Logistic regression (binary): sigmoid + cross-entropy
│ └── softmax classifier (multi-class): softmax + multi-class cross-entropy
└── Direct mapping: directly learn x → class label
Performance evaluation
├── Confusion matrix: TP / FP / FN / TN
├── ROC curve: TPR vs FPR, closer to top-left is better
└── AUC / F-score: single number summarizing classifier performance

Chapter 6 Deep Neural Networks

In the previous chapter, we learned about linear regression and classification models, which are usually based on a linear combination of fixed nonlinear basis functions of the input. For example, a classification model can be expressed as:

y(x,w)=f(j=1Mwjϕj(x)+w0)y(\mathbf{x}, \mathbf{w}) = f\left( \sum_{j=1}^M w_j \phi_j(\mathbf{x}) + w_0 \right)

where ϕj(x)\phi_j(\mathbf{x}) is a pre-defined basis function (such as polynomial, Gaussian, etc.), and f()f(\cdot) is the output activation function (such as the sigmoid function).

Such models are theoretically “universal approximators” — with enough suitable basis functions, they can approximate any nonlinear function. However, they face severe limitations in practice, especially in high-dimensional input spaces.


Limitations of Fixed Basis Functions

Curse of Dimensionality

When the number of input variables DD increases, the complexity of the fixed basis function approach rises sharply. This is not just a theoretical problem — it fundamentally limits the feasibility of fixed basis function methods on high-dimensional data.

  • Polynomial regression: the number of parameters of a third-order polynomial in DD-dimensional space grows as O(D3)O(D^3). For high-dimensional data (such as images), this leads to an explosion in the number of parameters.
  • Grid-based classifier: if we divide the input space into a regular grid, where each grid corresponds to a basis function, then the number of grids grows exponentially with dimension DD — each additional dimension doubles the number of grids. In a 10-dimensional space with just 10 bins per dimension, we would need 101010^{10} (10 billion) bins, far exceeding the number of samples in any practical dataset.

Curse of dimensionality

The growth trend of the number of small bins when divided into grids in 1D, 2D, and 3D spaces. In high-dimensional space, most grids are empty, causing the model to fail to classify new samples

This shows that if the basis functions are fixed in advance and uniformly distributed in the input space, then in high-dimensional cases they become extremely sparse and cannot effectively utilize the limited training data.

Our intuition in low-dimensional space often fails in high-dimensional space. For example:

  • Volume distribution of a hypersphere: in high-dimensional space, the volume of a unit hypersphere is almost entirely concentrated in a thin shell near the surface. This means most points are “far from the center” — imagine a 100-dimensional ball where 99% of the volume is in a thin shell less than 1% of the radius from the surface.
  • Probability mass of a Gaussian distribution: the probability mass of a multidimensional Gaussian distribution is also concentrated on a thin shell at a certain specific radius, rather than near the origin — this is completely different from the intuition in a 2D bell curve where “the closer to the center, the higher the probability”.
  • “Emptiness” of high-dimensional space: in high-dimensional space, the distances between data points tend to become equal. The difference between the nearest neighbor and the farthest neighbor becomes negligible, and the concept of “distance” itself becomes meaningless.

Data Manifold

Data manifold: refers to the low-dimensional structure that high-dimensional data actually distributes on. Although the data may have thousands of dimensions (such as the pixels of an image), the truly meaningful variation may be only a few dimensions (such as the position and rotation angle of an object).

Real-world data (such as images and speech), although represented in high-dimensional space (e.g., a 64×64 pixel image has 4096 dimensions), actually only occupies a low-dimensional submanifold of the entire space.

For example:

  • The variation of handwritten digit images is mainly controlled by a few factors such as position, rotation, and scaling, so these images are roughly distributed on a three-dimensional manifold.
  • Randomly generated pixel images are completely different from real images because they lack the strong correlations in real data (the difference between two adjacent pixels is usually small).

Therefore, we do not need to define basis functions over the entire high-dimensional space, but only on the data manifold. This greatly reduces the number of required basis functions.


Data-Dependent Basis Functions

To solve the problem of fixed basis functions, we can make the basis functions depend on the training data itself.

  • Radial Basis Function Network (RBF): each training sample acts as the center of a basis function, with the form:

    ϕn(x)=exp(xxn2s2)\phi_n(\mathbf{x}) = \exp\left( -\frac{\|\mathbf{x} - \mathbf{x}_n\|^2}{s^2} \right)

    where xn\mathbf{x}_n is the nn-th training sample (the “center” of the basis function), and ss is the width parameter (controlling how wide this “hill” is — the larger ss is, the wider the influence range; the smaller ss is, the stronger the response is only near xn\mathbf{x}_n). xxn2\|\mathbf{x} - \mathbf{x}_n\|^2 is the squared Euclidean distance from the input point to the center. Simply put: the closer to the training sample, the larger the output value.

    This method can automatically adapt to the data distribution, but is computationally expensive and prone to overfitting.

  • Support Vector Machine (SVM): similarly uses data points as basis function centers, but reduces the number of effective basis functions by optimizing the selection of support vectors.

Although these methods are more flexible than fixed basis functions, they still cannot effectively handle large-scale datasets and are difficult to scale to complex tasks. This leads to deep neural networks — a model that can automatically learn multi-level representations.


Multi-Layer Neural Networks

The core idea of deep neural networks is: let the basis functions themselves also have learnable parameters, and jointly optimize all parameters through gradient descent.

Two-Layer Network Structure

A simple two-layer neural network contains:

  1. First layer (hidden layer):

    aj(1)=i=1Dwji(1)xi+wj0(1),zj(1)=h(aj(1))a_j^{(1)} = \sum_{i=1}^D w_{ji}^{(1)} x_i + w_{j0}^{(1)}, \quad z_j^{(1)} = h(a_j^{(1)})

    where h()h(\cdot) is the nonlinear activation function (a function that performs a nonlinear transformation on the weighted sum result), and zj(1)z_j^{(1)} is called a hidden unit (a neuron in the middle layer of the network — neither input nor output, hence called “hidden”).

  2. Second layer (output layer):

    ak(2)=j=1Mwkj(2)zj(1)+wk0(2),yk=f(ak(2))a_k^{(2)} = \sum_{j=1}^M w_{kj}^{(2)} z_j^{(1)} + w_{k0}^{(2)}, \quad y_k = f(a_k^{(2)})

    where f()f(\cdot) is the output activation function (chosen according to the task, such as sigmoid, softmax).

Two-layer network structure

Two-layer network structure


Universal Approximation

Theory shows that, with enough hidden units, a two-layer neural network can approximate any continuous function to arbitrary precision. This shows that neural networks have powerful representational capacity.

However, universal approximation only guarantees “existence”, not that the learning algorithm can find the optimal solution, nor how many hidden units are needed. In practice, deep networks are often more efficient than shallow ones.


Hidden Unit Activation Functions

Hidden units must use nonlinear activation functions, otherwise the entire network is equivalent to a linear model (unable to capture nonlinear relationships).

Common activation functions include:

  • Logistic Sigmoid: σ(a)=11+ea\sigma(a) = \frac{1}{1 + e^{-a}}, compresses any real number into the (0,1)(0,1) interval. Commonly used early on, but when the absolute value of the input is large, the gradient approaches zero (vanishing gradient), making deep network training difficult.
  • tanh: tanh(a)=eaeaea+ea\tanh(a) = \frac{e^a - e^{-a}}{e^a + e^{-a}}, output in [1,1][-1, 1], with mean close to zero, making training more stable. It can be understood as an “upgraded version” of sigmoid — the output is zero-centered and has better gradient properties.
    • hard version: hardtanh(a)=max(1,min(1,a))\text{hardtanh}(a) = \max(-1, \min(1, a)), a linear approximation of tanh, faster to compute.
  • softplus: softplus(a)=log(1+ea)\text{softplus}(a) = \log(1 + e^a), the “smooth version” of ReLU — behaves similarly to ReLU, but is a smooth curve rather than a sharp corner near zero, and more computationally complex.
  • ReLU (Rectified Linear Unit): ReLU(a)=max(0,a)\text{ReLU}(a) = \max(0, a), the mainstream choice for modern deep networks. Intuitively it is a “switch” — negative values are all turned off (output 0), and positive values pass through unchanged. Extremely simple to compute, and the gradient in the positive interval is always 1, completely avoiding vanishing gradients. (Preferred)
    • leaky ReLU: leakyReLU(a)=max(0,a)+αmin(0,a)\text{leakyReLU}(a) = \max(0, a) + \alpha \min(0, a), gives the negative interval a small slope α\alpha (usually 0.01), avoiding ReLU’s “dead neuron” problem (some neurons always output 0 and can no longer be activated). (Choose when ReLU has problems)

Various activation functions

Various activation functions

Symmetry in Weight Space

In multi-layer neural networks, especially those with hidden layers, if we swap all the connection weights of two hidden units in the same hidden layer, the overall behavior of the network does not change.

For a two-layer network, if we swap the weights of hidden units jj and jj':

  • wji(1)wji(1)w_{ji}^{(1)} \leftrightarrow w_{j'i}^{(1)} (weights from input to hidden layer)
  • wkj(2)wkj(2)w_{kj}^{(2)} \leftrightarrow w_{kj'}^{(2)} (weights from hidden layer to output)

The output of the network remains unchanged, because this is equivalent to relabeling the hidden units.

Weights of hidden unit 1: [0.5, 0.3]; weights of hidden unit 2: [0.2, 0.7]

Swap all connections of these two hidden units: weights of hidden unit 1: [0.2, 0.7] (originally unit 2’s) weights of hidden unit 2: [0.5, 0.3] (originally unit 1’s)

The final output of the network is completely unchanged


For neural networks using symmetric activation functions (such as tanh), if we flip the signs of all input and output weights of a certain hidden unit at the same time:

  • wji(1)wji(1)w_{ji}^{(1)} \rightarrow -w_{ji}^{(1)}
  • wkj(2)wkj(2)w_{kj}^{(2)} \rightarrow -w_{kj}^{(2)}

While keeping the bias unchanged, the output of the network also does not change, because the symmetric activation function satisfies h(a)=h(a)h(-a) = -h(a).

For a network using the tanh activation function:

Originally: the weight is +0.5, the input is +2, compute tanh(0.5 × 2) = tanh(1)

After flipping: the weight is -0.5, the input is -2, compute tanh((-0.

Due to the property tanh(-x) = -tanh(x), the final result is the same

Deep Networks

Although a two-layer network is a universal approximator, deep networks (multiple hidden layers) have significant advantages:

  • Hierarchical representation: shallow layers learn low-level features such as edges and textures, while deep layers learn high-level features such as semantics and objects.
  • Parameter efficiency: for some complex functions, deep networks can achieve them with fewer parameters, while shallow networks may require an exponential number of hidden units.
  • Generalization ability: deep structures can better capture the intrinsic hierarchical structure of data, improving performance on complex tasks (such as image recognition and natural language processing).

An LL-layer deep network can be formally expressed as:

z(l)=h(l)(W(l)z(l1))\mathbf{z}^{(l)} = h^{(l)}(\mathbf{W}^{(l)} \mathbf{z}^{(l-1)})

where l=1,...,Ll=1,...,L, z(0)=x\mathbf{z}^{(0)} = \mathbf{x} is the input, z(L)=y\mathbf{z}^{(L)} = \mathbf{y} is the output, h(l)h^{(l)} is the activation function of the ll-th layer, and W(l)\mathbf{W}^{(l)} is the weight and bias parameter matrix.

Representation Learning

Representation learning means: letting the machine automatically learn effective representations of the input data, rather than relying on hand-designed features.

Early on, training deep networks was very difficult. A key breakthrough was unsupervised pre-training (without using labeled data, let the network learn the structure of the data by itself).

  1. Pre-training stage: use unsupervised learning layer by layer (such as autoencoders or restricted Boltzmann machines) to initialize the network weights. Each layer first learns how to reconstruct its input, thereby discovering the intrinsic structure of the data.
  2. Fine-tuning stage: connect the entire network and use labeled data and gradient descent for supervised fine-tuning.

This method provides the network with good initial weights through pre-training, making it easier to converge.

Important progress: later research found that under suitable conditions (such as using ReLU activation functions, appropriate weight initialization, batch normalization, etc.), the pre-training stage can be skipped entirely, and deep networks can be trained end-to-end (from raw input directly to final output, without manually designed intermediate steps) using supervised learning starting from random initialization. This simplifies the process and makes deep learning more accessible.

However, the ideas of pre-training and representation learning remain crucial, especially in data-scarce domains. The most famous example is the Transformer model (such as BERT, GPT) in natural language processing. These models are first pre-trained on massive unlabeled text (for example, by predicting masked words or the next word) to learn a deep internal representation of language. Afterwards, this pre-trained model can be used for various downstream tasks (such as question answering, translation), achieving excellent performance through fine-tuning.


Transfer Learning

Transfer learning is a technique that uses knowledge learned on one task to improve the performance of another related task. It is particularly suitable for situations where the labeled data of the target task (Task A) is scarce. Its core idea is:

A network trained on a large-scale dataset (Task B) has already learned general, low-level features of the input data (such as images) (e.g., edges, textures, basic shapes). These features are useful for many vision tasks. Transfer learning exploits these already-learned feature representations.


  1. Source task training: first train a deep network on a data-rich, related task (such as classification of everyday objects on ImageNet). The early layers of this network learn general image features.
  2. Target task application:
    • Feature extractor: use the early layers (usually the convolutional layers) of the pre-trained network as a fixed feature extractor. Pass the new data of the target task through this fixed network to obtain a high-level feature representation.
    • Classifier training: on these extracted features, train a new, simple classifier (usually the last few layers of the network) to solve the target task (such as skin lesion classification).
    • Fine-tuning: if the target task has enough data, the entire network (or only the last few layers) can be further fine-tuned to adapt to the specific features of the new task. Fine-tuning usually uses a very small learning rate to prevent destroying the useful knowledge already learned in the pre-trained model.

Advantages:

  • Improved accuracy: compared to training from scratch, transfer learning usually achieves higher accuracy because it exploits the general knowledge learned from large amounts of data.
  • Save time and resources: avoids the large amount of computational resources and time required to train a large network from scratch.
  • Alleviate data scarcity: makes it possible to train effective models in domains with very few labeled data.

Transfer learning (a) The network is trained on a large-scale dataset (such as ImageNet);

(b) Copy the weights of the early layers (red) as a fixed feature extractor, and retrain the last few layers (blue) to adapt to the new task (such as skin lesion classification).

Contrastive Learning

Contrastive learning is a self-supervised learning (no manual labeling required, constructing the learning signal from the data itself) paradigm aimed at learning good data representations without large amounts of labeled data.

Its core idea is: pull similar samples (positive pairs) closer in the representation space, while pushing dissimilar samples (negative pairs) farther apart.

  • Instance discrimination: treat different augmented versions of the same image (such as rotation, cropping) as positive pairs, and different images as negative pairs.
  • Supervised contrastive learning: treat different images of the same class as positive pairs.
  • Cross-modal contrastive learning (such as CLIP): treat an image and its corresponding text description as a positive pair.

Three types of contrastive learning

(a) Instance discrimination (b) Supervised contrastive learning (c) CLIP model


General Network Architectures

In addition to standard fully-connected feedforward networks, more complex architectures can be designed.

  • Residual Network (ResNet): introduces skip connections (allowing the signal to “skip” intermediate layers and pass directly to later ones), allowing information to bypass certain layers and propagate directly. This helps alleviate the vanishing gradient problem in deep networks (the gradient decays layer by layer during backpropagation in deep networks, causing the earlier layers to barely learn), making it possible to train very deep networks.
  • Graph Neural Network: handles graph-structured data, where both nodes and edges have features.

The key requirement is that the network must be feedforward (acyclic), to ensure that the output is a deterministic function of the input.


Tensors

In deep learning, data, weights, and activations are usually represented in the form of tensors (a general term for multi-dimensional arrays — a scalar is a 0th-order tensor, a vector is 1st-order, a matrix is 2nd-order, and higher dimensions are collectively called tensors).

  • Scalar: 0-dimensional tensor (a single number).
  • Vector: 1-dimensional tensor (an array of numbers).
  • Matrix: 2-dimensional tensor (a table of numbers).
  • Tensor: higher-dimensional arrays.

For example, a dataset containing NN color images can be represented as a 4D tensor: [N,H,W,C][N, H, W, C], where HH is the height, WW is the width, and CC is the number of channels (RGB is 3).

Tensors are the foundation of modern deep learning frameworks (such as PyTorch, TensorFlow), and GPUs are very good at tensor operations.


Error Functions

Summary subsection — corresponding to Section 6.4 of the original book

Choosing an appropriate error function is crucial for training neural networks. The error function is usually the negative log-likelihood (turning “maximize the probability of the data occurring” into “minimize the error” — see the discussion of maximum likelihood in Part 1 and Part 2).

Regression

Prerequisite: Chapter 2 - Maximum Likelihood and Least Squares

For regression tasks, the target variable tt is real-valued. Assume the target value follows a Gaussian distribution with the network output as the mean (see Part 2 - Gaussian Distribution):

p(tx,w)=N(ty(x,w),σ2)p(t | \mathbf{x}, \mathbf{w}) = \mathcal{N}(t | y(\mathbf{x}, \mathbf{w}), \sigma^2)

where y(x,w)y(\mathbf{x}, \mathbf{w}) is the output of the neural network, and σ2\sigma^2 is the noise variance.

At this point, the activation function of the output unit uses the identity function (i.e., linear output): y=ay = a.

Given an independent and identically distributed training dataset {xn,tn}n=1N\{ \mathbf{x}_n, t_n \}_{n=1}^N, the corresponding likelihood function is:

p(tX,w,σ2)=n=1Np(tny(xn,w),σ2)p(\mathbf{t}|\mathbf{X}, \mathbf{w}, \sigma^2) = \prod_{n=1}^N p(t_n | y(\mathbf{x}_n, \mathbf{w}), \sigma^2)

The corresponding negative log-likelihood error function is:

12σ2n=1N(tny(xn,w))2+N2log(σ2)+N2log(2π)\frac{1}{2\sigma^2}\sum_{n=1}^N (t_n - y(\mathbf{x}_n, \mathbf{w}))^2 + \frac{N}{2}\log(\sigma^2)+ \frac{N}{2}\log(2\pi)

which is equivalent to minimizing the sum-of-squares error function:

E(w)=12n=1N{y(xn,w)tn}2E(\mathbf{w}) = \frac{1}{2} \sum_{n=1}^N \{ y(\mathbf{x}_n, \mathbf{w}) - t_n \}^2

Minimizing this error function is equivalent to maximizing the likelihood function (the probability of the data given the parameters — see Part 1 and Part 2). Due to the nonlinearity of the network, this error function is usually non-convex, making it difficult to find the global optimum.

When there are multiple target variables, assuming they are independent and share the noise variance given the input and parameters, the conditional distribution is:

p(tx,w)=N(ty(x,w),σ2I)p(\mathbf{t} | \mathbf{x}, \mathbf{w}) = \mathcal{N}(\mathbf{t} | \mathbf{y}(\mathbf{x}, \mathbf{w}), \sigma^2 \mathbf{I})

The corresponding error function is:

E(w)=12n=1Ny(xn,w)tn2E(\mathbf{w}) = \frac{1}{2} \sum_{n=1}^N \| \mathbf{y}(\mathbf{x}_n, \mathbf{w}) - \mathbf{t}_n \|^2

The noise variance can be estimated by:

σ2=1NKn=1Ny(xn,w)tn2\sigma^2_* = \frac{1}{NK} \sum_{n=1}^N \| \mathbf{y}(\mathbf{x}_n, \mathbf{w}_*) - \mathbf{t}_n \|^2

where KK is the dimension of the target variable.


Binary Classification

Prerequisite: Logistic Regression Chapter 2 - Bernoulli Distribution

For binary classification tasks, the target variable t{0,1}t \in \{0, 1\}, indicating membership in class C1C_1 or C2C_2.

The network uses one output unit, with the logistic sigmoid function as the activation function:

y(x,w)=σ(a)=11+eay(\mathbf{x}, \mathbf{w}) = \sigma(a) = \frac{1}{1 + e^{-a}}

At this point yy can be interpreted as the posterior probability p(C1x)p(C_1 | \mathbf{x}), and 1y1 - y as p(C2x)p(C_2 | \mathbf{x}).

The conditional distribution of the target variable follows the Bernoulli distribution:

p(tx,w)=yt(1y)1tp(t | \mathbf{x}, \mathbf{w}) = y^t (1 - y)^{1-t}

The corresponding negative log-likelihood error function is the cross-entropy error function:

E(w)=n=1N[tnlnyn+(1tn)ln(1yn)]E(\mathbf{w}) = - \sum_{n=1}^N \left[ t_n \ln y_n + (1 - t_n) \ln (1 - y_n) \right]

Research shows that, compared to the sum-of-squares error, the cross-entropy error leads to faster training speed and better generalization performance.

If KK independent binary classification tasks need to be performed, KK output units can be used, each with a sigmoid activation function, and the total error is the sum of the cross-entropies of each output:

E(w)=n=1Nk=1K[tnklnynk+(1tnk)ln(1ynk)]E(\mathbf{w}) = - \sum_{n=1}^N \sum_{k=1}^K \left[ t_{nk} \ln y_{nk} + (1 - t_{nk}) \ln (1 - y_{nk}) \right]

Multi-class Classification

Prerequisite: Discriminative Classifier - Multi-class

For a KK-class classification problem, each sample belongs to one and only one class. Using 1-of-K encoding, only one element in the target vector t\mathbf{t} is 1 and the rest are 0.

The network uses KK output units, with the Softmax function as the activation function:

yk(x,w)=exp(ak)j=1Kexp(aj)y_k(\mathbf{x}, \mathbf{w}) = \frac{\exp(a_k)}{\sum_{j=1}^K \exp(a_j)}

Softmax ensures the output satisfies 0yk10 \leq y_k \leq 1 and kyk=1\sum_k y_k = 1, and can be interpreted as the posterior probability p(tk=1x)p(t_k=1 | \mathbf{x}).

The corresponding error function is the multi-class cross-entropy error function:

E(w)=n=1Nk=1Ktknlnyk(xn,w)E(\mathbf{w}) = - \sum_{n=1}^N \sum_{k=1}^K t_{kn} \ln y_k(\mathbf{x}_n, \mathbf{w})

The combination of Softmax and multi-class cross-entropy is the standard choice for multi-class classification problems.


One-sentence version:

  • Regression task: linear output + sum-of-squares error
  • Binary classification task: Sigmoid output + binary cross-entropy error
  • Multi-class classification task: Softmax output + multi-class cross-entropy error

This pairing originates from the maximum likelihood estimation framework, ensuring consistency between the error function and the output distribution assumption. This principle is universal and can be extended to other conditional distribution forms.

Mixture Density Networks

A Mixture Density Network (MDN) is a more advanced model for handling cases where the output is a multimodal function of the input (the same input may correspond to multiple reasonable outputs). Its core idea is: predict multiple possible futures, rather than a single answer.

Problem Background

A standard regression network learns the conditional mean E[tx]E[t|\mathbf{x}] from input x\mathbf{x} to output tt. This works well when the conditional distribution p(tx)p(t|\mathbf{x}) is unimodal (only one peak, i.e., only one “reasonable answer”). But when the distribution is multimodal (multiple peaks, i.e., multiple “reasonable answers”), the mean may lie between the two peaks — a “void zone” where no possible result would ever occur.

Multiple possible futures: imagine you are driving to an intersection and can turn left or right. If you let the model predict only one “average direction”, it will tell you to “go straight” — but there may be a wall there. The MDN’s approach is to tell you at the same time “70% chance of turning left, 30% chance of turning right”, so you can see all reasonable options.

For example, controlling a robot arm — the same end position may correspond to two different joint angles (elbow up or down). The average of these two solutions is not a valid joint configuration.

Mixture Density Network (MDN)

The MDN uses a mixture model (usually a Gaussian mixture model) to model the conditional probability density p(tx)p(t|\mathbf{x}):

p(tx,w)=k=1Kπk(x,w)N(tμk(x,w),σk2(x,w))p(t|\mathbf{x}, \mathbf{w}) = \sum_{k=1}^K \pi_k(\mathbf{x}, \mathbf{w}) \mathcal{N}(t | \mu_k(\mathbf{x}, \mathbf{w}), \sigma_k^2(\mathbf{x}, \mathbf{w}))

where:

  • πk(x,w)\pi_k(\mathbf{x}, \mathbf{w}) is the mixture coefficient of the kk-th Gaussian component (i.e., what proportion of the whole this component occupies), satisfying kπk=1\sum_k \pi_k = 1 and πk0\pi_k \geq 0.
  • μk(x,w)\mu_k(\mathbf{x}, \mathbf{w}) is the mean of the kk-th Gaussian.
  • σk2(x,w)\sigma_k^2(\mathbf{x}, \mathbf{w}) is the variance of the kk-th Gaussian.

The output layer of the network has 3K3K units, outputting πk\pi_k, μk\mu_k, and σk2\sigma_k^2 respectively ( σk2\sigma_k^2 is guaranteed to be positive).

The MDN is trained by maximizing the log-likelihood of the data. The error function is:

E(w)=n=1Nln(k=1Kπk(xn,w)N(tnμk(xn,w),σk2(xn,w)))E(\mathbf{w}) = -\sum_{n=1}^N \ln \left( \sum_{k=1}^K \pi_k(\mathbf{x}_n, \mathbf{w}) \mathcal{N}(t_n | \mu_k(\mathbf{x}_n, \mathbf{w}), \sigma_k^2(\mathbf{x}_n, \mathbf{w})) \right)

Prediction

The MDN can output the entire conditional distribution, not just a point estimate. We can:

  • Predict the conditional mean: E[tx]=kπkμkE[t|\mathbf{x}] = \sum_k \pi_k \mu_k.
  • Predict the conditional variance: s2(x)=E[tE[tx]2x]s^2(\mathbf{x}) = E[\|t - E[t|\mathbf{x}]\|^2|\mathbf{x}], which depends on x\mathbf{x}.
  • Predict the conditional mode (the most likely value): usually take the mean μk\mu_k of the Gaussian component with the largest mixture coefficient.

MDN

MDN

(a) Mixture coefficients πk(x)\pi_k(x)

The three colors represent the mixture coefficients π(x)\pi(x) of three different Gaussian components. At different positions of the input xx, the contribution weight of each Gaussian component to the overall distribution. For example: when xx is small, π1(x)\pi_1(x) is larger, indicating the first Gaussian component dominates; when xx is close to the middle value, π2(x)\pi_2(x) peaks, indicating the second component plays the main role; when xx is large, π3(x)\pi_3(x) dominates.

This shows that the MDN can dynamically adjust the importance of each component according to the input.

(b) Means μk(x)\mu_k(x)

The three colors represent the means μ1(x)\mu_1(x) of three different Gaussian components, showing the trend of the center position of each Gaussian component as the input xx changes. Together they define the “modes” of the conditional distribution (i.e., the possible output values). For example: in some xx regions, μ1(x)\mu_1(x) and μ3(x)\mu_3(x) correspond to two different output paths respectively; while μ2(x)\mu_2(x) lies between them, possibly used for smooth transitions or filling gaps.

(c) Conditional probability density p(tx)p(t|x) contour plot

(d) Conditional mode

Green circles: represent the true training data points (x,t)(x, t) Red curve: represents the conditional mode predicted by the MDN (i.e., the most likely output value), obtained by selecting the mean μk\mu_k of the Gaussian component with the largest mixture coefficient.


Chapter 6 Summary

One-sentence version: Fixed basis functions “explode” in high-dimensional space (curse of dimensionality), so we need to let the basis functions learn by themselves — this is the core idea of neural networks. Deep networks are stronger than shallow ones in “hierarchical understanding”; transfer learning and contrastive learning let the model reuse already-learned knowledge, and the MDN can handle scenarios where “one input corresponds to multiple reasonable outputs”.

Knowledge map:

Limitations of fixed basis functions
├── Curse of dimensionality: number of parameters grows exponentially with dimension, data becomes sparse
├── Data manifold: real data actually only occupies a low-dimensional substructure of high-dimensional space
└── Data-dependent basis functions: RBF / SVM, use training data to define basis function centers
Multi-layer neural networks
├── Structure: input → hidden layer (learnable basis functions) → output layer
├── Activation functions: ReLU (preferred) / sigmoid / tanh / softplus
├── Universal approximation: a two-layer network can theoretically approximate any continuous function
└── Weight symmetry: swapping hidden units does not change the output
Deep networks
├── Hierarchical representation: shallow layers learn edges/textures, deep layers learn semantic objects
├── Representation learning: from hand-crafted features to automatically learned features
├── Transfer learning: large model pre-training → fine-tuning on small data
└── Contrastive learning: pull similar samples closer, push dissimilar samples apart
Error function pairings
├── Regression: linear output + sum-of-squares error
├── Binary classification: sigmoid + cross-entropy
└── Multi-class classification: softmax + multi-class cross-entropy
Mixture Density Network (MDN)
└── Use Gaussian mixture model to model p(t|x), output the entire distribution rather than a single prediction

Thanks for reading! Follow me if you'd like~

Deep Learning Notes - 3: Classification Models and Introduction to Deep Neural Networks

Mon Sep 01 2025
7489 words · 40 minutes
Cover
Sample track
Sample artist
Cover
Sample track
Sample artist
0:00 / 0:00