Perceptrons and Logistic Regression
Linear Classifiers, Perceptrons, and Logistic Regression
1. Classification from Feature Vectors
Many machine-learning classification problems follow a two-stage process:
Convert an input x into a feature vector f(x).
Use the feature vector to predict a class label y.
For example, in email classification:
x is the original email.
f(x) might contain:
The number of times the word “free” occurs.
Whether the recipient’s name appears.
The number of misspelled words.
Whether the email came from a friend.
y is the predicted class, such as spam or ham.
For image classification:
x is an image.
f(x) could contain pixel values.
Binary images may use features with values 0 or $1`.
Grayscale images may use values between 0 and 1, or between 0 and 255.
More advanced features could describe properties such as the number of loops in a handwritten digit.
The focus of linear classifiers is the transition from the feature vector to the class prediction:
The feature-engineering step, converting x into f(x), often requires substantial human judgment. A designer must decide which properties are useful, whether related words should be grouped together, and which image characteristics should become features. Later machine-learning methods can also learn useful features automatically, but the methods discussed here assume that f(x) is already available.
2. Probabilistic Models Versus Direct Classifiers
Earlier probabilistic methods, such as naive Bayes, learn a broader probabilistic model over the variables in the problem. That model can then answer queries such as:
A linear classifier takes a narrower approach:
It does not necessarily model the full probability distribution of all variables.
It focuses directly on making the decision from features to a class label.
It can devote its parameters specifically to classification performance.
Advantages of focusing directly on classification
The method concentrates on the decision that matters.
It does not spend modeling capacity on the distribution of inputs if that distribution is irrelevant to the task.
It can be especially effective when there is abundant labeled data.
Limitation
A direct classifier does not automatically provide a complete probabilistic model of the inputs and labels. If a full model of how the data are generated is needed, a generative probabilistic model may be more appropriate.
3. Biological Inspiration: A Single Neuron
Perceptrons are loosely inspired by the behavior of biological neurons. This analogy is only an approximate source of inspiration; it is not intended to be a complete or accurate model of how the brain works.
A biological neuron has:
Dendrites, which receive signals from other neurons or sensory systems.
A central processing region, where incoming signals are combined.
An axon, which sends an output signal to other neurons.
A simplified artificial neuron can be represented as follows:
Each input is a feature value.
Each feature has an associated weight.
The neuron combines the weighted features.
The resulting activation determines the output class.
If the feature vector is
and the weight vector is
then the activation is the weighted sum
The dot product measures how strongly the feature vector aligns with the weight vector.
4. The Binary Perceptron
The binary perceptron classifies examples into two classes, conventionally represented as +1 and −1.
Its decision rule is:
The activation’s sign determines the prediction.
The perceptron predicts the positive class when the weighted feature sum is positive and the negative class when it is negative.
Interpretation of weights
Each weight indicates how a feature affects the classification score.
For a spam classifier, possible weights might be:
“free”: +4
A frequent occurrence increases the spam score substantially.
Recipient’s name: −1
The presence of the recipient’s name decreases the spam score.
Misspelling: +1
Misspellings provide some evidence of spam.
From a friend: −3
Messages from friends are less likely to be spam.
A positive weight makes a feature support the positive class. A negative weight makes the feature support the negative class. The magnitude indicates the strength of that influence.
A negative activation can arise because:
A feature has a negative weight and a positive value.
A feature itself has a negative value and a positive weight.
Several negative contributions outweigh positive contributions.
Geometric interpretation
Feature vectors can be viewed as points in a high-dimensional feature space. The weight vector defines a direction.
If w⋅f(x)>0, the feature vector lies on the positive side.
If w⋅f(x)<0, it lies on the negative side.
If w⋅f(x)=0, it lies on the decision boundary.
The decision boundary is the hyperplane orthogonal to w:
In two dimensions, this hyperplane is a line. In three dimensions, it is a plane. With more features, it is a higher-dimensional hyperplane.
A feature vector pointing in roughly the same direction as w has a positive inner product. A vector pointing in the opposite direction has a negative inner product.
5. Bias Terms
A perceptron can include a bias term, which represents a default preference for one class.
The bias can be incorporated by adding a constant feature whose value is always 1. If the bias is b, the activation becomes
Equivalently, the augmented feature vector may be written as
with an augmented weight vector
The decision rule then becomes
Effect of the bias
Without a bias, the decision boundary must pass through the origin. A bias allows the hyperplane to shift away from the origin.
A positive bias favors the positive class by making positive predictions easier.
A negative bias favors the negative class by requiring more positive feature evidence before predicting the positive class.
For example, if the positive class is spam and the bias is negative, an email is initially presumed to be non-spam unless its features provide enough evidence to make the total activation positive.
6. Learning the Perceptron Weights
The perceptron does not determine its weights in a single closed-form calculation. Instead, it learns through repeated updates over the training data.
Let:
f(x) be the feature vector for a training example.
y∗ be the true label, where y∗∈{−1,+1}.
y be the prediction made using the current weights.
Basic training procedure
Initialize the weight vector, often to zero.
Select a training example.
Compute the activation w⋅f(x).
Predict the class from the sign of the activation.
If the prediction is correct, leave w unchanged.
If the prediction is incorrect, update w.
Continue cycling through the training examples until an appropriate stopping condition is reached.
Perceptron update rule
For a misclassified example, the update is
If the example is correctly classified, the update is zero:
The compact form can be written as
where the indicator is 1 only for a mistake.
Why the update works
Consider the new activation with respect to the same feature vector:
Expanding gives
The self-inner-product is the squared length of the feature vector:
Therefore:
If y∗=+1, the activation increases.
If y∗=−1, the activation decreases.
This moves the classifier in the direction needed to classify the current example correctly.
Geometric interpretation of the update
For a positive example, +f(x) is added to w, making w more aligned with that example.
For a negative example, −f(x) is added to w, making w less aligned with that example and more aligned with its opposite direction.
The update does not necessarily make the current example correctly classified immediately, nor does it guarantee that previously corrected examples remain correct. It simply nudges the decision rule in the correct direction.
7. Learning Rate and Update Size
The basic perceptron update uses the full correction y∗f(x). A more general update can include a learning-rate parameter α:
The learning rate controls the size of each adjustment.
A large α produces larger, more abrupt changes.
A small α produces smaller, more gradual changes.
Smaller steps may reduce sensitivity to individual examples.
Learning rates and more gradual updates are particularly important in more sophisticated optimization methods.
The basic perceptron can work without an explicit learning rate under appropriate conditions, but controlling the step size is useful in many related learning algorithms.
8. Perceptron Convergence
Linearly separable data
A binary dataset is linearly separable if there exists a hyperplane that places all positive examples on one side and all negative examples on the other.
When the data are linearly separable, the binary perceptron is guaranteed to converge to some separating decision boundary, assuming the standard perceptron setup.
The perceptron may change its boundary many times before converging, but eventually it will make no further mistakes on the training set.
Nonseparable data
If no hyperplane can perfectly separate the classes, the perceptron generally does not converge. It can continue to bounce between different weight vectors:
One example causes an update.
That update causes another example to become misclassified.
The next update fixes the second example but may break the first one again.
This cycle can continue indefinitely.
Mistake bound
For separable data, the number of mistakes is bounded. In the simplified form discussed, the bound depends on:
k, the number of features.
δ, a measure of separation between the classes.
The number of mistakes is on the order of
The intuition is:
More features can make learning take longer.
A larger separation margin δ makes the problem easier.
As δ increases, the possible number of mistakes decreases.
If the separation is nonzero and the number of features is finite, the number of mistakes is finite.
9. Multiclass Perceptrons
The binary perceptron uses one weight vector to distinguish between two classes. For a problem with multiple classes, the perceptron uses one weight vector per class.
Suppose there are classes 1,…,C. Each class has a weight vector:
For an input x, the score for class c is
The predicted class is the one with the highest score:
Each weight vector represents the feature direction associated with its class.
Geometric interpretation
Each class weight vector creates a region of feature space where its score is largest.
The regions are not determined only by the angles of the weight vectors. Their lengths also matter:
A longer weight vector can produce larger inner products.
A class with a larger-magnitude weight vector may occupy more of the feature space.
If all weight vectors have similar lengths, the regions are influenced mainly by their directions.
Thus, a class’s decision region depends on both the direction and magnitude of its weight vector.
10. Multiclass Perceptron Training
Let:
y∗ be the correct class.
y^ be the class predicted by the current weights.
Training procedure
Initialize every class weight vector, often to zero.
Process training examples one at a time.
Compute every class score.
Predict the class with the highest score.
If y^=y∗, make no update.
If y^=y∗, adjust the weights of the predicted and correct classes.
Multiclass update rule
For a mistaken prediction, update:
and
All other class weight vectors remain unchanged.
Why the update works
For the incorrectly predicted class:
Its score decreases.
For the correct class:
Its score increases.
Therefore, the update makes the correct class more competitive and the incorrectly predicted class less competitive. It does not guarantee that the correct class immediately becomes the winner, but it moves the scores in the desired direction.
Example: classifying text
Suppose the classes are:
Sports
Politics
Technology
A sentence such as “win the vote” can be represented using binary features such as:
where the first component is a bias feature.
If the current model predicts Sports but the correct label is Politics:
Subtract the sentence’s feature vector from the Sports weight vector.
Add the sentence’s feature vector to the Politics weight vector.
Leave the Technology weight vector unchanged.
The algorithm then continues through the examples repeatedly until it completes a full pass without any mistakes, if convergence is possible.
11. Separability Versus Convergence
These concepts describe different things.
Separability
Separability is a property of the dataset. It asks whether a suitable set of decision boundaries exists that can classify all training examples correctly.
For binary classification, this means a single separating hyperplane exists. For multiclass classification, it means that each class can have a region in which its score is highest for all examples belonging to that class.
Convergence
Convergence is a property of an algorithm’s run. It asks whether the algorithm eventually stops changing its parameters.
These concepts are related but not identical:
A dataset may be separable, allowing a binary perceptron to converge.
A dataset may be nonseparable, causing the perceptron to update forever.
An algorithm may stop because of a chosen stopping rule even when the model is not ideal.
For a binary perceptron, linearly separable data guarantee convergence; general perceptron training does not guarantee convergence on nonseparable data.
12. Problems with the Perceptron
Although the perceptron is simple and useful, it has several limitations.
Nonseparable data cause endless updates
When the data cannot be perfectly separated by a hyperplane, the perceptron keeps correcting mistakes indefinitely. It has no natural way to accept that some examples may lie on the “wrong” side of a boundary.
It may stop at a poor boundary
Even when the data are separable, many separating hyperplanes may exist. The perceptron stops as soon as it finds one that makes no training mistakes.
Some separating boundaries are poor because they pass very close to training examples. A new example near the boundary could easily be classified incorrectly.
The perceptron does not inherently prefer a boundary with a large margin. It treats all perfectly accurate separating boundaries as acceptable.
Overfitting
As the perceptron continues updating, its training accuracy generally improves because the updates are driven by the training examples. However, the model may begin memorizing peculiarities of the training data rather than learning general patterns.
A common strategy is to divide the data into:
Training data: used to update the model.
Hold-out data: monitored during training to decide when to stop.
Test data: kept untouched until final evaluation.
Typically:
Training accuracy increases.
Hold-out accuracy also increases initially.
Hold-out accuracy reaches a maximum.
Hold-out accuracy begins to decrease as overfitting occurs.
Training should stop when hold-out performance starts declining.
This strategy is called early stopping.
The test data should not be used to make training decisions because it is intended to estimate performance on unseen future data.
Logistic Regression
13. From Hard Decisions to Probabilistic Decisions
The perceptron makes a hard decision based on the sign of the activation:
A more flexible approach is to interpret the activation as evidence for a class and convert it into a probability.
Instead of claiming that every point on one side is definitely positive, the model can assign probabilities such as:
Near the boundary: approximately 50% positive and 50% negative.
Somewhat toward the positive side: approximately 70% positive.
Far from the boundary: approximately 90% positive.
Points on the “wrong” side can still receive a nonzero probability of belonging to the other class.
This allows the model to represent uncertainty and tolerate imperfectly separable data.
14. The Sigmoid Function
Let the linear score be
The sigmoid function converts any real-valued score into a number between 0 and 1:
The positive-class probability is defined as
The negative-class probability is
Properties of the sigmoid
If z is very negative, σ(z) is close to 0.
If z=0, σ(z)=0.5.
If z is very positive, σ(z) is close to 1.
The function changes smoothly rather than making an abrupt threshold decision.
Thus, the linear score still determines the direction of the decision, but the sigmoid expresses the strength of that evidence probabilistically.
15. Maximum Likelihood for Logistic Regression
Once the classifier produces probabilities, the weights can be selected using maximum likelihood estimation.
The goal is to choose weights that make the observed labels as probable as possible given the inputs.
For training examples indexed by i, the objective is
Because the features are derived from the inputs, the conditional distribution may also be written as
The logarithm is used because:
Products of probabilities become sums of log probabilities.
Sums are easier to optimize numerically.
Maximizing log likelihood is equivalent to maximizing likelihood because the logarithm is monotonic.
For binary logistic regression, the probability is determined using the sigmoid function. The optimal weight vector is the one that gives the highest total log probability to the observed labels.
Unlike some simpler probabilistic models, logistic regression generally does not produce a convenient closed-form solution for the optimal weights. In practice, an optimization algorithm is needed to search for a high-likelihood weight vector.
16. Why Logistic Regression Improves on the Perceptron
Logistic regression addresses two major perceptron limitations.
It handles nonseparable data
Because logistic regression assigns probabilities rather than requiring every example to be perfectly classified, it can continue improving even when no linear boundary separates all examples.
It does not need to alternate endlessly between incompatible corrections. Instead, it seeks the weight vector that maximizes the overall likelihood.
It prefers larger margins
Suppose two decision boundaries classify all training points correctly:
One boundary passes close to several data points.
The other leaves more distance between the boundary and the data points.
The perceptron is indifferent once both produce zero training mistakes.
Logistic regression is not indifferent. Points far from the boundary receive probabilities closer to 1 for their predicted class, which produces higher log likelihood. Points close to the boundary receive probabilities closer to 0.5, which produces lower confidence and a lower likelihood when their labels are known.
Therefore, logistic regression tends to favor a boundary that places examples farther from the decision boundary when doing so improves the probabilities of the observed labels.
17. Multiclass Logistic Regression and Softmax
For multiclass classification, logistic regression uses one weight vector per class, just as the multiclass perceptron does.
For class c, define the activation or score
Each score can range from negative infinity to positive infinity. These scores must be converted into probabilities that:
Are nonnegative.
Sum to 1.
Give higher probability to classes with higher scores.
The required transformation is the softmax function.
For class c:
Substituting the class scores gives
Why softmax produces probabilities
Every exponential ezc is positive.
Dividing by the sum of all exponentials normalizes the values.
The resulting probabilities sum to 1:
Relative scores determine probabilities
Softmax is based on relative activations:
The class with the largest zc receives the largest probability.
A class with a lower score receives a lower probability.
The largest score tends to dominate because exponentials grow rapidly.
Equal scores produce equal probabilities.
For instance, a model might assign:
90% to class 1,
5% to class 2,
5% to class 3.
This expresses uncertainty while still identifying class 1 as the most likely class.
18. Maximum Likelihood for Multiclass Logistic Regression
The parameters are selected to maximize the conditional log likelihood of the observed labels:
Using softmax, this becomes
The objective rewards the model when:
The correct class receives a high score.
The correct class receives a high probability.
Competing classes receive lower probabilities.
Unlike the multiclass perceptron, which only reacts to mistakes, multiclass logistic regression uses the full probability distribution. Even a correctly classified example can influence the weights if the model is insufficiently confident or if another probability assignment would produce a higher likelihood.
Discriminative and Generative Classification
19. Generative Models
A generative model attempts to model the joint distribution of inputs and labels:
Using the product rule, this can be decomposed as
A generative model therefore models both:
The conditional relationship between labels and inputs, P(y∣x).
The distribution of inputs, P(x).
Naive Bayes is an example of a generative approach.
Its log-likelihood objective can be expressed as
20. Discriminative Models
A discriminative model focuses directly on the conditional distribution
Logistic regression is a discriminative classifier because it optimizes the probability of the label given the features without needing to model the distribution of inputs themselves.
Its objective focuses on
Why use a discriminative model?
If the only goal is to predict labels, modeling P(x) may be unnecessary. Including the input-distribution term could influence the learned parameters even though that term does not directly determine classification performance.
A discriminative model can concentrate all of its capacity on the classification decision.
Why use a generative model?
The input-distribution term can sometimes act as a form of regularization:
With little training data, modeling more of the data structure may help stabilize the parameters.
A generative model can provide a broader understanding of how the data are produced.
The additional structure may reduce overfitting in some situations.
With a large amount of data, a discriminative model often has enough information to focus directly on predicting labels and may achieve better classification performance.
Discriminative models learn how to distinguish classes; generative models learn how the data and classes are jointly generated and can then be used for classification.
21. Overall Comparison
Binary perceptron
Uses a linear score w⋅f(x).
Makes a hard binary decision based on the sign.
Updates only after mistakes.
Converges when binary training data are linearly separable.
May fail to converge on nonseparable data.
Does not inherently prefer a large margin.
Multiclass perceptron
Uses one weight vector per class.
Computes one score per class.
Predicts the class with the highest score.
On a mistake, subtracts the feature vector from the predicted class and adds it to the correct class.
Can also fail to converge when the data are not appropriately separable.
Binary logistic regression
Uses a linear score followed by a sigmoid.
Produces a probability for the positive class.
Learns weights by maximizing conditional log likelihood.
Handles nonseparable data more gracefully.
Prefers parameter settings that assign high confidence to correctly labeled examples.
Multiclass logistic regression
Uses one score per class.
Converts scores into a probability distribution with softmax.
Learns by maximizing the conditional log likelihood of the correct labels.
Uses graded probabilistic information rather than only correct-versus-incorrect feedback.
Can continue converging even when the classes are not perfectly separable.
The central distinction is that the perceptron makes deterministic mistake-driven updates, whereas logistic regression uses smooth probabilities and maximum likelihood to find a stable decision rule.

Ask anything
We've read this whole study set, so questions about it get the best answers.