ai theory
CS231n Summary (2): Linear Classification
Junyoung Park · 2022-11-03 · 18 min
In the Previous Post...
The previous post introduced image classification, one of the most representative tasks in computer vision, as well as the simple KNN (k-Nearest Neighbor) classifier. It described several challenges in image classification and explained why we use data-driven algorithms to address them. Classification based only on comparing a distance metric between samples, however, has two problems:
- The classifier must retain all training data as a reference for test data. Keeping that data in memory is inefficient.
- Classifying a single item requires comparing it with every training example, making computation expensive.
KNN offers limited generalization and uses memory inefficiently. Image classification therefore needed a more efficient approach: learning with a neural network. Everything covered up to that point was not really about deep learning, but about how to define a task such as computer vision, what a data-driven algorithm means, and why we choose that methodology.
Neural Network Circuits
The neural-network circuit approach imitates the operating principles of the human nervous system.
To represent how a neuron receives and transmits information, an input interacts with weights and produces an output through an activation function . This is called a perceptron. A perceptron cannot fully reproduce a neuron, so it is misleading to map dendrites, the soma, axons, and other biological parts directly onto perceptron components. Instead, think of it as defining information transmission by an affine transform of input and then applying a nonlinear function to increase logical complexity. More concretely, when an input enters the computation, predefined parameters and produce an output; applying a nonlinear function yields a score or some indicator of the result.
If the defined parameters and behave as intended on the input dataset, the difference between the output and label (ground truth) will converge to .
We must therefore define a distance metric that meaningfully measures the difference between output and label. The neural-network parameters will be adjusted incrementally according to this metric.
Score function / Loss function / Cost function
Choosing the distance metric appropriately is important, as is the task represented by the ground-truth labels. If is unsuitable, it may fail to capture the difference between ground truth and output, or training may be unable to converge. When viewed as a function, this metric is called a loss function or cost function. Both terms imply how far something falls short of a criterion. To preview a later point, unsupervised, semi-supervised, and supervised learning all ultimately need a reference point that can play the role of ground truth. Returning to the topic, neural-network optimization requires a loss or cost function.
Since this post is about linear classification, let us make the explanation specific to that task. In addition to loss, we need the concept of a score function. A score function maps raw data to a score for each class, while the loss function uses those scores to quantify the difference between a prediction and its label. Here, raw data means the input supplied to the neural network.
Let us formulate exactly how an image is mapped to scores. Suppose there are image samples, each corresponding to one of classes.
Interpreting these in matrix dimensions, a CIFAR-10 input image, for example, has size , so
The image sample can be flattened into a one-dimensional vector whose length is the product of all three dimensions of the image tensor. As its name suggests, CIFAR-10 contains 10 classes, so it corresponds to in the expression above.
Because activation function operates element-wise on the vector, the output retains the dimensions of the affine-mapped . The neural-network circuit can therefore replace an input image with dimensions with scores for classes. As introduced earlier, the learnable parameters and are called the weight and bias. The discussion so far can be summarized in four points.
-
The single matrix product can be computed efficiently. Here, efficient means parallelizable: each label score in is computed from a row vector of . Although there are 10 classes, their computations can run in parallel.
-
The data is fixed, but the function parameters and can be adjusted.
-
The goal is to pass training data through the network and find and that predict the dataset well. We therefore no longer need to keep the training data in memory after training.
-
This is much faster than comparing a test image with every training image, as KNN does.
The computation can be illustrated as above. Strictly speaking, the diagram behaves differently from the activation function previously described. In this example, treat as simply the affine function . The result on the far right contains the predicted scores used for classification. Since the dog score is highest, the model will probably predict “dog”—an obviously incorrect answer here.
Once expanded into a high-dimensional vector, an image can be interpreted as a point in a coordinate system with 3,072 axes. Linear classification maps the entire image dataset directly into this 3,072-dimensional space. The figure above reduces those dimensions to two for ease of understanding.
As explained earlier, each row vector of classifies one label. Geometrically, changing a row vector is like rotating the classifier in another direction, while bias shifts the classifier relative to the origin.
A linear classifier can also be interpreted as template matching, like KNN. Every computation is the inner product between a row vector of and (a column vector). This lets learn a template or prototype and find the closest value in vector space. The problem can ultimately be interpreted like KNN, which treats samples as prototypes and predicts from the nearest samples. This may not be intuitive at first, but an inner product itself acts as a distance metric, much like calculating an or distance.
For example, the learned horse template might show two horses facing each other. A car classifier should distinguish many colors and types of cars, yet red features biased by the dataset may dominate. The figure below shows the weights learned for each class.
A simple linear classifier trained on the dataset produces a weight prototype for each class, as shown above. When a new sample is projected onto a prototype, greater similarity produces a larger value. This mechanism does not provide especially good generalization. To overcome these problems, deep neural architectures later introduce hidden layers and move beyond prototype-style learning.
Weight and bias
If bias and weight are learned and computed separately, the parallelization of row-vector operations described above cannot be applied to the bias. But adding bias is simply an element-wise sum with each element of the linear projection of and , so it can be incorporated by adding a dimension instead of being learned separately.
Append an element to the input and extend the row vector with the bias on its right. The two operations can then be optimized together rather than processed separately.
Loss functions
Everything described so far concerns making a neural network predict one score for each desired class. When the network gives a wrong or ambiguous answer for an input, we need a criterion that quantifies the error and supports optimization. We will therefore examine basic forms of the objective introduced earlier, beginning with a brief introduction to the support vector machine.
Support Vector Machine (SVM)
The basic principle of an SVM is to give the score of the correct answer for each image a margin () above the scores of other classes. In a linear classification model, it maximizes the score at the correct class index while minimizing those at the remaining class indices. For a variable indexing classes from 1 through , the score of sample () is
Because SVM loss requires the correct class score to exceed every other class score by at least a margin , the SVM loss for sample is
Suppose the correct answer for sample is , mapped to one of classes. is the score assigning sample to its correct class , while each is the score assigning sample to an incorrect class . If the score for class is not at least the margin below the score of the correct class , the argument to is positive and the loss increases. Loss definitions vary by task, but in general they grow as a result moves farther from the desired criterion. Here, loss increases unless all incorrect-class scores lie at least the margin below the correct-class score.
The figure above visualizes this idea. Training continues until every other class score has been reduced enough to differ by the margin. In neural-network matrix notation,
If is the class index whose score we want, the required element is row vector of matrix , which is combined with sample by an inner product. A loss defined around a threshold in this way is called hinge loss. To penalize predictions more heavily or make the loss differentiable, we can instead use
SVM loss has a major problem. If a trained can make a particular class score larger by the desired margin , every scalar multiple of can do the same. For every with , for example, the scores produced by are also scaled above 1 and satisfy the same condition. From an optimization perspective, having multiple global minima violates the conditions for convex optimization. Without a constraint in the problem, training may slow down or diverge. We therefore add a regularization penalty to restrict the search to a more feasible region—that is, a meaningful manifold that can actually be explored.
The norm of a two-dimensional matrix is defined as above. Among the many possible values of , it encourages the ideal optimum to be the one closest to the origin on an -dimensional hypersphere. The loss we minimize therefore combines the hinge loss introduced earlier with the regularization loss above.
When optimizing multiple loss functions, the user typically chooses hyperparameter through cross-validation. From an optimization perspective, the regularization term makes the problem closer to convex optimization, as explained above. From the perspective of post-training performance, larger weight parameters make the network more sensitive to changes in the input and can cause overfitting. Explanations of regularization losses and methods therefore often say they are used to prevent overfitting. That is correct, but it is not the whole reason for regularization.
Hyperparameters in SVM
We introduced as an adjustable hyperparameter, but in the hinge loss must also be chosen by the user. Since controls the scale of the weights, adjusting would require a corresponding adjustment to . The two hyperparameters are related rather than acting independently on performance, so we can leave fixed and consider only , which controls weight magnitude, as the hyperparameter. The SVM classifier described so far applies regardless of the number of classes. For binary classification with two classes, fixing the margin at gives
Here, constant is a hyperparameter inversely proportional to . In a binary support vector machine, takes the values rather than representing a class index.
Softmax
The SVM introduced above is one type of classifier. Another representative choice is the softmax classifier. I have rarely used an SVM in recent projects or deep-learning assignments, while softmax appears frequently when applying energy-based functions, so it may be the more important concept in practice. Softmax can be summarized as extending binary logistic regression to a multiclass classifier. Binary logistic regression begins with two categories, and , whose classification probabilities sum to 1. It differs from ordinary linear regression because it uses a linear model in a special way, constraining the target to lie between and . Consider a model that predicts a dependent variable taking the values or from an independent variable . An ordinary linear model would be . Linear regression finds the slope (weight) and intercept (bias) of a line that represents multiple data points, but this linear formulation is not very helpful for classification with only two possible dependent-variable values.
The range of a linear function extends to infinity regardless of how the data and parameters are chosen, rather than remaining between and . Since this is unrelated to the result we want, functions were designed to map onto the desired values and of the dependent variable : the logistic model and the Gumbel model . Because the nested exponentials make the Gumbel model expensive to compute, the simpler logistic model came into use.
As the form of the logistic function shows, its dependent-variable output is always between 0 and 1 for a continuous independent variable . Two concepts used in the computation are odds and logit. Odds are the ratio of the probability of success to the probability of failure. If the probability that the dependent variable belongs to class for a given independent variable is the probability of success, then
Because probability ranges from 0 to 1, taking its logarithmic odds gives the logit
which spans the entire real line. We now have a function defining the relationship between dependent variable and independent variable , so linear regression can be applied.
This expression is not defined directly in terms of . Solving it for dependent variable turns it into a logistic-regression problem.
This demonstrates that classification with softmax is possible in a neural network. We have considered only the binary case so far, but the idea can be extended to multiple classes. The logistic function used in logistic regression converts an input score into an estimated class probability. Whereas an SVM classifier uses scores directly, this approach uses probabilities obtained through logistic mapping.
This is called the softmax function. Here, is the class index and is its score. To return probabilities for classes, softmax transforms scores into a vector of values in the range —a normalized probability distribution. The loss aims to make the probability at the correct class index approach , and is computed by taking the negative logarithm of the softmax result.
Minimizing this expression increases the target-class score and decreases the remaining scores, so SVM and softmax ultimately share the same direction. The resulting loss is called cross-entropy loss.
Cross-Entropy Loss and Information Theory
We commonly say entropy is high when a situation is confusing or uncertain. In probabilistic terms, entropy is large when we cannot be confident about a piece of information. Given possible outcomes (results or information) and their respective probabilities , Shannon entropy is
This expression can be interpreted as the amount of information that probability distribution preserves about itself. If we are uncertain about every outcome, is distributed uniformly, and preserving all possible outcomes requires more information, increasing entropy. Conversely, if is uneven enough that we can be confident about the outcome, the result can be represented without preserving every possibility, reducing entropy. Now consider how much information a predicted distribution preserves about . Assume we know the target distribution and treat it as ground truth .
From a classification perspective, for each the ideal distribution assigns probability to the correct class index and to all other classes. The softmax term is the predicted probability . Decomposing cross-entropy gives
The first term on the right is the KL divergence, which expresses the distance between distributions and . Since this distance is nonnegative, the following inequality holds.
Cross-entropy must therefore be greater than or equal to entropy. The original distribution's is treated as a constant, so its derivative is and it does not affect training. Optimizing cross-entropy is consequently equivalent to optimizing KL divergence.
The model predicts unnormalized scores, which softmax—with its exponential function—converts into normalized probabilities. Maximizing the probability that an image belongs to a particular class is equivalent to maximizing likelihood and can be interpreted as MLE through Bayes' rule below.
This form cannot account for the input prior. In a neural network, however, matrix can take its place. If is interpreted as a transformation of input through parameter , the prior can be rewritten as
Thus, while optimizing classification likelihood, can simultaneously serve as the prior, allowing the process to be interpreted as MAP (maximum a posteriori) estimation.
Normalization trick
Computing the exponentials above and applying log-likelihood can make the sum of exponentials in the denominator () extremely large. Because the scores are unnormalized, values may overflow or lose precision during computation. We therefore use the following trick to reduce their magnitude.
Dividing both numerator and denominator by the same value leaves the result unchanged. Let the largest original score be . Then
Rescaling relative to this maximum makes every exponent nonpositive, keeping the exponential values in the range .
SVM vs. Softmax: Which Is Better?
We have examined two classifiers for linear classification: the support vector machine (SVM) and softmax.
An SVM applies hinge loss to the score function produced by a neural network. Softmax converts the network's score function into normalized probabilities and uses cross-entropy loss to perform MLE or MAP optimization.
Regularization in SVM—and in Softmax?
We noted that an SVM can have multiple values of producing the same loss. The following example shows why softmax nevertheless also uses regularization.
Suppose a neural-network computation with some produces the values above. A softmax classifier converts scores into normalized probabilities . If regularization makes every element of this half as large, the probabilities become
The result is more diffuse—a denser probability distribution. In other words, as weight parameters become smaller, the output probabilities become more uniform. Unlike the raw SVM score table, the ordering of probabilities remains the same while their confidence changes, rather than preserving absolute values or differences.
Conclusion
The performance difference between SVM and softmax is not very large, so there is no universal answer about which classifier is better for every task or practitioner. An SVM is described as having a more local objective—it focuses only where necessary—because it can ignore score differences larger than the margin. Softmax does not satisfy this condition because its loss never becomes zero, no matter how far apart the scores are. In summary, an SVM stops learning once its condition is met, whereas softmax continues updating parameters in pursuit of higher performance.