Supervised Learning and Neural Networks: Classifiers

Learn how a program can learn to classify from labeled examples. Set up a supervised learning problem with features, labels and a loss, then train three classic classifiers by hand: naive Bayes, which counts evidence with probabilities; the perceptron, which corrects its weights after every mistake; and logistic regression, which turns a weighted score into a probability. See how gradient descent minimizes a loss, how neural networks combine many simple units, and how backpropagation finds every weight's gradient with the chain rule. Finally, learn to recognize overfitting and to control it with smoothing, regularization, early stopping and dropout.

IntermediateLesson 9 of 10 in Artificial Intelligence Course

What you will learn

  1. Describe what a learning program receives, what it produces and how its quality is measured: labeled examples, features, hypotheses, loss and performance on new data.
    • Describe the supervised learning task
      Name the parts of a supervised learning problem, tell classification from regression, and explain why a learned hypothesis is judged on examples it has not seen.
    • Represent examples with features and measure loss
      Turn inputs into feature vectors, compute weighted scores with a dot product, and measure a hypothesis's mistakes with a loss function.
  2. Build a probabilistic classifier from Bayes' rule and a conditional independence assumption, estimate its probabilities by counting with smoothing, and apply it to text.
    • Make predictions with the naive Bayes model
      State the naive Bayes assumption, compute class scores and posterior probabilities for an example, and carry out the computation with logarithms.
    • Estimate naive Bayes probabilities from data
      Estimate the prior and conditional probabilities by counting, see why a zero count breaks the model, and repair it with Laplace smoothing.
    • Classify text with a bag-of-words model
      Represent documents by word counts, classify them with multinomial naive Bayes in log space, and recognize what the model ignores.
  3. Separate classes with a weighted sum of features, learn the weights with the perceptron rule, and turn scores into probabilities with logistic regression.
    • Read linear decision boundaries
      Compute a linear classifier's score and prediction, describe its decision boundary, and decide whether a data set is linearly separable.
    • Learn weights with the perceptron rule
      Run the perceptron learning rule by hand, explain when it converges and what happens when it cannot, and extend it to several classes.
    • Predict probabilities with logistic regression
      Use the sigmoid to turn a linear score into a probability, interpret the weights as changes in log-odds, measure fit with log loss, and extend the model to many classes with softmax.
  4. Treat training as minimizing a loss, compute gradients, choose a learning rate, and train models with stochastic and mini-batch gradient descent.
    • Minimize a loss by following the gradient
      Compute partial derivatives and gradients, apply the gradient descent update by hand, and see how the learning rate and the shape of the loss affect the result.
    • Train with stochastic and mini-batch gradient descent
      Compare batch, stochastic and mini-batch gradient descent, derive and apply the logistic regression update, and relate it to the perceptron rule.
  5. Compute the output of a feedforward network, find every weight's gradient with backpropagation, and train networks in practice.
    • Compute the output of a feedforward network
      Describe units, activation functions and layers, run a forward pass by hand, and explain why hidden layers with nonlinear activations make networks more expressive than linear models.
    • Compute gradients with backpropagation
      Apply the chain rule on a computation graph to find the gradient of the loss with respect to every weight, check it numerically, and recognize vanishing gradients.
    • Train a neural network in practice
      Set up the training loop, initialize weights sensibly, choose hyperparameters and read training curves to spot common problems.
  6. Tell overfitting from underfitting with training and held-out results, relate it to model complexity and data, and reduce it with regularization, early stopping and dropout.
    • Diagnose overfitting and underfitting
      Compare training and held-out performance to spot overfitting and underfitting, and explain how model complexity and the amount of data affect generalization.
    • Prevent overfitting with regularization
      Add L2 or L1 penalties to the loss, use early stopping and dropout, enlarge the data with augmentation, and choose the regularization strength on validation data.

Supervised Learning and Neural Networks study guide

6 chapters

1

Set up a supervised learning problem

Learning starts with a prediction task: what describes one case, what answer is wanted, and how a mistake is measured. These choices determine the examples and the family of rules the program can learn. Turn inputs into ordered feature vectors, calculate weighted scores, and distinguish fitting a training sample from performing well on new cases. The same basic setup supports probability models, linear classifiers, and neural networks.

1.1 Describe the supervised learning task

A learning program receives examples of the behavior it should learn. In supervised learning, each example pairs an input with its correct output, called a label. The learned rule must also work on inputs that were absent during training.

Identify the task and its labels

Write a training set as (𝐱1,y1),…,(𝐱N,yN). The input describes one case; the label supplies the answer for that case. An unknown target function describes the underlying relationship. With noise-free labels, y=f(𝐱). The program chooses a hypothesis h to approximate that relationship.

For a spam filter, one case is an email. Its input can describe whether it contains "free," how many links it has, and whether its sender is a contact. Its label is spam or ham, meaning wanted email. A training set might contain 5,000 labeled emails; the finished filter is evaluated on 1,000 different labeled emails.

TaskOutputExample
Binary classificationOne of two classesSpam or ham
Multiclass classificationOne of several classesA digit from 0 to 9
RegressionA numerical quantityRainfall in millimeters

The output defines the task. "Will more than 5 mm of rain fall?" asks for a class; "How many millimeters will fall?" asks for a number. An integer output can still be a class: digit 7 names a category, not seven times digit 1.

Supervised learning uses labeled examples. Unsupervised learning looks for structure without labels, such as customer clusters. Reinforcement learning uses rewards following an agent's actions. Creating reliable labels can require substantial human work.

Choose a family of possible rules

The hypothesis space is the family the program can search, such as linear classifiers using specified features. Learned parameters, including weights or conditional probabilities, select one member of that family. A target outside the family cannot be represented exactly, even with unlimited data.

A hyperparameter controls the learning setup: examples include a learning rate or the number of hidden units. Training fits parameters. Comparisons on validation data help choose hyperparameters. More flexible families capture more patterns but also have more ways to fit noise.

Judge predictions on new cases

Training error measures fit to examples used for learning. A rule that memorizes every training email can have zero training error and still fail on new messages. Use a validation set for model choices and keep a separate test set for the final assessment.

For a classifier, error rate is the number of wrong predictions divided by the number tested. Three errors among 40 emails give

error rate=3/40=0.075=7.5%,accuracy=92.5%.

The connection to future performance depends on the sampling setting. Independent and identically distributed, or i.i.d., examples are independent draws from the same distribution. If future spam uses very different wording, the old test set no longer represents that future stream. Report the held-out result for the population it actually represents.

Key Takeaways

  • Supervised learning fits a hypothesis from input–label pairs.
  • Classification predicts a class; regression predicts a numerical quantity.
  • Parameters are learned; hyperparameters control the learning setup.
  • Use validation data for choices and untouched test data for final assessment.
  • Generalization to future cases depends on representative sampling.

1.2 Represent examples with features and measure loss

Models work with a numerical description of each case. The choice and order of these features determine what a model can notice. A loss then tells learning how costly its predictions are.

Build a feature vector

A feature can be binary, a count, or a measured number. "Contains free" becomes 0 or 1, a link count might be 4, and floor area might be 85 m². Keep the same feature order for training and prediction. A 28 by 28 grayscale image supplies 28×28=784 pixel features.

For a category without a numerical order, use one-hot encoding. For red, green, and blue, the vectors are (1,0,0), (0,1,0), and (0,0,1). Codes 1, 2, and 3 would impose an artificial ordering and spacing on these colors.

Combine features into a score

A dot product multiplies corresponding weights and features, then adds:

𝐰⋅𝐱=∑iwixi.

For 𝐰=(2,−1,0.5) and 𝐱=(1,3,4), the score is

2(1)+(−1)(3)+0.5(4)=2−3+2=1.

A positive weight raises the score when its feature increases; a negative weight lowers it. Weight magnitude describes sensitivity per feature unit, so comparing magnitudes across differently scaled features needs care.

The bias shifts the score independently of varying inputs. Include a constant first feature x0=1 and let w0 be its weight. Thus 𝐱=(1,x1,…,xn) includes the bias feature; it is not an extra measured property. The model can then shift a decision boundary without changing the other weights.

Measure the cost of a prediction

A loss function compares a prediction with its label. Different losses express different costs:

LossCalculationEffect
0/10 if correct, 1 if wrongCounts classification mistakes
Squared(y−y^)2Gives large errors extra weight
Absolute∣y−y^∣Grows directly with error size

For a true temperature of 10 °C and prediction of 7 °C, squared loss is 9 and absolute loss is 3. An error of 6 has squared loss 36, four times the loss for an error of 3. The average 0/1 loss is the classification error rate.

Empirical loss is average loss on the training sample. Predictions (2,4,7) for labels (3,4,5) give squared errors 1, 0, and 4, hence mean squared error 5/3≈1.67. Add the losses before dividing by the number of examples.

Generalization loss is expected loss on new examples from the same distribution. Minimizing empirical loss can fit accidental details of the sample. Irrelevant features give a learner more opportunities to do this; near-duplicate features can also count the same evidence twice in naive Bayes. Ockham's razor favors a simpler hypothesis when alternatives fit about equally well, because extra flexibility needs support from data.

Key Takeaways

  • Feature order and encoding must stay consistent across examples.
  • One-hot encoding represents unordered categories without an artificial ranking.
  • A dot product adds weighted feature contributions; the constant feature carries the bias.
  • Squared loss emphasizes large errors more strongly than absolute loss.
  • Empirical loss is a sample average; generalization loss concerns new examples.
  • More features can increase opportunities to fit noise.
2

Classify with naive Bayes

Naive Bayes learns class evidence by counting and combines that evidence through Bayes' rule. Work from a conditional independence assumption to class scores, then normalize them or compare their logarithms. Counts introduce a practical problem: an unseen outcome gets zero probability. Smoothing repairs that problem, and the text model shows why document counts, token counts, binary absences, and repeated words must stay distinct.

2.1 Make predictions with the naive Bayes model

Naive Bayes combines a class's starting probability with the evidence supplied by an input. Its simplifying assumption makes a large probability model learnable from relatively small samples.

Factor the evidence by class

The model assumes features are conditionally independent given the class. For a class variable and several features,

P(y,f1,…,fn)=P(y)∏iP(fi∣y).

A Bayesian network shows the class as the parent of each feature. Independence is conditional: features can be strongly related overall because both depend on the class. For 100 binary features, a full joint feature table needs 2100−1 free probabilities per class. Naive Bayes needs only 100 probabilities per class, one for each feature's yes value.

Bayes' rule gives a class score

sy=P(y)∏iP(fi∣y).

Choose the class with the largest score. The omitted evidence denominator is the same for all classes. A score is not yet a posterior probability: to obtain a posterior, divide it by the sum of all class scores.

Work through a binary-feature prediction

Suppose the spam prior is 0.4 and the ham prior is 0.6. The probabilities for "free" are 0.5 in spam and 0.05 in ham. For "meeting," they are 0.1 and 0.4. The new email contains "free" but lacks "meeting."

  1. For spam, absence of "meeting" contributes 1−0.1=0.9. The score is 0.4(0.5)(0.9)=0.18.
  2. For ham, that absence contributes 1−0.4=0.6. The score is 0.6(0.05)(0.6)=0.018.
  3. The scores sum to 0.198, so the spam posterior is 0.18/0.198≈0.909.

An absent binary feature supplies evidence. If both words occur, the scores become 0.02 and 0.012, and the spam posterior falls to 0.625. "Meeting" shifts the balance toward ham even though spam still wins.

Keep the direction of conditioning straight. P(free∣spam)=0.5 describes spam messages. The reverse probability, P(spam∣free), also needs the class priors and the ham likelihood; here it is 0.2/(0.2+0.03)≈0.870.

Use log scores without changing the winner

Long products can underflow to zero in computer arithmetic. Two hundred factors of 0.01 give 10−400, smaller than the least positive double-precision number. Compare

log⁡sy=log⁡P(y)+∑ilog⁡P(fi∣y)

instead. Logarithms preserve order and turn multiplication into addition. Here ln⁡0.18≈−1.715 beats ln⁡0.018≈−4.017; among negative scores, the less negative score is larger.

Naive Bayes is generative: it models the prior and how features arise within each class. Logistic regression is discriminative: it models the class probability from the input directly. Binary-feature naive Bayes also has a linear log-odds boundary. Correlated features, such as "Hong" and "Kong," can make its posterior too extreme by counting overlapping evidence. A class prediction can be right even when the assigned probability is too extreme.

Key Takeaways

  • Naive Bayes assumes conditional feature independence given the class.
  • Multiply the prior by every observed feature-value likelihood, including binary absences.
  • Normalize class scores to obtain posterior probabilities.
  • Log scores prevent underflow and preserve the winning class.
  • Correlated evidence can produce overconfident probabilities.

2.2 Estimate naive Bayes probabilities from data

Naive Bayes learns by counting. The important choices are which population belongs in a denominator and how much protection to give an outcome that has not appeared yet.

Estimate probabilities within the right group

The maximum likelihood estimate, or MLE, makes the observed data most probable. For a class prior, divide the class count by the total number of examples. For a conditional feature probability, restrict both counts to the class:

P^(y)=count⁡(y)N,P^(f∣y)=count⁡(f,y)count⁡(y).

Consider 100 emails: 40 spam and 60 ham. "Free" appears in 20 spam messages and 3 ham messages; "meeting" appears in 4 spam and 24 ham messages. Thus the spam prior is 0.4. The "free" estimates are 20/40=0.5 for spam and 3/60=0.05 for ham. The "meeting" estimates are 4/40=0.1 and 24/60=0.4. Dividing a feature-and-class count by 100 would estimate a joint probability, not the requested conditional probability.

Repair zero counts

Suppose "prize" appears in 8 spam messages and no ham message. Its ham MLE is zero. Any new message containing it gets ham score zero, whatever its other features say. A finite sample's missing outcome has become a claim of impossibility.

Add-k smoothing gives every possible feature value a pseudo-count of k:

Pk(f∣y)=count⁡(f,y)+kcount⁡(y)+k∣F∣.

Here ∣F∣ is the number of values of this feature. For a yes/no feature it is 2, not the number of words being modeled. With add-one smoothing,

P(prize∣ham)=162≈0.016,P(prize∣spam)=942≈0.214.

Both outcomes receive a pseudo-count. In ham, the absent value therefore has probability 61/62. The two probabilities sum to 1. Adding only to the numerator would break this normalization.

Choose the strength of smoothing

The strength k is a hyperparameter. At zero it gives MLE. As it becomes large, each probability approaches the uniform value 1/∣F∣ and class-specific evidence weakens. Smoothing trades some fit to the observed counts for more stable predictions on new cases.

Compare settings such as 0.1, 0.5, 1, 2, and 5 on validation data. Keep the test set separate for the final assessment. A large setting can underfit; a very small setting may leave rare features with unstable estimates.

The same pseudo-count matters less when real counts grow. Among 6,000 ham emails with 300 containing "free," the MLE is 0.05 and the add-one value is 301/6002≈0.0502. With many observations, the data dominate the pseudo-counts. Class priors are commonly left unsmoothed when every class is well represented. A single pass over labeled examples can collect the counts, which makes this training method fast.

Key Takeaways

  • MLE estimates probabilities with relative frequencies in the relevant class.
  • A zero feature count can erase an entire class score.
  • Add-k smoothing adds k to every outcome count and k times the number of outcomes to the total.
  • Choose smoothing strength on validation data; its influence decreases as counts grow.

2.3 Classify text with a bag-of-words model

A bag of words turns text into word counts. It gives a simple classifier evidence about vocabulary while discarding the order in which words occur.

Count tokens, not just documents

"The cat saw the dog" and "the dog saw the cat" have the same bag: "the" twice and each other word once. A token is an occurrence; the vocabulary is the set of distinct words represented by the model.

In multinomial naive Bayes, every word position is an independent draw from a class-specific word distribution. A word appearing three times contributes three factors:

sy=P(y)∏wP(w∣y)nw.

The matching log score is log⁡P(y)+∑wnwlog⁡P(w∣y). The prior appears once per document. The word count multiplies its log probability.

Estimate word probabilities from token counts within a class. With smoothing,

Pk(w∣y)=count⁡(w,y)+kNy+k∣V∣,

where Ny counts all training tokens in that class and ∣V∣ counts vocabulary words. Suppose spam contains 200 tokens, including "cash" 9 times, and the vocabulary contains 1,000 words. MLE gives 9/200=0.045. Add-one gives 10/1200≈0.0083, while k=0.1 gives 9.1/300≈0.0303. A large vocabulary makes even one pseudo-count per word substantial.

Classify a short document

Sports and politics each have prior 0.5. Word probabilities are:

WordSportsPolitics
goal0.050.005
vote0.0040.04
match0.030.006

For "goal goal vote match," the sports score is

0.5(0.05)2(0.004)(0.03)=1.5×10−7.

The politics score is 0.5(0.005)2(0.04)(0.006)=3×10−9. Sports wins by a factor of 50, and its normalized posterior is 50/51≈0.98. Omitting the second "goal" would discard part of the evidence. In practice use the log scores, about −15.71 and −19.62, to avoid tiny products.

Keep the text models distinct

A Bernoulli text model uses one yes/no feature per word and includes every absent word's factor. The multinomial model uses occurrence counts and has no separate absent-word factors. Its denominators count tokens, not documents. Mixing those choices produces neither model correctly.

A vocabulary word unseen in one class needs smoothing. A word outside the vocabulary has no modeled probability and is usually skipped. Alternatively, training can reserve an unknown-word token with its own class-specific probability.

The bag ignores context: "good" supplies the same evidence inside "not good" and "very good." Adding bigrams, or word pairs, can represent a phrase such as "not good." Near-duplicate or neighboring words can still produce overconfident probabilities. The model remains useful as a fast baseline for topics, spam, sentiment, or language identification.

Key Takeaways

  • A bag of words records occurrence counts and ignores order.
  • Multinomial naive Bayes uses token probabilities, with one factor per occurrence.
  • Token smoothing uses the total class token count plus k times vocabulary size.
  • Bernoulli text models also model absences; multinomial models use counts.
  • Unknown vocabulary items are skipped unless an unknown-word token was trained.
  • Bigrams capture some local context that single-word counts lose.
3

Train linear classifiers

A weighted sum gives a simple geometric classifier: its zero-score boundary divides the input space. The perceptron moves that boundary after mistakes, while logistic regression assigns probabilities and learns through a smooth loss. Follow both kinds of predictions and updates, see why XOR needs changed features, and extend class scoring to several classes. The geometry also explains what multiplying or omitting weights changes.

3.1 Read linear decision boundaries

A linear classifier makes a decision from a weighted sum. Geometry shows which patterns that sum can separate and why some tasks require new features.

Read the score and boundary

Include the constant bias feature first: 𝐱=(1,x1,…,xn). Compute z=𝐰⋅𝐱 and predict +1 for z≥0 or −1 for z<0. A zero score belongs to the positive class under this convention.

With at least one nonzero feature weight, the decision boundary is 𝐰⋅𝐱=0. For two varying features it is a line; for three it is a plane; in general it is a hyperplane. The non-bias weight vector is perpendicular to this boundary and points toward the positive side.

For 𝐰=(−3,1,1), the score is −3+x1+x2 and the boundary is x1+x2=3. Point (2,2) scores 1, (1,1) scores −1, and (3,0) scores zero. The predictions are positive, negative, and positive.

The geometric distance is the score magnitude divided by the length of the non-bias weight vector:

d=∣𝐰⋅𝐱∣∥(w1,…,wn)∥.

For (2,2) it is 1/2≈0.71. Multiplying every weight by a positive constant changes the score but leaves both the distance and the predicted class unchanged. Leaving out the bias restricts boundaries to pass through the origin.

Decide whether a line is enough

Data are linearly separable when one weight vector classifies every point correctly. For AND, use 𝐰=(−1.5,1,1). Only (1,1) has positive score; the other three binary inputs have negative scores.

XOR labels (1,0) and (0,1) positive, but (0,0) and (1,1) negative. No line can separate those diagonally opposite pairs. To see why, the negative origin requires w0<0. The two positive points require w1+w2≥−2w0, while the negative point (1,1) requires w1+w2<−w0. Together they require w0>0, a contradiction.

The feature representation can change separability. Add the feature x1x2 and use weights (−0.5,1,1,−2). The four XOR inputs then score −0.5, 0.5, 0.5, and −0.5 in the order (0,0),(1,0),(0,1),(1,1). The rule is linear in the expanded feature vector, even though it is nonlinear in the original inputs. A hidden layer can learn useful transformed features.

Extend scoring to several classes

Keep one vector per class and choose the largest dot product. For 𝐱=(1,2), vectors 𝐰A=(1,1), 𝐰B=(2,0), and 𝐰C=(0,1) give scores 3, 2, and 2. Class A wins. These are comparative scores, not probabilities; they need not lie between zero and one or sum to one.

Key Takeaways

  • The sign of a dot product selects the binary class; a zero score is positive here.
  • The bias moves the boundary away from the origin.
  • Positive weight scaling preserves the boundary and predictions.
  • XOR needs transformed features or a nonlinear model.
  • Multiclass linear prediction selects the largest class score.

3.2 Learn weights with the perceptron rule

The perceptron learns a linear decision rule by correcting mistakes as they occur. It changes weights directly, without fitting probabilities or differentiating a smooth loss.

Update one example at a time

Use labels y∈{−1,+1}, include the bias feature, and start with zero weights. A score of zero predicts +1. For each example, predict using the current weights. Leave them unchanged if correct; otherwise apply

𝐰←𝐰+y𝐱.

A positive example adds its feature vector. A negative example subtracts it. The score on that example changes by y∥𝐱∥2, so it moves toward the correct sign. The bias feature makes the squared length positive. One update can still leave the example wrong and can disturb earlier predictions.

An epoch is a full pass through the training set. Stop after an entire mistake-free epoch or a chosen pass limit.

Trace two passes

Take the examples in this order, with the bias coordinate already included:

ExampleInputLabel
A(1,1,3)−1
B(1,3,1)+1
C(1,0,1)−1
D(1,2,0)+1
  1. A scores zero and is wrongly positive. Subtract A to get (−1,−1,−3).
  2. B now scores −1−3−3=−7. Add B to get (0,2,−2).
  3. C scores −2 and D scores 4. Both are correct, so no update occurs.
  4. On the next pass, A, B, C, and D score −4, 4, −2, and 4. No mistakes remain, so stop.

The learned boundary is x1=x2. Predictions must use the weights after all preceding updates, not the weights at the start of the epoch.

Understand convergence and its limits

The perceptron convergence theorem guarantees finitely many mistakes for linearly separable training data. If augmented inputs have lengths at most R and a unit-length separator achieves positive signed margin γ, the mistake bound is (R/γ)2. The guarantee finds a separator; it does not select the widest margin or the best test performance.

Nonseparable data, including XOR in its original features or conflicting labels, never allow a mistake-free pass. Set a training limit and use validation performance to choose weights. An averaged perceptron predicts using the average of weights over training steps. A fixed positive learning rate simply scales every weight when starting from zero, so it leaves the binary prediction sequence unchanged; a changing rate can alter that behavior.

Correct a multiclass prediction

On a multiclass mistake, add the input to the true class vector and subtract it from the predicted class vector. Leave the rest unchanged. For input (1,2), true class B and predicted A, vectors (1,1) and (2,0) become (0,−1) and (3,2). Their new scores are −2 and 7. The unchanged C score is 2, so B now wins. Like the binary perceptron, this model outputs a class, not a probability.

Key Takeaways

  • Update only after a wrong prediction, using the label times the augmented input.
  • Use the latest weights for each new example.
  • One epoch visits every training example.
  • Separable data have a finite-mistake guarantee; nonseparable data do not.
  • A multiclass update raises the true class score and lowers the mistaken winner.
  • A perceptron prediction is a class, not a probability.

3.3 Predict probabilities with logistic regression

Logistic regression turns a linear score into a probability for a binary class. Its smooth output gives a graded training signal even when a hard classification is already correct.

Convert a score into probability

For labels 0 and 1, compute z=𝐰⋅𝐱 and

p=P(y=1∣𝐱)=σ(z)=11+e−z.

The sigmoid increases from values near zero to values near one. It gives σ(0)=0.5, σ(1)≈0.731, σ(2)≈0.881, and σ(−2)≈0.119. Predicting class 1 when p≥0.5 is equivalent to using z≥0, so this decision boundary remains linear.

The score equals the log-odds:

ln⁡p1−p=z.

With weights (−4,0.8) and input (1,hours studied), five hours give score zero and probability 0.5. At 7.5 hours the score is 2 and the probability is about 0.881. Each extra hour adds 0.8 to log-odds and multiplies odds by e0.8≈2.23. It does not add 0.8 to probability. A predicted probability of 0.7 concerns this example's class; it is not a report of 70% model accuracy.

Train with log loss

For one example, binary log loss is

−[yln⁡p+(1−y)ln⁡(1−p)].

Only the term for the observed label remains. If y=1, use −ln⁡p; if y=0, use −ln⁡(1−p). At p=0.9, these losses are about 0.105 and 2.303. A confident wrong prediction is much more costly than an uncertain one; p=0.5 gives loss about 0.693 for either label.

Maximum likelihood chooses weights that assign high joint probability to the observed labels. Taking a negative logarithm turns their probability product into the sum of log losses. Gradient descent fits the weights because there is no general closed-form solution.

The logistic log loss is convex in the weights, so every local minimum is global. The 0/1 loss is flat almost everywhere and supplies no useful gradient; squared loss after the sigmoid loses this convexity. On separable training data, unregularized log loss can decrease as weights grow without bound, so a finite maximum-likelihood solution is absent. A weight penalty controls that growth.

Use softmax for more classes

Give each class a score and normalize exponentials:

P(c∣𝐱)=ezc∑jezj.

Scores (2,1,0) produce probabilities about (0.665,0.245,0.090). Adding one constant to every score changes neither the probabilities nor the winning class because the common exponential factor cancels. With two classes, softmax is a sigmoid of the score difference.

Logistic regression models P(y∣𝐱) directly and fits weights jointly. It does not assume feature independence. Naive Bayes estimates a prior and feature distributions by counting; it can be especially effective with small data, but correlated evidence can make its probabilities too extreme.

Key Takeaways

  • The sigmoid maps a linear score to a probability for class 1.
  • Weights change log-odds linearly, not probability linearly.
  • Log loss penalizes confident wrong predictions strongly.
  • Logistic log loss is convex, but separable data need regularization for finite fitted weights.
  • Softmax normalizes class scores into probabilities.
  • Logistic regression fits class probabilities directly without naive Bayes feature independence.
4

Optimize models with gradient descent

Gradient descent connects a prediction rule to a method for fitting its parameters. Derivatives tell how a loss changes locally; a learning rate turns that information into an update. Work through one- and two-parameter steps, then compare full-data updates with noisy single-example and mini-batch updates. Logistic regression provides a concrete derivation in which the chain rule simplifies to prediction error times input.

4.1 Minimize a loss by following the gradient

Training often means finding weights that make a loss small. Gradient descent uses the local slope of that loss to choose the next weights, repeating until a stopping rule is met.

Find the downhill direction

A partial derivative measures how the loss changes when one parameter varies and the others stay fixed. The gradient collects all these derivatives. For

L(w1,w2)=w12+3w22,∇L=(2w1,6w2).

At (2,1) the gradient is (4,6). It points in the direction of steepest local increase under Euclidean distance; its negative points downhill. A smooth minimum has zero gradient, but a zero gradient can also occur at a saddle point or maximum.

With positive learning rate α, update

𝐰←𝐰−α∇L(𝐰).

Compute the entire gradient before changing any weight. From (2,1) with α=0.1, the next point is (1.6,0.4), then (1.28,0.16). Loss falls from 7 to 3.04 to about 1.72. The second coordinate changes faster because its curvature is larger.

See how step size controls convergence

For L(w)=(w−3)2, the derivative is 2(w−3). From zero with rate 0.1:

  1. The first gradient is −6, so the next weight is 0.6.
  2. At 0.6 the gradient is −4.8, so the next weight is 1.08.
  3. The following values are 1.464, 1.7712, and about 2.017.

Each step multiplies the distance to 3 by 1−2α=0.8. For this loss, convergence from a nonoptimal start needs 0<α<1. Rate 1 bounces between 0 and 6; rate 1.1 produces 6.6, −1.32, and 8.184, moving farther away. A smaller rate can be stable but slow. The same rate is not suitable for every loss or feature scale.

Differentiate a prediction loss

For a linear predictor h=w0+w1x and one example with squared loss (y−h)2,

∂L∂w0=2(h−y),∂L∂w1=2(h−y)x.

Use x=2, y=5, and weights (0,1). The prediction is 2, so the gradient is (−6,−12). A rate of 0.05 gives new weights (0.3,1.6). The next prediction is 3.5 and loss falls from 9 to 2.25. The bias derivative has input factor 1, while the slope derivative includes the measured input.

Read the loss surface

A convex loss has no inferior local minima: every local minimum is global. Linear squared loss and logistic log loss are convex. Neural network losses are generally nonconvex, with saddle points and flat regions as well as minima. Initialization can affect the final result.

Feature scales also affect optimization. Area up to 200 m² and room counts up to 6 can stretch the loss surface into a narrow valley. Standardization subtracts each feature's training mean and divides by its training standard deviation. Better-scaled coordinates reduce zigzagging. Stop using a chosen step budget, small gradients, or lack of improvement.

Key Takeaways

  • A gradient collects partial derivatives and points toward steepest local increase.
  • Subtract a learning-rate-scaled gradient to move downhill.
  • Compute every gradient at the same weights before updating.
  • Too large a learning rate can cause oscillation or divergence.
  • Convex losses have no inferior local minima; network losses are generally nonconvex.
  • Feature scaling can make optimization more stable and efficient.

4.2 Train with stochastic and mini-batch gradient descent

Computing a gradient over every example can be costly. Stochastic and mini-batch updates trade a perfectly averaged direction for more frequent, cheaper steps.

Choose how much data informs an update
MethodGradient for one updateMain trade-off
BatchAverage over all training examplesExact training gradient, expensive steps
StochasticOne randomly selected exampleCheap, noisy steps
Mini-batchAverage over a small batchBalances noise and efficient parallel work

An epoch visits the whole training set once. With 10,000 examples and batches of 100, an epoch has 100 update steps. Shuffle examples between epochs so the same groups do not recur in the same order.

A uniformly chosen single-example gradient has expectation equal to the full training gradient. Individual steps can nevertheless increase total loss. Plotting loss over epochs gives a clearer trend than judging one update. Noise can help movement around saddle points and shallow minima, but a fixed large learning rate also keeps weights jittering near a solution. A decreasing learning-rate schedule helps settle them.

Derive the logistic update

Let p=σ(z), z=𝐰⋅𝐱, and use binary log loss. Its derivative with respect to probability is

∂L∂p=−yp+1−y1−p=p−yp(1−p).

Multiplying by the sigmoid derivative p(1−p) leaves ∂L/∂z=p−y. Since ∂z/∂wi=xi, the complete gradient is

∇L=(p−y)𝐱.

Subtracting it gives the equivalent update 𝐰←𝐰+α(y−p)𝐱. For a batch, average these vectors using the same current weights before making one update. Summing instead of averaging multiplies the effective learning rate by batch size.

Work one stochastic step

Start at 𝐰=(0,0,0) with input 𝐱=(1,2,1), target 1, and rate 0.5. The score is zero, so p=0.5. Then

𝐰new=0.5(1−0.5)(1,2,1)=(0.25,0.5,0.25).

The new score is 0.25+0.5(2)+0.25=1.5 and the new probability is about 0.818. This example's log loss falls from about 0.693 to 0.201. That improvement concerns this example; a stochastic step need not improve every training case.

The perceptron also uses a label-related correction times the input, but it uses ±1 targets and changes weights only on mistakes. Logistic regression uses 0/1 targets and a smooth probability error. At finite weights, it can keep updating after the predicted class is correct.

Recognize common optimizer variants

Momentum carries a running average of gradient directions, helping movement along consistent directions and reducing oscillation. Adam combines this with adaptive per-parameter step sizes. Both still need a suitable learning rate. Compare settings with validation results and record validation loss along with training loss to decide when further training stops helping.

Key Takeaways

  • Batch, stochastic, and mini-batch methods differ in examples used per update.
  • An epoch is a full data pass, not a single update.
  • For binary logistic log loss, the gradient is prediction minus target times input.
  • Average mini-batch gradients before updating.
  • Stochastic loss can fluctuate; schedules reduce step size over time.
  • Momentum and Adam modify how gradient information produces steps.
5

Build and train neural networks

Hidden layers build features that a single linear score cannot express. Follow values through a small network, count its weights and biases, and match its final activation to the target. Backpropagation sends derivative information in the opposite direction so all parameters can be trained efficiently. Initialization, input scales, mini-batches, and validation curves then connect those calculations to a working training loop.

5.1 Compute the output of a feedforward network

A neural network connects many simple units. Hidden layers transform inputs into learned features; nonlinear activations let those features represent patterns that a single linear classifier misses.

Compute units and count parameters

A unit calculates z=∑iwiai+b, then outputs a=g(z). Here the incoming activations are its inputs, and the bias is shown separately. This is equivalent to including a constant bias feature.

ActivationOutput rule or rangeCommon role
Sigmoid1/(1+e−z), between 0 and 1Binary probability output
tanhBetween −1 and 1Centered nonlinear hidden output
ReLUmax⁡(0,z)Cheap nonlinear hidden unit

A feedforward network has no directed cycles: information moves from input through hidden layers to output. In a fully connected layer, each unit receives every output of the previous layer. A layer with m inputs and n units has mn weights and n biases. Three inputs, four hidden units, and two output units therefore give

3(4)+4+4(2)+2=26

trainable parameters. Count one bias per receiving unit, not one per connection. Networks with many hidden layers are called deep.

Follow a network that computes XOR

Use two hidden ReLU units and a linear output:

h1=ReLU⁡(x1+x2),h2=ReLU⁡(x1+x2−1),y^=h1−2h2.

For (0,0), the hidden values are (0,0), so the output is 0. For either (0,1) or (1,0), they are (1,0), giving 1. For (1,1), they are (2,1), giving 2−2=0. The hidden representation allows the output to distinguish the XOR classes.

Without nonlinear activations, stacking layers would still make one affine transformation. Ignoring biases for clarity, W2(W1𝐱)=(W2W1)𝐱. Depth alone would add no nonlinear expressive power. The bends introduced by activations change what the network can represent.

Match outputs to targets

For a numerical regression target, a linear output and squared loss are a standard choice. For binary labels, use one sigmoid output and binary log loss. For one of several classes, use softmax outputs and cross-entropy −ln⁡pcorrect. Probabilities (0.665,0.245,0.090) with the second class correct give loss about 1.41. The loss uses the probability assigned to the true class, even when another class wins.

The universal approximation theorem says a sufficiently wide hidden layer with a suitable nonlinear activation can approximate any continuous function on a closed, bounded input region to arbitrary accuracy. It is an existence result, not a guarantee that training finds the weights or that a small network suffices. Depth can represent some functions much more efficiently.

Hidden representations can progress from image edges and textures to object parts. Architectures also build in useful structure: convolutional networks share small weight sets across image positions, while recurrent networks share weights across sequence steps.

Key Takeaways

  • A unit applies an activation to a weighted sum plus bias.
  • A fully connected layer has one weight per connection and one bias per receiving unit.
  • Hidden nonlinear features let networks represent patterns such as XOR.
  • Output activations and losses must match the target type.
  • Universal approximation describes representational possibility, not training success.
  • Weight sharing captures repeated spatial or sequential structure.

5.2 Compute gradients with backpropagation

Backpropagation computes how every parameter affects loss. A forward pass stores the values needed by the chain rule; a backward pass reuses them to avoid repeating the same derivative calculations.

Move through a computation graph

A computation graph separates sums, products, and activations into operations. Along a path through an intermediate value,

∂L∂w=∂L∂z∂z∂w.

When a parameter affects loss along several paths, add their contributions. For unit j, write δj=∂L/∂zj. Its backward signal is

δj=g′(zj)∑kwjkδk.

The sum includes units that receive its output. A weight from activation ai into unit j has gradient aiδj. The bias gradient is simply δj because its input is 1.

Work a forward and backward pass

Let x=2, h=ReLU⁡(w1x), y^=w2h, and L=(y^−y)2. Start with w1=0.5, w2=3, and target y=1.

  1. Forward: the hidden sum is 1, hidden output is 1, prediction is 3, and loss is 4.
  2. At the output, ∂L/∂y^=2(3−1)=4. Thus ∂L/∂w2=4h=4.
  3. Going back through the output weight gives ∂L/∂h=4(3)=12. The hidden sum is positive, so the ReLU derivative is 1.
  4. The first weight's gradient is therefore 12(1)(2)=24.

With rate 0.01, update both weights from these stored gradients:

w1=0.5−0.01(24)=0.26,w2=3−0.01(4)=2.96.

A fresh forward pass gives hidden output 0.52, prediction 1.5392, and loss about 0.291. Using 2.96 during the preceding backward pass would mix two parameter states and produce the wrong gradient.

Check derivatives and recognize weak signals

A numerical check approximates one derivative by

L(w+ε)−L(w−ε)2ε.

With ε=0.001, the first weight's derivative above is 24. This needs two forward passes per weight, so it is useful for checking, not large-scale training. Backpropagation computes all gradients at a cost of the same order as a forward pass. Libraries implement this as reverse-mode automatic differentiation.

Sigmoid has derivative σ(z)(1−σ(z))≤0.25; tanh has derivative 1−tanh⁡2z. ReLU's derivative is 1 above zero and 0 below; zero is commonly assigned derivative 0. A ReLU unit whose preactivation is negative for every input is dead and receives no useful gradient through its activation. Softmax cross-entropy has score gradient 𝐩−𝐲 for one-hot targets.

Repeated small derivative factors cause vanishing gradients. A chain of 10 sigmoid units with connecting weights 1 has derivative at most 0.2510≈9.5×10−7. Wider graphs also depend on weights and summed paths. ReLU, suitable initialization, and residual connections reduce this problem. Large backward signals can instead explode; gradient clipping caps their size.

Key Takeaways

  • Backpropagation multiplies derivatives along paths and adds contributions from different paths.
  • A weight gradient is its incoming activation times the receiving unit’s delta.
  • Store forward values and compute all gradients before updating.
  • Numerical differences check gradients but cost too much for routine training.
  • Repeated small factors can vanish; large factors can explode.
  • Dead ReLU units have zero activation gradients on all their inputs.

5.3 Train a neural network in practice

Network training needs more than a correct derivative. Starting weights, input scales, update settings, and held-out results all affect whether useful features are learned.

Break symmetry and scale signals

Initialize weights randomly so hidden units begin differently. If a layer's units have identical weights and the same outgoing connections, they compute the same values, receive the same updates, and remain copies. All-zero network weights create this symmetry. Biases can start at zero because random connection weights already distinguish units.

The random scale matters. Glorot, or Xavier, initialization is suited to tanh and sigmoid units; He initialization accounts for ReLU activations. These schemes aim to keep signal sizes from shrinking or growing too much from layer to layer.

Normalize inputs as well. Dividing pixel values by 255 puts them between zero and one. Standardization subtracts a feature's training mean and divides by its training standard deviation. Apply the same fitted transformation to later inputs. Moderate initial sums help sigmoid and tanh avoid saturated regions with very small derivatives; comparable feature scales also improve optimization.

Run the training loop
  1. Initialize the weights and choose the optimizer and settings.
  2. At each epoch's start, shuffle the training examples.
  3. For each mini-batch, run a forward pass and compute average loss.
  4. Backpropagate, then update all parameters using that batch's gradients.
  5. At the epoch's end, record training and validation results.

For 784 pixel inputs, 128 hidden ReLU units, and 10 softmax outputs, the parameter count is

784(128)+128+128(10)+10=101,770.

With 60,000 images and batch size 64, there are 937 full batches and one final batch of 32 images: 938 updates per epoch. The final short batch still uses its own average gradient.

Read training curves
Observed patternWhat to investigate
Loss jumps or becomes NaNLearning rate too large or unstable calculations
Loss falls very slowlyRate too small or gradients too weak
Training improves while validation worsensOverfitting and stopping time

These patterns guide diagnosis; several causes can share a symptom. For a slowly learning sigmoid network, inspect input scale and activation saturation along with the learning rate. A high training accuracy only shows fit to training examples. A large network can even memorize random labels.

The main hyperparameters include learning rate, batch size, epoch count, width, depth, activation, and optimizer. Compare them on validation data. Keep the test set for evaluating the selected configuration. Increasing width changes parameter count and capacity; increasing epochs gives the same parameters more update steps.

Network loss is nonconvex. Different random starts can reach different weights and accuracies. In large networks, saddle points and flat regions often slow progress more than poor local minima. Momentum and Adam help optimize such surfaces, but held-out performance still decides whether the fitted pattern is useful.

Key Takeaways

  • Random weights distinguish hidden units; all-zero network initialization creates symmetry.
  • Initialization scale and input normalization support stable signals.
  • The loop alternates forward pass, loss, backpropagation, and optimizer update.
  • Count mini-batch steps by rounding the examples-per-batch quotient upward.
  • Use training and validation curves together to investigate learning problems.
6

Recognize and control overfitting

A useful learned rule must survive beyond its training sample. Compare training and validation results to diagnose excessive flexibility or an overly restricted model, and separate those problems from changed data conditions. Weight penalties, early stopping, dropout, and valid data augmentation offer different ways to control overfitting. Their settings still need validation: stronger restrictions can remove real signal along with noise.

6.1 Diagnose overfitting and underfitting

A model can fit its training sample well without learning a dependable pattern. Compare training and held-out results to understand whether the model is too restricted, too flexible, or facing different data.

Compare two kinds of error

Generalization is performance on new examples from the same distribution. Underfitting occurs when the model is too restricted to capture the pattern. Overfitting occurs when it fits sample-specific noise so closely that new predictions suffer.

ModelTraining accuracyValidation accuracyInterpretation
A99%71%Large gap suggests overfitting
B74%73%Underfitting if stronger models can do better
C92%90%Best held-out performance here

Choose C from these validation results. A's higher training score is not an advantage on the held-out cases. B's small gap is not enough to make it good: both scores are low relative to what the task allows. Difficulty, noise, and achievable performance matter when interpreting a small gap.

Relate capacity to noise

Capacity describes how flexible the hypothesis family is. Ten noisy points may lie near a straight trend. A line uses two coefficients and misses the points slightly. A degree-9 polynomial uses ten coefficients and can interpolate all ten distinct input points, reaching zero training error. Between and beyond them, that polynomial can swing sharply and predict badly.

As capacity increases, training error generally falls. Held-out error often falls at first as genuine structure becomes representable, then rises as noise is fitted. Compare candidate capacities using held-out results. This familiar pattern is a guide to model choice, not a guarantee that every possible network-size curve has exactly that shape.

High bias means systematic error from a restrictive family. High variance means the learned rule changes substantially across training samples of the same size. Underfitting commonly involves high bias; overfitting commonly involves high variance.

Separate more data from different data

For fixed capacity, more representative examples usually reduce overfitting. A degree-9 polynomial cannot generally interpolate 1,000 noisy points exactly, so its fit must compromise. Large networks can still memorize large samples, including random labels. More data reduce risk without eliminating the need for held-out checks. Wrong or noisy labels add accidental patterns the learner might fit.

Distribution shift is a different problem. A classifier trained and tested on daytime photos can fail on night photos even when its daytime generalization is good. Those new inputs come from a different distribution. More regularization alone does not supply missing night conditions.

Preserve the meaning of the final test

Train candidates on the training set and compare their settings or capacities on validation data. Once a candidate is chosen, measure it on the untouched test set. Using test scores to change architecture or choose an epoch turns that set into another source of model selection, making its reported performance optimistic. Overfitting can affect polynomials, naive Bayes, perceptrons, and networks; it is a relationship between learning and data, not a property unique to one algorithm.

Key Takeaways

  • Overfitting combines strong training fit with weaker performance on new data.
  • Underfitting can produce similarly poor training and held-out results.
  • Capacity permits useful structure and accidental patterns to be fitted.
  • More representative data usually help at fixed capacity, but memorization remains possible.
  • Distribution shift differs from overfitting.
  • Use validation for choices and preserve the final test set.

6.2 Prevent overfitting with regularization

Regularization changes learning to improve predictions on new data. It can constrain weights, limit training duration, interrupt reliance on particular units, or supply more valid examples.

Penalize large weights

A regularized objective combines data loss and a complexity penalty:

J(𝐰)=L(𝐰)+λC(𝐰),λ≥0.

For L2, use C=∑iwi2, usually excluding the bias. Weights (3,−4) and λ=0.1 give penalty 0.1(9+16)=2.5. The added derivative is 2λwi. Under ordinary gradient descent,

wi←(1−2αλ)wi−α∂L∂wi.

With rate 0.1 and strength 0.1, the shrinkage factor is 0.98; a weight of 5 contributes 4.9 before the data-loss step. This is the weight-decay interpretation for this optimizer. With adaptive optimizers such as Adam, an L2 penalty and separately applied weight decay are different operations.

L1 uses C=∑i∣wi∣. It favors sparse solutions with many weights exactly zero, selecting features. L2 usually shrinks weights without making them exactly zero. Neither penalty is a rule to set every weight to zero.

The strength is a hyperparameter. Zero removes the penalty; excessive strength makes the model underfit. Compare values across orders of magnitude on validation data. A positive L2 penalty also controls the divergent weights of separable logistic regression.

Keep the best stopping point

Early stopping monitors validation loss, saves the best weights, and stops after a patience interval without improvement. For losses 0.62, 0.48, 0.41, 0.39, 0.40, 0.43, and 0.47 at epochs 1–7, the best epoch is 4. Patience 3 allows epochs 5–7, then stops and restores epoch 4's weights. The final trained epoch is not necessarily the saved model.

Train with dropout

At each training step, dropout independently sets hidden-unit outputs to zero with probability p. Units must learn without relying on a particular partner always being present. At prediction time dropout is disabled and all units participate.

In inverted dropout, divide surviving activations by 1−p during training. If p=0.5, surviving outputs double, so their expected value matches the undropped activation. This scaling is not applied again at prediction time.

Add valid variation

Collecting more representative data and using a simpler model can reduce overfitting. Data augmentation adds transformed training examples whose labels stay correct, such as suitable shifts, crops, or brightness changes. A transformation must suit the task: rotating a handwritten 6 by 180° can change it into a 9, so keeping label 6 would teach the wrong relationship.

Laplace smoothing is another regularizer: pseudo-counts make naive Bayes less dependent on sparse counts. Use validation data to choose smoothing, penalties, dropout rates, or stopping times. Watch both training and validation error so protection against overfitting does not become excessive restriction.

Key Takeaways

  • L2 penalizes squared weights; L1 favors sparse weights.
  • Regularization strength trades data fit against restrictions and is selected on validation data.
  • Early stopping restores the best validation checkpoint.
  • Inverted dropout rescales surviving training activations and is disabled for prediction.
  • Augmentation must preserve the correct label.
  • Smoothing, simpler models, and more representative data also help control overfitting.
  • L2 shrinkage under gradient descent must be distinguished from adaptive weight-decay implementations.

Supervised Learning and Neural Networks examples

6 Walkthroughs

1

Set up and check a supervised task

10 steps
Connect labels, feature vectors, scores, losses, and held-out performance.
  1. 1
    IntroductionTurn examples into a learning task

    A supervised learner needs paired inputs and answers. Before choosing an algorithm, identify what one case means and what output is wanted.

    Follow an email filter from its labels to a numerical representation and a loss. The final check is whether its learned rule works on fresh cases, so fitting and assessment need separate data roles.

  2. 2
    ExampleIdentify the case and label

    For a spam filter, one case is an email. Inputs can record "contains free," number of links, and whether the sender is a contact. The label is spam or ham, meaning wanted email.

    The learner fits a hypothesis from 5,000 labeled examples. That hypothesis takes a new email's features and predicts its label. Its learned weights are parameters; settings such as model size are hyperparameters.

  3. 3
    ExplanationKeep fitting and assessment separate

    Use training data to fit parameters and validation data to compare settings. Keep test cases untouched until the model has been selected.

    This matters even if a memorizing rule gets every training email right. Its stored answers may say little about unfamiliar messages. Held-out performance represents future performance when the examples are independent draws from the same distribution; changed spam wording can break that connection.

  4. 4
    ChallengeClassify the prediction task

    A weather service wants one model to predict rainfall in millimeters and another to predict whether more than 5 mm will fall. How do their task types differ?

    ---reveal---

    The measured amount is a regression target. The yes/no event is a binary classification target. Both can use labeled historical weather cases; the fact that each concerns future weather does not make either unsupervised learning.

  5. 5
    ExplanationChoose a numerical representation

    A feature vector lists properties in a fixed order. Binary indicators represent yes/no facts, counts represent occurrences, and real numbers represent measurements.

    For unordered colors, use one-hot indicators: red is (1,0,0) and blue is (0,0,1). Codes 1, 2, and 3 would impose an artificial numeric relationship. Add a separate first coordinate fixed at 1 when the model uses a bias inside its dot product.

  6. 6
    ExampleAdd weighted contributions

    Take augmented input 𝐱=(1,3,4) and weights 𝐰=(2,−1,0.5). Multiply matching coordinates, then add:

    z=2(1)−1(3)+0.5(4)=1.

    The constant first input makes 2 the bias contribution. Increasing the second coordinate lowers the score because its weight is negative. This calculation produces a score; a classifier still needs a rule connecting scores to class predictions.

  7. 7
    ExampleMeasure prediction cost

    For numerical predictions (2,4,7) against targets (3,4,5), the squared errors are 1, 0, and 4.

    mean squared error=(1+0+4)/3=5/3.

    Squaring before averaging prevents signed errors from canceling. Squared loss emphasizes large misses: doubling an error quadruples its loss. For classification, averaging 0/1 losses instead gives the fraction of wrong predictions.

  8. 8
    ChallengeCalculate a score and its loss

    A numerical predictor has augmented input (1,2) and weights (1,2). Its target is 7. What prediction and squared loss result?

    ---reveal---

    The dot product is 1(1)+2(2)=5. The squared loss is (7−5)2=4. The target is used to measure the prediction's error; it is not another input coordinate. An absolute-loss calculation would give 2, a different cost for the same miss.

  9. 9
    ChallengeChoose what the result supports

    A team adds many word features and reduces training error to zero, but validation error rises. Should it choose this model because every training label is now correct?

    ---reveal---

    No. Extra features gave it more ways to fit the training sample, but the held-out comparison became worse. Use validation results to compare the candidates, then assess the selected model on untouched test cases. The objective is useful predictions on new inputs.

  10. 10
    RecapKeep the learning roles clear

    Start with input–label pairs and a family of possible prediction rules. Represent each input consistently, compute the prediction, and use the chosen loss to measure its cost.

    Training fits parameters. Validation guides model choices. Testing assesses the selected result. Accuracy and loss describe performance on particular cases; applying those results to future inputs also depends on how the cases were sampled.

2

Predict with naive Bayes and word counts

15 steps
Build class scores, estimate smoothed probabilities, and keep binary and token models distinct.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionCombine class evidence by counting
  2. 2
    ExplanationBuild a score for each class
  3. 3
    ExampleInclude a missing binary feature
  4. 4
    ExampleNormalize and compare logs
  5. 5
    ChallengeUse both observed values
  6. 6
    ExampleEstimate within each class
  7. 7
    ExplanationProtect an unseen outcome
  8. 8
    ChallengeSmooth a binary feature
  9. 9
    TipSet smoothing with held-out evidence
  10. 10
    ExplanationChange from indicators to token counts
  11. 11
    ExampleSmooth over a vocabulary
  12. 12
    ExampleKeep every repeated word
  13. 13
    ChallengeUse repeated-token evidence
  14. 14
    ChallengeRepair a model mismatch
  15. 15
    RecapMatch evidence to the probability model
3

Move boundaries and fit class probabilities

17 steps
Read geometry, trace perceptron corrections, and interpret sigmoid and softmax outputs.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionLearn from a weighted score
  2. 2
    ExampleRead the boundary
  3. 3
    Key InsightSeparate score from distance
  4. 4
    ExampleChange features for XOR
  5. 5
    ChallengePredict after changing the bias
  6. 6
    ExplanationUpdate only on mistakes
  7. 7
    ExampleTrace the first two mistakes
  8. 8
    ExampleCheck the next full pass
  9. 9
    ChallengeCarry the current weights forward
  10. 10
    ConnectionRaise one class and lower another
  11. 11
    ExplanationTurn a score into probability
  12. 12
    ExampleScore the observed label
  13. 13
    Key InsightConvexity does not bound weights
  14. 14
    ChallengeFind a log loss
  15. 15
    ConnectionNormalize several class scores
  16. 16
    ChallengeCompare two learning signals
  17. 17
    RecapConnect representation and learning
4

Follow gradients and average updates

13 steps
Compute descent steps, derive the logistic gradient, and reason about mini-batch scale.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionUse derivatives to improve weights
  2. 2
    ExplanationRead the gradient
  3. 3
    ExampleMake a simultaneous step
  4. 4
    ExampleCheck what the rate changes
  5. 5
    ChallengeDifferentiate before stepping
  6. 6
    TipMatch scales to optimization
  7. 7
    ExplanationChoose a gradient sample
  8. 8
    ExplanationSimplify the logistic derivative
  9. 9
    ExampleRun a logistic stochastic update
  10. 10
    ChallengeAverage before updating
  11. 11
    ConnectionManage noisy directions
  12. 12
    ChallengeDiagnose a change in batch size
  13. 13
    RecapSeparate direction, size, and sampling
5

Compute and train a small network

20 steps
Trace nonlinear activations, backpropagation, and the practical training loop.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow values forward and derivatives backward
  2. 2
    ExplanationCompute one unit
  3. 3
    ExampleCount a small network
  4. 4
    ExampleBuild nonlinear features for XOR
  5. 5
    ChallengeKeep output activation separate
  6. 6
    ConnectionMatch output to the task
  7. 7
    ExplanationStore the forward state
  8. 8
    ExampleFind the output-weight gradient
  9. 9
    ExampleCarry the signal to the hidden weight
  10. 10
    ExampleUpdate both weights together
  11. 11
    ChallengeDifferentiate through an active unit
  12. 12
    TipCheck a derivative numerically
  13. 13
    Key InsightNotice weakened backward signals
  14. 14
    ExplanationStart units differently
  15. 15
    ExampleCount parameters and batch steps
  16. 16
    ExplanationRun one batch, then monitor the epoch
  17. 17
    ChallengeChoose a response to the curves
  18. 18
    ChallengeSeparate poor learning from low capacity
  19. 19
    ConnectionRepresentations depend on training
  20. 20
    RecapCoordinate the entire training step
6

Diagnose and control overfitting

13 steps
Compare fit, apply regularization, and preserve an independent final test.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFind the fit that survives new data
  2. 2
    ExampleCompare held-out performance
  3. 3
    ExplanationConnect capacity with sample noise
  4. 4
    ChallengeDiagnose a richer model
  5. 5
    ConnectionSeparate changed conditions from noise fitting
  6. 6
    ExplanationAdd a weight penalty
  7. 7
    ExampleDerive L2 shrinkage
  8. 8
    ChallengeChoose a sparse fit
  9. 9
    ExampleRestore the best checkpoint
  10. 10
    ExplanationKeep dropout expectations stable
  11. 11
    ChallengeCheck an augmentation label
  12. 12
    ChallengeChoose the final evaluation order
  13. 13
    RecapUse the right control for the observed problem

Supervised Learning and Neural Networks practice questions

50 Practice Questions in 5 sets

Set 1: Counts, updates, and training behavior10 Practice Questions

Question 1 of 10

A developer fits network weights on one data split and compares hidden-layer sizes on a second split. What is the second split’s role?
  1. Training: it supplies the fitted weight updates.
  2. Testing: it supplies an untouched final assessment.
  3. Unsupervised learning: it replaces missing labels.
  4. Validation: it informs the architecture choice.
Show answerHide answer
Answer: D
Comparing hidden-layer sizes is model selection, so the second split is validation data. The weights are fitted on training data, while the test set is reserved for assessing the already selected configuration. Calling the selection split a test set would not keep it independent of those choices.

Question 2 of 10

A multinomial text model has class-M token total 80 and vocabulary size 20. The word "orbit" appears 3 times in class M. What probability does add-one smoothing assign to this word within M?
  1. 4/100
  2. 4/82
  3. 3/80
  4. 4/81
Show answerHide answer
Answer: A
Token smoothing gives (3+1)/(80+1(20))=4/100. The denominator receives one pseudo-count for each of the 20 vocabulary words. Adding 2 instead would treat the word as a binary present/absent feature, which is the wrong event space for this multinomial model.

Question 3 of 10

Two class-specific binary features have the same observed relative frequency, 1/5 and 100/500. Why does add-one smoothing alter the first estimate more?
  1. The larger sample has more possible binary outcomes in its denominator.
  2. The fixed pseudo-counts form a larger share of the smaller sample.
  3. The smaller sample receives a larger pseudo-count for each observed success.
  4. The larger sample is kept unsmoothed because its frequency is already known.
Show answerHide answer
Answer: B
Both estimates receive one pseudo-count per outcome, but those two extra observations are much more influential beside 5 observations than beside 500. The smoothed values are 2/7 and 101/502. Sample size changes the relative influence of smoothing; it does not change a binary feature’s two possible values.

Question 4 of 10

A zero-initialized perceptron sees augmented inputs (1,2) with label −1, then (1,−1) with label +1. Zero scores predict +1. What are its weights after these two examples?
  1. (0,−3)
  2. (0,3)
  3. (−1,−2)
  4. (1,−1)
Show answerHide answer
Answer: C
The first zero score is wrongly positive, so subtracting the first input gives (−1,−2). The second score is −1+2=1, already correct, so no update follows. Thus the final weights are (−1,−2), not (0,−3), which would add the second input despite its correct prediction.

Question 5 of 10

A binary logistic model predicts p=0.75 for an example whose target is 0. What is its log loss?
  1. Approximately 0.288.
  2. Approximately 0.750.
  3. Approximately 1.386.
  4. Approximately 0.563.
Show answerHide answer
Answer: C
The observed target is 0, so its assigned probability is 1−p=0.25 and the loss is −ln⁡0.25≈1.386. Using −ln⁡0.75≈0.288 would score a target of 1. Log loss always uses the probability of the class that actually occurred.

Question 6 of 10

A logistic model starts with zero weights and sees augmented input (1,4) with target 0. What weights result from one SGD step with rate 0.2?
  1. (0.1,0.4)
  2. (−0.1,−0.4)
  3. (−0.2,−0.8)
  4. (0,0)
Show answerHide answer
Answer: B
The initial score is zero, so p=0.5. The correction is 0.2(0−0.5)(1,4)=(−0.1,−0.4). A full negative input step would use a hard perceptron-style correction; logistic regression instead scales the update by the probability error, here one half.

Question 7 of 10

Let h=ReLU⁡(ax), y^=bh, and L=(y^−y)2. At x=3,a=1,b=2,y=4, what is ∂L/∂a?
Show answerHide answer
Answer: A
The hidden value is 3, prediction is 6, and output-loss derivative is 2(6−4)=4. The active ReLU contributes derivative 1, so the chain gives 4(2)(1)(3)=24. Stopping at 12 omits the output weight 2, which carries the backward signal from prediction to hidden activation.

Question 8 of 10

A network uses identical zero weights for all connections. Why can its hidden units fail to learn different features?
  1. They begin at a global loss minimum, so every labeled example has already been fitted.
  2. They begin with different gradients, but zero biases force those gradients to disappear.
  3. They begin with excessive capacity, so increasing training epochs immediately removes symmetry.
  4. They begin with the same outputs and gradients, so equal updates preserve their symmetry.
Show answerHide answer
Answer: D
Identical units and connections have no initial distinction for learning to amplify: the same forward values lead to matching backward signals and updates. Random connection weights break that symmetry. Zero biases can be used with random weights; the problem is the identical network initialization, not zero biases by themselves.

Question 9 of 10

A classifier performs well on fresh daytime images from its training population, but poorly on night images absent from training. What problem is directly indicated?
  1. Overfitting established by a large daytime training–validation gap.
  2. Distribution shift between the represented and new conditions.
  3. Underfitting established by poor performance on the training images.
  4. Label noise established by contradictory labels in the training set.
Show answerHide answer
Answer: B
Night images change the conditions represented by the data, so this is distribution shift. The model already performs well on fresh daytime cases, and the stem supplies no evidence of a large daytime gap or contradictory labels. Stronger regularization alone cannot provide the missing night-image experience.

Question 10 of 10

Validation losses at epochs 1–6 are 0.54, 0.43, 0.38, 0.40, 0.39, and 0.42. Early stopping uses patience 3 and restores the best checkpoint. When does it stop, and which epoch is restored?
  1. Stop after epoch 6; restore epoch 6.
  2. Stop after epoch 5; restore epoch 3.
  3. Stop after epoch 6; restore epoch 3.
  4. Stop after epoch 4; restore epoch 3.
Show answerHide answer
Answer: C
Epoch 3 has the lowest loss, 0.38. Epochs 4, 5, and 6 all fail to improve on it, so three consecutive non-improving epochs trigger stopping after epoch 6 and restoration of epoch 3. The drop from 0.40 to 0.39 is still above the best checkpoint and does not reset patience.
Set 2: From labeled examples to learned predictions10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A network has two inputs, three fully connected hidden units, and one fully connected output unit. Every receiving unit has a bias. How many trainable parameters does it have?
  1. 9 parameters.
  2. 10 parameters.
  3. 12 parameters.
  4. 13 parameters.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

For L(w)=(w−4)2, start at w=1 and use learning rate 0.2. What is the weight after one gradient descent step?
  1. −0.2
  2. 1.6
  3. 2.2
  4. 3.4
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A sensor model predicts the water temperature in °C for the next hour. What kind of supervised task is this?
  1. Binary classification, because the prediction concerns one hour.
  2. Multiclass classification, because temperatures have many values.
  3. Regression, because the target is a numerical measurement.
  4. Unsupervised learning, because the target describes the future.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Weights are (1,−2,0.5) and the augmented input is (1,2,6). What score does the model compute?
  1. −1
  2. 0
  3. 8
  4. 2
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Class A has prior 0.25 and P(F=1∣A)=0.8. Class B has prior 0.75 and P(F=1∣B)=0.2. What is P(A∣F=1)?
  1. Approximately 0.571.
  2. Approximately 0.800.
  3. Approximately 0.200.
  4. Approximately 0.250.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A binary feature is present in 4 of the 18 class-C examples. What is its add-one-smoothed probability of being present within C?
  1. 5/19
  2. 4/18
  3. 5/18
  4. 5/20
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A binary classifier has augmented weights (−4,2,1). What class does it assign to the point (1,2) under the zero-score-positive convention?
  1. Class −1, because the score is 0.
  2. Class +1, because the score is 0.
  3. Class +1, because the score is 4.
  4. Class −1, because the score is −4.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A perceptron starts at zero weights and processes augmented inputs (1,2) with label −1, (1,3) with label +1, then (1,−1) with label −1. Zero scores predict +1. What are its final weights?
  1. (−1,2)
  2. (−1,−2)
  3. (1,0)
  4. (0,1)
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A logistic model assigns probability 0.8 to class 1. What are the odds of class 1 against class 0?
  1. 4 to 1.
  2. 0.8 to 1.
  3. 1.25 to 1.
  4. 1 to 4.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Three models are evaluated on the same representative validation set. P scores 100% training and 78% validation; Q scores 86% and 85%; R scores 96% and 93%. A developer selects R, then reports its untouched test accuracy. Why is this selection reasonable?
  1. R has the best validation result; P’s perfect training fit does not outweigh its poorer held-out result.
  2. P has the best learned rule; its validation deficit should be ignored because it fits all training labels.
  3. Q has the best learned rule; the smallest training–validation gap always gives the best new predictions.
  4. R is reasonable only if its test score was first used to choose its architecture and training duration.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Combine model calculations and learning rules10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A model predicts 6 for a target of 9. What squared loss does this single prediction have?
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A Bernoulli naive Bayes model has priors P(A)=0.4 and P(B)=0.6. The yes-probabilities for features U and V are (0.75,0.2) in A and (0.25,0.5) in B. For U present and V absent, what is the posterior for A?
  1. Approximately 0.444.
  2. Approximately 0.667.
  3. Approximately 0.240.
  4. Approximately 0.762.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A multinomial naive Bayes model has two document classes with equal priors. For "pulse pulse beam," the likelihood ratios A/B are 3 for "pulse" and 1/2 for "beam." What is the posterior probability of A?
  1. 3/5
  2. 9/11
  3. 9/2
  4. 3/11
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

XOR labels (0,0) and (1,1) negative, and (1,0) and (0,1) positive. Using features (1,x1,x2,x1x2), what weights classify all four points correctly?
  1. (−1,2,2,−4)
  2. (−1,2,2,−2)
  3. (−3,2,2,0)
  4. (−1,−2,−2,4)
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A multiclass perceptron predicts A for augmented input (1,3), whose true class is C. Current vectors are wA=(2,0), wB=(0,0), and wC=(0,0.5). What vectors result?
  1. wA=(3,3), wB=(0,0), wC=(−1,−2.5)
  2. wA=(2,0), wB=(0,0), wC=(1,3.5)
  3. wA=(1,−3), wB=(0,0), wC=(1,3.5)
  4. wA=(1,−3), wB=(−1,−3), wC=(1,3.5)
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

For L(w)=3(w−2)2, a nonoptimal starting weight must converge to 2 under a fixed positive gradient descent rate. What is the full interval of learning rates that ensures convergence?
  1. 0<α<1
  2. 0<α<2/3
  3. 0<α<1/3
  4. 0<α<1/6
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A two-example mini-batch gives logistic gradients (0.2,0.6) and (−0.4,0.2) at weights (1,1). What weights follow an averaged update with learning rate 0.5?
  1. (1.05,0.8)
  2. (1.1,0.6)
  3. (0.95,1.2)
  4. (0.9,0.7)
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A network uses h1=ReLU⁡(2x−1), h2=ReLU⁡(1−x), and output h1−3h2. What is its output for x=0.5?
  1. 0.5
  2. 1.5
  3. −0.5
  4. −1.5
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A parameter w feeds two branches: a=2w and b=w2, with output u=a+b and loss L=(u−1)2. What is dL/dw at w=1?
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Two non-bias weights are 2 and −3. With L2 strength 0.2 and learning rate 0.1, what are the weights after a step whose data-loss gradient is zero?
  1. (1.92,−2.88)
  2. (1.96,−2.94)
  3. (2.08,−3.12)
  4. (1.8,−2.8)
Show answerHide answer

Save this lesson to see this answer.

Set 4: Diagnose models and preserve valid comparisons10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A team compares 20 learning rates using one held-out set, then publishes the best score from that same set as its final performance estimate. What should change?
  1. Use that set for validation and assess the chosen model on a separate untouched test set.
  2. Use the training set for choosing rates and keep the current best held-out score as the test estimate.
  3. Average the 20 held-out scores and report that average as the selected model’s final test score.
  4. Choose the largest learning rate and reuse the held-out set because the selection is now deterministic.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A predictor gives outputs (1,5,6) for targets (2,3,6). What is its mean squared error?
  1. 1
  2. 5
  3. 5/3
  4. 1/3
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Two naive Bayes class log scores are −42 and −39. Which class has the larger unnormalized probability?
  1. The class with log score −42.
  2. The class with log score −39.
  3. Both classes, since both log scores are negative.
  4. Neither class, since valid probabilities need positive log scores.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A categorical feature has four possible values. In one class, their counts are 0, 2, 3, and 5. What add-0.5 probability vector preserves the observed ordering and normalization?
  1. (0.5,2.5,3.5,5.5)/10.5
  2. (0.5,2.5,3.5,5.5)/11
  3. (0,2,3,5)/12
  4. (0.5,2.5,3.5,5.5)/12
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A classifier has weights (−6,3,4) and receives point (2,1). Another classifier multiplies all three weights by 2. How do the prediction and geometric boundary distance compare?
  1. Both predict +1; distances are 0.8 and 1.6.
  2. Both predict +1; both distances are 0.8.
  3. The signs differ; both distances are 0.8.
  4. Both predict +1; distance halves to 0.4.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Three softmax scores are 0,ln⁡2,ln⁡3, and the second class is correct. What is the cross-entropy loss after adding 7 to every score?
  1. ln⁡3≈1.099
  2. ln⁡2≈0.693
  3. ln⁡6≈1.792
  4. ln⁡3+7≈8.099
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

For L(a,b)=(a+b−1)2 at (a,b)=(0,0), use learning rate 0.1. What pair results from a correct simultaneous gradient descent update?
  1. (0.2,0.16)
  2. (−0.2,−0.2)
  3. (0.1,0.1)
  4. (0.2,0.2)
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A unit has h=ReLU⁡(wx+b), output y^=2h, and squared loss against target 1. At w=−2,b=1,x=1, what is the gradient with respect to w?
  1. −4.
  2. −2.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A training set has 1,030 examples. The batch size is 128, and the final partial batch is used. How many updates occur in one epoch, and how many examples are in the last batch?
  1. 8 updates; 128 examples in the last batch.
  2. 9 updates; 6 examples in the last batch.
  3. 9 updates; 122 examples in the last batch.
  4. 8 updates; 6 examples in the last batch.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A small model performs poorly on both training and validation data. A larger model, trained on the same examples, improves both scores substantially and leaves only a small gap. What diagnosis and response best fit this evidence?
  1. The small model overfit; added capacity removed its sample sensitivity.
  2. The larger model underfits more; a small gap always signals insufficient flexibility.
  3. The larger model faces distribution shift; its improved validation score shows changed sampling.
  4. The small model underfit; added capacity captured structure that it missed.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Transfer the methods to new learning problems10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A feature records one of four unordered machine modes. What encoding avoids imposing a numerical ranking on those modes?
  1. One integer from 1 through 4, treated as a measured quantity.
  2. Four indicators, with exactly one equal to 1 for each case.
  3. One rank from 0 through 3, ordered by the spelling of each mode.
  4. Four equal indicators, each holding the mode’s assigned integer.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A text classifier uses multinomial token probabilities. A document contains one vocabulary word four times and a second word once; a developer counts each word only once and also multiplies factors for absent vocabulary words. What must be changed?
  1. Keep one contribution per word but omit all class priors from the document score.
  2. Use four contributions for the repeated word and retain every absent-word factor.
  3. Keep one contribution per word and switch only the smoothing denominator to two outcomes.
  4. Use four contributions for the repeated word and omit separate absent-word factors.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A zero-initialized binary perceptron uses a fixed positive learning rate. A second run multiplies that rate by 5 and processes exactly the same examples in the same order. How do their mistake sequences compare?
  1. They are identical because every weight vector in the second run is scaled by 5.
  2. They differ because a larger update must correct each example in fewer steps.
  3. They are identical only if the data are separable and the bias is excluded.
  4. They differ because scaling weights moves the zero-score decision boundary.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A logistic model separates every training example correctly, but its unregularized log loss keeps falling as all weights grow. What explains the behavior, and what fitting change addresses it?
  1. Convexity requires a finite optimum at zero weights; keep increasing the learning rate.
  2. Perfect classification forces log loss to zero immediately; replace the labels with ±1.
  3. Separability allows no finite maximum-likelihood optimum; add a positive weight penalty.
  4. A hidden local minimum traps the model; add identical zero-initialized hidden units.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A logistic mini-batch contains augmented inputs (1,2) with target 1 and (1,−2) with target 0. Starting from zero weights, what pair results from one average-gradient step at rate 0.4?
  1. (0,0.8)
  2. (0.2,0.4)
  3. (0,−0.4)
  4. (0,0.4)
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A network gains more hidden layers, but every activation remains linear. What happens to its representable function family?
  1. It gains curved decision boundaries solely from the additional depth.
  2. It can represent XOR because each extra bias supplies a nonlinear feature.
  3. It still computes an affine transformation of the original input.
  4. It becomes a probability model because linear outputs sum to one.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

For h=ReLU⁡(ax), y^=bh, and L=(y^−y)2, use x=1,a=2,b=1,y=0 and rate 0.1. What simultaneous weight update follows one backpropagation pass?
  1. (a,b)=(1.6,0.2)
  2. (a,b)=(1.6,0.36)
  3. (a,b)=(1.2,0.6)
  4. (a,b)=(2.4,1.8)
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A sigmoid network’s training loss barely changes. Its inputs are unscaled large measurements, hidden activations are near 0 or 1, and early-layer gradients are tiny. What intervention directly addresses the evidence?
  1. Raise the learning rate sharply while keeping the same saturated activations.
  2. Scale the inputs and use suitable random initialization to reduce saturation.
  3. Increase the number of saturated layers to accumulate stronger derivatives.
  4. Initialize every connection at the same zero value to remove random variation.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A unit’s activation before dropout is 3. Inverted dropout independently drops it with probability 0.25. What value is used when it survives training, and what value is used at prediction time?
  1. 3 during surviving training steps; 2.25 at prediction time.
  2. 4 during surviving training steps; 4 at prediction time.
  3. 4 during surviving training steps; 3 at prediction time.
  4. 2.25 during surviving training steps; 3 at prediction time.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A digit classifier overfits. A team proposes stronger L2, random image shifts that retain the digit, and 180° rotations that leave all labels unchanged. What revision best preserves useful regularization?
  1. Tune L2 and retain valid shifts; reject rotations that change a digit’s label.
  2. Keep every proposed transformation; more training images always outweigh wrong labels.
  3. Reject shifts and tune rotations on the test set to select the strongest augmentation.
  4. Set all weights to zero with very strong L2 before deciding whether rotations change labels.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

86 Key Terms, each with its definition

A

Activation function
An activation function transforms a unit’s weighted sum and bias into its output; nonlinear activations give networks nonlinear expressive power.
Applying ReLU after a hidden weighted sum prevents the whole network from collapsing into one affine map.
Adam
Adam is an optimizer that combines a moving average of gradients with adaptive per-parameter step sizes derived from recent squared-gradient information.
Adam still needs a suitable overall learning rate even though individual weights receive adapted steps.
Averaged perceptron
An averaged perceptron predicts with weights averaged across training steps, reducing reliance on the last weight vector produced by learning.
On noisy nonseparable data, averaging can give more stable predictions than using the final update alone.

B

Backpropagation
Backpropagation efficiently computes loss derivatives through a computation graph by propagating chain-rule signals backward through stored forward values.
A hidden weight’s derivative combines its input activation with the downstream loss signal reaching its unit.
Bag of words
A bag of words represents a document by vocabulary-word counts while discarding order, so different word sequences can share a representation.
The phrases "the cat saw the dog" and "the dog saw the cat" have identical bags of words.
Batch gradient descent
Batch gradient descent uses the average loss gradient across the entire training set for each parameter update, making each step computationally costly.
A batch method reads every example before producing one exact empirical-loss gradient update.
Bernoulli naive Bayes
Bernoulli naive Bayes models binary feature values, using one present-or-absent event per vocabulary word and class in a text classifier.
Repeating a word leaves its presence indicator unchanged, while absent vocabulary words still supply evidence.
Bias
A bias is a learned constant contribution that shifts a model’s score independently of its varying features, allowing an offset decision boundary.
Adding an input fixed at 1 lets its weight act as the bias within the same dot product.
Bigram
A bigram is a feature representing two adjacent words, allowing a text model to retain some local ordering that single-word counts discard.
The bigram "not good" can distinguish a negative phrase from an isolated occurrence of "good".

C

Chain rule
The chain rule differentiates a composition by multiplying local derivatives along dependencies and summing contributions from multiple paths.
A loss derivative passes through an output weight, an activation, and an input multiplier to reach a hidden weight.
Class prior
A class prior is the model’s probability for a class before the current input’s feature evidence is incorporated into its prediction.
A rare class can need stronger feature evidence to overcome its smaller prior probability.
Classification
Classification predicts one category from a specified set of classes, using a learned rule to assign new inputs to those categories.
Predicting whether a component will pass or fail inspection is a binary classification task.
Computation graph
A computation graph represents a calculation as linked elementary operations, making paths of dependence explicit for forward values and derivatives.
If one weight affects two branches, their backward derivative contributions must be added.
Conditional independence
Conditional independence means knowing one variable adds no information about another after the conditioning variable’s value is known.
Naive Bayes assumes word indicators are independent within a class, even when real words often occur together.
Convex loss
A convex loss lies below straight chords between parameter points, ensuring that any local minimum is also a global minimum.
Logistic log loss is convex in its weights, while a multilayer network’s loss is generally nonconvex.

D

Data augmentation
Data augmentation creates additional training examples through transformations that preserve correct labels, adding useful variation without new manual labeling.
A small image shift may keep a digit label valid, while rotating a 6 into a 9 can make that label wrong.
Dead ReLU
A dead ReLU is a unit whose preactivation remains negative for all relevant inputs, making its output and local activation derivative zero.
Loss error downstream cannot update its incoming weights through a zero ReLU derivative.
Decision boundary
A decision boundary is the set of inputs at which the class decision switches; for a nondegenerate binary linear rule, its score is zero.
A point can lie on the boundary and still receive a class through the classifier’s explicit tie rule.
Distribution shift
Distribution shift is a change between the population represented by training data and the population encountered when the model makes predictions.
A daytime-only photo model can fail at night even if its held-out daytime performance is strong.
Dot product
A dot product is the sum of products of matching vector coordinates; models use it to combine feature values with their corresponding weights.
Multiplying each feature by its weight and adding the contributions gives the classifier’s score.
Dropout
Dropout randomly sets hidden-unit outputs to zero during training, reducing reliance on particular other units always being available.
Inverted dropout rescales surviving activations during training and disables the random masking for prediction.

E

Early stopping
Early stopping limits training when validation performance stops improving and restores the checkpoint with the best recorded validation loss.
The selected weights can come from an earlier epoch even though later epochs continued lowering training loss.
Empirical loss
Empirical loss is the average prediction loss on an observed sample, usually the training set whose examples are used to fit the model.
A model can reduce empirical loss by memorizing training details that fail to help on fresh inputs.
Epoch
An epoch is one full pass through the training set, including every example; its number of parameter updates depends on the learning method.
A perceptron stops when a complete epoch has no mistakes, while a network often updates once per batch.

F

Feature vector
A feature vector is an ordered list of numerical properties describing one input, with the same coordinate meanings used for every example.
An image vector can list pixel intensities, while an email vector can list word indicators and a link count.
Feedforward network
A feedforward network arranges units in directed layers without cycles, computing successive representations from the input to the output.
A hidden layer receives the input vector, transforms it, and sends its activations to the next layer.
Fully connected layer
A fully connected layer links every incoming activation to every receiving unit, with a separate trainable weight for each connection.
Four inputs feeding three units give 12 weights plus three biases when each receiving unit has a bias.

G

Generalization
Generalization is a learned model’s ability to perform well on new examples from the distribution it was intended to learn.
Fresh examples from the same population test whether the learned pattern extends beyond remembered training cases.
Generative model
A generative model describes the class prior and how inputs arise within each class, enabling class prediction through Bayes’ rule.
Naive Bayes estimates feature distributions for spam and ham, while logistic regression fits class probabilities directly.
Gradient
A gradient is the vector of partial derivatives of a scalar function and points toward its steepest local increase in Euclidean coordinates.
For loss w₁² + 3w₂², the gradient at (2, 1) is (4, 6), so descent moves against that vector.
Gradient clipping
Gradient clipping limits the size of a computed gradient before the update, reducing instability caused by excessively large backward signals.
Clipping can control an exploding signal but does not create a signal for a dead ReLU unit.
Gradient descent
Gradient descent repeatedly subtracts a learning-rate-scaled gradient from current parameters to seek smaller values of an objective function.
All weight gradients for a simultaneous update are calculated at the same current parameter state.

H

He initialization
He initialization chooses a random weight scale designed for rectified activations, helping maintain signal sizes through layers using ReLU.
A ReLU network can begin with He-scaled weights instead of an arbitrary tiny random scale.
Hidden layer
A hidden layer is an internal network layer between input and output whose trainable units form intermediate features used by later layers.
Two hidden ReLU units can transform the binary inputs so a linear output computes XOR.
Hyperparameter
A hyperparameter is a setting that controls the model or learning process and is chosen using validation results rather than fitted weight updates.
The learning rate and hidden-layer width are hyperparameters; fitted connection weights are parameters.
Hyperplane
A hyperplane is a flat boundary one dimension below its feature space, specified by one nondegenerate linear equation with a possible offset.
A line in a two-feature space and a plane in a three-feature space are examples of hyperplanes.
Hypothesis space
A hypothesis space is the family of prediction functions available to a learner; its parameters select one function from that family.
Restricting a learner to straight-line boundaries defines a narrower hypothesis space than allowing a network.

I

Initialization
Initialization assigns starting parameter values before optimization; suitable random scales break unit symmetry and keep signals manageable across layers.
Random connection weights allow hidden units to learn different features even when all biases start at zero.

L

L1 regularization
L1 regularization penalizes the sum of absolute weight values and favors sparse fitted models that assign exactly zero weight to many features.
An L1-regularized model can ignore unhelpful inputs through zero coefficients while retaining useful ones.
L2 regularization
L2 regularization penalizes the sum of squared weights, usually excluding the bias, discouraging large weights while typically keeping them nonzero.
For weights 3 and −4, strength 0.1 contributes a penalty of 2.5 to the training objective.
Label
A label is the supplied target output for one training example, such as a category in classification or a measured value in regression.
For a labeled digit image, the label names the digit that the classifier should recognize.
Laplace smoothing
Laplace smoothing adds a pseudo-count to each possible outcome, preventing zero estimates and reducing dependence on sparse observed counts.
Add-one smoothing turns 0 occurrences in 60 binary cases into a present-value estimate of 1/62.
Learning rate
A learning rate is the positive scale factor that converts a gradient into an update step, controlling how far parameters move during optimization.
An excessive learning rate can turn stable progress toward a loss minimum into oscillation or divergence.
Learning-rate schedule
A learning-rate schedule changes the update scale during training, often reducing it so noisy updates settle more closely around a solution.
A large early step size can support progress, while smaller later steps reduce persistent fluctuations.
Linear classifier
A linear classifier predicts a class from weighted input scores, with a binary decision made by which side of a zero-score boundary contains the input.
A bias of −3 and two weights of 1 create the two-feature decision boundary x₁ + x₂ = 3.
Linear separability
Linear separability is the existence of a linear classifier that correctly separates every labeled training example in the chosen feature representation.
XOR is not separable in its two original binary features, but an interaction feature changes the representation.
Log loss
Log loss is the negative logarithm of the probability assigned to the observed label, giving increasingly large penalties to confident wrong predictions.
A prediction of class-1 probability 0.9 has much larger loss when the true label is 0 than when it is 1.
Log score
A log score is the logarithm of an unnormalized class probability, computed as a log prior plus a sum of feature log likelihoods.
A log score of −12 ranks above −15 because taking logarithms preserves the order of positive products.
Log-odds
Log-odds are the natural logarithm of a probability divided by its complement; logistic regression models this quantity as a linear score.
Increasing a feature by one unit adds its weight to log-odds while the other inputs remain fixed.
Logistic regression
Logistic regression is a discriminative classifier that models class-1 probability by applying a sigmoid to a linear score and fits it with log loss.
The score threshold zero corresponds to probability 0.5, so the usual binary boundary is still linear.
Loss function
A loss function assigns a cost to a prediction compared with its target, specifying which kinds and sizes of errors learning should penalize.
Squared loss gives a temperature error of 6 a cost four times that of an error of 3.

M

Margin
A separating margin is the smallest positive signed score across labeled inputs for a normalized separator, measuring how securely it separates them.
With bounded input norms, a larger positive margin gives a smaller perceptron mistake bound.
Maximum likelihood estimation
Maximum likelihood estimation chooses parameter values that maximize the probability assigned to the observed training data under a model.
For a categorical feature, relative class-specific counts supply its unsmoothed maximum likelihood estimates.
Mini-batch
A mini-batch is a small group of training examples whose gradients are averaged for one update, balancing computational efficiency and gradient noise.
A batch of 64 images supplies one averaged network update rather than 64 separate stochastic updates.
Model bias
Bias is systematic prediction error associated with restrictive modeling assumptions that prevent the learner from representing the underlying pattern.
A model family limited to straight trends can have high bias when the true relationship is strongly curved.
Model capacity
Model capacity is the flexibility of a hypothesis family, determining which patterns it can fit through its features, structure, or parameters.
A degree-9 polynomial has more capacity than a line and can interpolate ten distinct training inputs.
Momentum
Momentum combines recent gradient directions into a running update tendency, accelerating consistent progress and reducing side-to-side oscillations.
Successive gradients along a narrow valley can reinforce forward motion while sideways changes partly cancel.
Multiclass perceptron
A multiclass perceptron keeps a score vector per class and corrects a mistake by raising the true class score and lowering the predicted class score.
Only the true class vector and the mistaken winning vector change during one multiclass correction.
Multinomial naive Bayes
Multinomial naive Bayes models word occurrences as class-specific draws, making each repeated token contribute another likelihood factor.
A word occurring four times contributes four times its class log probability to the document score.

N

Naive Bayes
Naive Bayes is a probabilistic classifier that combines class priors with feature likelihoods under conditional independence given the class.
A spam score multiplies the spam prior by the likelihood of each observed binary feature value.
Numerical gradient check
A numerical gradient check compares an analytic derivative with a small finite-difference estimate of how loss changes when one parameter is perturbed.
Two nearby forward evaluations can check one weight derivative without using the backpropagation calculation.

O

One-hot encoding
One-hot encoding represents a category with separate binary indicators, with exactly one active indicator marking the category for each case.
Three unordered machine modes become three indicator positions without assigning the modes numerical ranks.
Overfitting
Overfitting occurs when learning captures sample-specific noise or accidents so closely that performance on new examples suffers.
A network with nearly perfect training accuracy but much lower validation accuracy shows a typical overfitting pattern.

P

Partial derivative
A partial derivative measures a function’s local rate of change with respect to one variable while its other variables are held fixed.
A weight derivative asks how loss changes if that weight moves without simultaneously moving the other weights.
Perceptron
A perceptron is a hard-decision linear unit whose mistake-driven learning rule adds the signed input vector to its weights after a wrong prediction.
A misclassified negative example causes the binary perceptron to subtract the augmented input from its weights.
Posterior probability
A posterior probability is a class probability after the input’s evidence has been incorporated, obtained by normalizing the class scores.
Scores of 0.18 and 0.018 become a spam posterior of about 0.909 after division by their sum.
Pseudo-count
A pseudo-count is an added count used to express prior support for an outcome, contributing to both its numerator and the total count.
Adding one pseudo-count to each of four feature values increases the denominator by four.

R

Regression
Regression predicts a numerical quantity from an input, with prediction error measured by the difference from the target value.
A model that estimates tomorrow’s temperature in °C performs regression, even if it reports whole degrees.
Regularization
Regularization changes learning to favor models that perform better on new data, often by restricting complexity or sensitivity to training details.
Weight penalties, early stopping, smoothing, and suitable data augmentation all control overfitting in different ways.
ReLU
A rectified linear unit, or ReLU, outputs zero for a negative input and otherwise outputs the input itself, creating a simple nonlinear bend.
A ReLU receiving −2 outputs zero, while the same unit receiving 3 outputs 3.

S

Sigmoid
The sigmoid is the increasing function that maps a real score to a value strictly between zero and one, making a binary probability output.
A score of 2 gives probability about 0.881, while a score of −2 gives its complement, about 0.119.
Smoothing strength
Smoothing strength is the hyperparameter setting how much pseudo-count evidence is added, balancing observed frequencies against stability.
Large smoothing strengths flatten class-specific estimates toward uniform feature probabilities.
Softmax
Softmax converts a vector of class scores into positive probabilities summing to one by normalizing the exponential of each score.
Adding a common constant to every score preserves probabilities because the shared exponential factor cancels.
Standardization
Standardization rescales a feature by subtracting its training mean and dividing by its training standard deviation to put features on comparable scales.
Area and room-count features can be standardized so one numerical scale does not stretch the loss surface as much.
Stochastic gradient descent
Stochastic gradient descent updates parameters using one randomly selected example’s loss gradient, a noisy estimate of the full training gradient.
One stochastic step can raise total loss even when the long-run optimization trend is downward.
Supervised learning
Supervised learning fits a prediction rule from examples that pair inputs with known outputs, so the rule can predict outputs for new cases.
A supervised email filter learns from messages that people have already labeled as spam or wanted email.
Symmetry problem
The symmetry problem occurs when identical network units receive identical updates and remain copies, preventing them from learning distinct representations.
Starting every connection at zero provides no random difference to distinguish units within a hidden layer.

T

Test set
A test set is a held-out collection used to assess a selected model after training and model choices, without using its results to tune that model.
A final accuracy report uses test emails that did not help fit weights or select the smoothing strength.
Token
A token is one occurrence of a represented word in text; repeated appearances count separately when estimating multinomial word probabilities.
The document "goal goal vote" has three word tokens but only two distinct words.
Training curve
A training curve plots a performance quantity across learning steps or epochs, revealing progress, instability, or a growing held-out gap.
Falling training loss with rising validation loss helps identify the point at which more fitting harms generalization.

U

Underfitting
Underfitting occurs when the model is too restricted to represent the useful pattern, leading to poor training and held-out performance.
A straight-line model can underfit a curved relationship that a suitable richer model captures on both splits.
Universal approximation
Universal approximation is the ability of a sufficiently wide suitable nonlinear network to approximate continuous functions on a closed, bounded region.
The theorem establishes representational possibility without promising how many units or which training run will succeed.

V

Vanishing gradients
Vanishing gradients are backward derivative signals that shrink through repeated transformations, leaving earlier parameters with very small learning updates.
A chain of sigmoid derivatives can weaken the loss signal even though each individual unit is differentiable.
Variance
Variance describes how much the fitted hypothesis changes across different training samples of the same size from the same distribution.
A flexible fit that swings widely when a few sampled points change exhibits high variance.
Vocabulary
A vocabulary is the set of distinct words represented by a text model, fixing which word probabilities can be estimated during training.
A word outside the fixed vocabulary is skipped unless a trained unknown-word token represents it.

Z

Zero-count problem
The zero-count problem occurs when an unobserved feature value receives estimated probability zero and eliminates a class’s entire likelihood product.
A word absent from all training ham messages can wrongly make a new ham message seem impossible.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started