Neural Networks Fundamentals

Learn how a neural network turns inputs into predictions. Compute what a single neuron does, see why activation functions must be nonlinear, and follow forward propagation through a small network by hand and with matrices. Turn raw scores into class probabilities with softmax, score them with cross-entropy, and understand how backpropagation and gradient descent improve the weights. Then build, train and evaluate a small classifier in Keras (TensorFlow) or PyTorch, and judge when a neural network is worth using instead of a simpler model.

IntermediateLesson 7 of 9 in Machine Learning Course

What you will learn

  1. Describe what a single artificial neuron computes, why activation functions must be nonlinear, and how neurons are arranged in layers to build a network with a known number of parameters.
    • Compute the output of a single artificial neuron
      Calculate a neuron's weighted sum, bias and activation, and connect a single sigmoid neuron with logistic regression.
    • Choose and apply activation functions
      Compute sigmoid, tanh, ReLU and linear activations, explain why hidden layers need nonlinear activations, and pick suitable activations for hidden and output layers.
    • Organize neurons into layers and count parameters
      Describe input, hidden and output layers in a fully connected network, explain what hidden units can learn, and count a network's weights and biases.
  2. Pass inputs through a network layer by layer to obtain its prediction, first by hand for one example and then with matrices for a whole batch.
    • Carry out forward propagation by hand
      Compute every pre-activation and activation of a small network for one input, and turn the output into a prediction.
    • Vectorize forward propagation for a batch of examples
      Write a dense layer as a matrix product plus a bias, track the shapes through a network, and compute a batch of predictions at once.
  3. Choose an output layer that matches the task, convert raw scores into class probabilities with softmax, and measure the quality of predictions with cross-entropy loss.
    • Match the output layer to the prediction task
      Set up the output units, activation and label format for binary, multiclass, multilabel and regression tasks.
    • Turn scores into class probabilities with softmax
      Calculate softmax probabilities, use their properties, and compute them in a numerically stable way.
    • Measure prediction quality with cross-entropy loss
      Compute cross-entropy for multiclass and binary predictions, interpret its values, and use the framework loss functions correctly.
  4. Describe training as repeated gradient descent steps that lower the cost, and explain with the chain rule how backpropagation finds the gradient of every weight.
    • Describe training as minimizing a cost with gradient descent
      Follow one gradient descent update by hand and explain batches, epochs, the learning rate and random initialization.
    • Explain backpropagation through the chain rule
      Trace how the error at the output is passed backward to give the gradient of every weight, and recognize why gradients can vanish.
  5. Prepare a dataset, define a small network, train it while watching its learning curves, and evaluate and use it, with Keras in TensorFlow or with PyTorch.
    • Prepare the data and define the model in code
      Split and scale a small dataset correctly and define the same network in Keras and in PyTorch.
    • Train the network and monitor its progress
      Write the training step in Keras and in PyTorch, follow the losses during training, and read learning curves.
    • Evaluate the model and make predictions
      Measure test performance correctly, turn outputs into probabilities and class names, and compare the network with a simple baseline.
  6. Weigh what neural networks do well against their costs, and choose between a network and a simpler model for a concrete problem.
    • Weigh the strengths and costs of neural networks
      Identify the kinds of data and problems where neural networks excel, and the costs and risks that come with them.
    • Choose a model for a concrete problem
      Apply a step-by-step decision to realistic scenarios and compare a network with simpler models fairly.

Neural Networks study guide

6 chapters

1

Explain how neurons, activations and layers form a network

Networks build complex predictions from small repeated calculations. Start by computing one neuron, then see how activation functions change its response and how layers combine neurons into learned features. Counting weights and biases makes the size of an architecture concrete. These ideas also separate what a model can represent from whether training will find useful parameters and predict well on new examples.

1.1 Compute the output of a single artificial neuron

A neuron combines numbers into one output. The same small calculation appears thousands of times in a larger network, so keeping its stages separate makes the whole model easier to follow.

From inputs to one activation

For inputs x1,…,xn, the neuron computes

z=∑i=1nwixi+b,a=g(z).

Each input has its own weight. The bias is added once to the total. The number z is the pre-activation; the number a, after applying the activation function, is the output. Vector notation shortens the first calculation to z=𝐰⋅𝐱+b. A dot product means multiplying matching entries and adding their products.

A positive weight makes an increase in its input raise z, with the other inputs fixed. A negative weight makes it lower z. A zero weight removes that input's direct contribution to this neuron. These statements concern the weighted sum: the activation function then determines how a change in that sum changes the output. The bias shifts the sum even when all input values are zero.

Weights and biases are parameters. Training adjusts them; predicting with an already trained neuron uses their current values. The input values belong to the example being processed, so they change from one example to another without being learned parameters.

Work through the arithmetic

Take 𝐱=(2,1,4), 𝐰=(0.5,−1,0.25) and b=−0.5. Match each weight to its input:

0.5(2)=1,(−1)(1)=−1,0.25(4)=1.

The products add to 1−1+1=1. Adding the bias gives z=1−0.5=0.5. Only now apply the activation. With the sigmoid,

a=σ(0.5)=11+e−0.5≈0.622.

With ReLU, the same sum gives a=max⁡(0,0.5)=0.5. The parameters and inputs are identical in both calculations; changing the activation changes the output rule. Applying sigmoid to each input first would describe a different computation. Leaving out the bias would give z=1 instead of 0.5.

Connect the neuron to logistic regression

A single sigmoid neuron computes P(y=1∣𝐱)=σ(𝐰⋅𝐱+b), exactly the form of logistic regression. Its output is a probability estimate. A separate threshold converts it to a class: at threshold 0.5, outputs at or above 0.5 predict class 1.

Sigmoid reaches 0.5 when z=0. The decision boundary is therefore 𝐰⋅𝐱+b=0. With two features this is a straight line; with more features it is a hyperplane. Although sigmoid is curved, this single neuron's threshold boundary is linear.

That boundary cannot separate XOR: (0,0) and (1,1) have label 0, while (0,1) and (1,0) have label 1. No one straight line separates the two pairs. Hidden units provide intermediate features that let a network build a more flexible boundary. The name "neuron" reflects a loose biological inspiration; the unit itself is a mathematical function.

Key Takeaways

  • Compute the weighted sum and bias before applying the activation.
  • Weights and biases are learned parameters; inputs describe the current example.
  • A sigmoid neuron has the same form as logistic regression.
  • One sigmoid neuron has a linear threshold boundary and cannot separate XOR.

1.2 Choose and apply activation functions

An activation function determines how a layer responds to its weighted sums. Hidden activations give the network flexibility; output activations give predictions the right meaning for the target.

Compare the main functions
FunctionRule or rangeUseful role
Sigmoidσ(z)=1/(1+e−z), between 0 and 1Binary probability
TanhBetween −1 and 1, with tanh⁡(0)=0Zero-centered hidden activations
ReLUmax⁡(0,z)Default starting point for hidden layers
Leaky ReLUSmall negative slope, positive slope 1Allows a signal for negative sums
Linearg(z)=zReal-valued regression output

Sigmoid gives σ(0)=0.5, σ(2)≈0.881 and σ(−2)≈0.119. Tanh is related by tanh⁡(z)=2σ(2z)−1. For z=0.5, this gives about 0.462. Both functions change smoothly, but their outputs flatten near the ends of their ranges.

ReLU clips negative values to zero and leaves positive values unchanged. Thus ReLU(−3)=0 and ReLU(2.5)=2.5. With negative slope 0.01, leaky ReLU instead gives −0.03 for input −3. A linear activation leaves both signs unchanged. For predicting temperature in degrees Celsius, a linear output allows both negative and positive predictions.

Why straight layers need a bend

Suppose one layer gives h=2x+1 and a second gives y=3h−4. Substitution produces y=6x−1. The two stages reduce to one affine function: a linear transformation plus a bias. Adding more such stages changes coefficients but adds no curved boundary.

The matrix calculation has the same form:

W2(W1𝐱+𝐛1)+𝐛2=(W2W1)𝐱+W2𝐛1+𝐛2.

A final sigmoid would turn this into logistic regression on the original inputs. Hidden nonlinear activations break that collapse. ReLU qualifies even though each side of zero is straight: its slope changes at zero. Different units place bends in different parts of the input space, and later layers combine them.

Match the function to its job

Start hidden layers with ReLU. For outputs, ask what must be predicted. Use one sigmoid for a binary label, softmax across the scores for one class out of several, and one sigmoid per label when several labels may be true together. Use a linear output for an unrestricted real target. A ReLU output can enforce a nonnegative prediction; a linear output alone does not enforce that restriction.

Sigmoid's derivative is σ(z)(1−σ(z)), at most 0.25. At z=4 its output is already about 0.982, with a small slope. During learning, multiplying many small slopes can leave early layers with tiny gradients. Tanh also saturates. ReLU has slope 1 on its positive side, which helps signals pass backward there; on its negative side its slope is zero. The choice therefore affects both what a network can represent and how it learns.

Key Takeaways

  • Hidden nonlinear activations let stacked layers represent more than one affine transformation.
  • ReLU is nonlinear because its slope changes at zero.
  • Choose the output activation to match the target.
  • Sigmoid and tanh can saturate and pass back small gradients.
  • Leaky ReLU keeps a small slope for negative pre-activations.

1.3 Organize neurons into layers and count parameters

A feedforward network passes feature values through hidden layers to an output. In a dense layer, every unit receives every output from the previous layer, with a separate weight for each connection.

Read an architecture

The input layer holds the features and has no weights or biases. Hidden layers compute intermediate activations. The output layer produces scores or predictions. This fully connected arrangement is also called a multilayer perceptron, or MLP.

A layer's number of units is its width. Depth describes how many layers the network has. Here, layer counts include only layers with parameters: one hidden layer plus one output layer is a two-layer network. The input is layer 0. An activation written as a separate software module does not add a parameter-bearing layer.

Parameters are the weights and biases learned during training. Hyperparameters are choices made when building or training the model, such as hidden width, activation function, learning rate and number of epochs.

Count every weight and bias

For a layer with nin inputs and nout units,

N=ninnout+nout=(nin+1)nout.

Each unit needs one weight per input and one bias. A 4–8–3 network has 4(8)=32 hidden weights and 8 hidden biases, totaling 40. Its output layer has 8(3)=24 weights and 3 biases, totaling 27. The full count is 40+27=67.

For 784 inputs, 128 hidden units and 10 outputs, the first layer has 784(128)+128=100,480 parameters. The second has 128(10)+10=1,290, giving 101,770 overall. Count connections into each layer once. Adding parameters for the input layer or forgetting biases changes the total incorrectly.

Hidden units build useful features

A hidden unit combines the original measurements; the next layer combines those learned combinations. With price, shipping cost, marketing spend and quality as inputs, some hidden responses might track affordability or perceived quality. Training uses labels to choose useful combinations. A human-readable name for every hidden unit is neither supplied nor guaranteed.

XOR shows why intermediate features help. Define

h1=ReLU(x1+x2),h2=ReLU(x1+x2−1),o=h1−2h2.

At (0,0), both hidden outputs are zero, so o=0. At (1,0) and (0,1), they are 1 and 0, so o=1. At (1,1), they are 2 and 1, so o=2−2=0. These nonlinear features make a pattern possible that a single straight boundary cannot capture.

Separate capacity from successful learning

The universal approximation theorem says that a sufficiently wide hidden layer with a suitable nonlinear activation can approximate continuous functions on compact input regions to any desired accuracy. It is an existence result. It gives neither a training procedure nor a guarantee of accurate predictions on new examples.

Deeper networks can represent some complicated functions with fewer units than a single very wide layer. Still, more capacity brings more parameters to estimate and can increase overfitting. Choose size using validation results, alongside the amount of data and the computing cost.

Key Takeaways

  • A dense layer with n inputs and m units has nm weights and m biases.
  • The input layer has no parameters.
  • State whether a layer count includes the input layer.
  • Hidden units learn intermediate features from data.
  • The universal approximation theorem guarantees representational capacity, not training success or generalization.
  • Architecture choices are hyperparameters; weights and biases are parameters.
2

Compute predictions with forward propagation

A prediction travels forward through the network using fixed weights and biases. Following that route by hand shows exactly which values each layer receives. The same arithmetic can then be organized as matrix products for a batch. Keeping track of shapes, bias broadcasting and activation placement helps connect the numerical example to what Keras and PyTorch compute, including their different weight-storage conventions.

2.1 Carry out forward propagation by hand

Forward propagation computes a prediction using the current parameters. Each layer receives the previous layer's activations, forms weighted sums, adds biases and applies its activation. The same process used for prediction is called inference.

Fix the network before calculating

Use two inputs and two ReLU hidden units. Hidden unit 1 has weights (0.5,−0.25) and bias 0.5. Hidden unit 2 has weights (−1,0.5) and bias −0.5. The sigmoid output has weights (1.5,1) and bias 0.25.

For each example, keep a record of both the pre-activation and activation. They are different quantities even when ReLU happens to leave a positive value unchanged. Parameters stay fixed throughout this pass; changing them belongs to a training update.

Calculate the hidden layer

For input (1,2), hidden unit 1 gives

z1=0.5(1)−0.25(2)+0.5=0.5−0.5+0.5=0.5.

Its activation is h1=max⁡(0,0.5)=0.5. Hidden unit 2 gives

z2=−1(1)+0.5(2)−0.5=−1+1−0.5=−0.5.

Its activation is h2=0. Pass (0.5,0) to the output layer. Passing (0.5,−0.5) would skip ReLU and produce a different network result.

Calculate and interpret the output

The output pre-activation is

z=1.5(0.5)+1(0)+0.25=0.75+0+0.25=1.

The sigmoid produces a=σ(1)≈0.731. This is the estimated probability of class 1. At the threshold 0.5, the predicted class is 1. The raw score 1, the probability 0.731 and the class label 1 have different roles, even though two happen to share a numeral.

The threshold is a decision rule applied after the probability is computed. As with logistic regression, a problem with unequal costs for the two error types can use another threshold. Changing it changes class decisions without changing the forward pass or its probabilities.

Follow a second route through the same units

For input (0,4), the first hidden sum is 0−1+0.5=−0.5, giving h1=0. The second is 0+2−0.5=1.5, giving h2=1.5. Now the output sum is 1.5(0)+1(1.5)+0.25=1.75, so a=σ(1.75)≈0.852.

Different inputs activate different ReLU units. Inside one region of input space, one set of units passes signals; in another region, a different set does. This switching lets the hidden layer build a nonlinear decision boundary.

Keep unrounded sigmoid values for later calculations and round reported results at the end.

Key Takeaways

  • A forward pass computes outputs without updating parameters.
  • Each layer receives the previous layer’s activations.
  • A negative ReLU pre-activation becomes zero before the next layer.
  • Convert output probabilities to labels with the task’s decision rule.

2.2 Vectorize forward propagation for a batch of examples

A batch groups several examples into one matrix. Vectorization calculates all their weighted sums with matrix products, using the same parameters for every row. It changes how efficiently the calculation runs, not what each example predicts.

Track the shapes first

Store one example per row and one feature per column. If X has shape (m,n) and the layer has u units, its Keras-style weight matrix has shape (n,u). Then

Z=XW+𝐛,A=g(Z)

both have shape (m,u). The bias has u entries and is added to every row by broadcasting. ReLU, sigmoid and tanh act separately on each entry.

For 32 flowers with four measurements and layers of 16 and 3 units, the activation shapes are (32,4)→(32,16)→(32,3). The final matrix holds three class scores for each of 32 examples. Batch size changes the number of rows; it does not change the number of model parameters.

Compute a two-row batch

For the two-input network, use

X=(1230),W1=(0.5−1−0.250.5),𝐛1=(0.5,−0.5).

Each column of W1 contains one hidden unit's weights. Multiplication gives

XW1=(001.5−3).

Add the bias to both rows, then clip the negative entries:

Z1=(0.5−0.52−3.5),A1=(0.5020).

With output weights W2=(1.5,1)⊤ and bias 0.25, the output sums are 1 and 3.25. Sigmoid gives about 0.731 and 0.963. Each row agrees with running that example alone through the network.

Read framework storage correctly
LayerStored weight shapeOperation
Keras Denseinputs × unitsXW+𝐛
PyTorch Linearunits × inputsXW⊤+𝐛

PyTorch stores the transpose of the Keras-style matrix. Its Linear module applies the required transpose internally. For nn.Linear(4, 16), stored weights have shape (16, 4), but a batch still goes from (m, 4) to (m, 16).

Matrix multiplication requires the inner dimensions to agree. A hidden layer producing 16 values must feed a layer expecting 16 inputs. Do not transpose a framework layer's weights during ordinary use: the module already knows its storage convention.

For portable prediction code, keep a batch dimension even for one example, such as (1, 4). PyTorch Linear also accepts an unbatched vector, but a consistent two-dimensional layout makes the class axis and later metric code clear. Softmax differs from the element-wise activations: it uses an entire row of class scores together. For a matrix shaped (examples, classes), normalize along the class axis, so every example gets its own probability distribution.

Key Takeaways

  • Use one row per example and one column per feature.
  • Keras Dense and PyTorch Linear store transposed versions of the same weights.
  • Broadcast one bias per unit across all batch rows.
  • Matrix multiplication requires matching inner dimensions.
  • Apply softmax across classes within each example.
3

Produce and score multiclass predictions

A classifier’s final scores need a meaning that matches its labels. A binary decision, one class out of several, and several simultaneous tags require different output rules. Softmax converts competing scores into probabilities, while cross-entropy measures the probability assigned to the true class. Keeping scores, probabilities, decisions and losses separate prevents both interpretation errors and framework configuration mistakes.

3.1 Match the output layer to the prediction task

The output layer must represent the kind of answer the task allows. Decide whether labels compete, whether several labels can be true, or whether the target is a number before choosing units and a loss.

Match outputs to targets
TaskOutputTypical loss
Binary classificationOne sigmoid probabilityBinary cross-entropy
One of K classesK logits, interpreted with softmaxMulticlass cross-entropy
Several possible labelsOne sigmoid probability per labelBinary cross-entropy per label
RegressionOne linear output per numeric targetSquared error

A binary sigmoid output estimates the probability of class 1; class 0 has the remaining probability. A multiclass output describes mutually exclusive alternatives, such as one flower species. Its softmax probabilities sum to 1, and argmax selects the class with the largest value.

For multilabel classification, one image can contain a person, a car and a bicycle. Each label is a separate yes/no target. Logits (2,0.5,−1) become sigmoid probabilities of about 0.881, 0.622 and 0.269. At threshold 0.5, the predicted tags are person and car. Their probabilities total about 1.77; a total above 1 is valid because the labels are not competing alternatives. Using softmax would force them to compete.

For regression, the output can be any real number. A target such as temperature in degrees Celsius calls for a linear output, which leaves the final weighted sum unchanged. The hidden layers can stay the same while the output and loss change to serve a different task.

Keep raw scores distinct from probabilities

A logit is a raw output score before sigmoid or softmax. It can be negative or greater than 1. A dense output with no activation returns logits. During training, a loss can apply the probability transformation internally, improving numerical stability. During prediction, apply sigmoid or softmax when probabilities are needed.

A model without hidden layers and with softmax probabilities is softmax regression, the multiclass form of logistic regression. Adding hidden layers changes the features from which the logits are computed; it does not change the meaning of the classes.

Match label encoding to the loss

With three classes indexed 0, 1 and 2, a label can be the integer 2 or the one-hot vector (0,0,1). The 1 occupies the true class's position; class indexing starts at zero.

In Keras, use SparseCategoricalCrossentropy for integer labels and CategoricalCrossentropy for one-hot labels. If the model returns logits, set from_logits=True. In the PyTorch class-index workflow, nn.CrossEntropyLoss() receives logits and labels of type torch.long. The score tensor has one column per class; the label tensor has one integer per example.

Check the target's meaning before its array shape. A three-column label array might describe one-hot mutually exclusive classes or three independent binary tags. The columns alone cannot choose the task. Read whether exactly one label or several labels can be true, then choose the output transformation and compatible loss.

Key Takeaways

  • Choose outputs from the target’s meaning, including whether labels compete.
  • Multiclass probabilities sum to 1; multilabel sigmoid probabilities need not.
  • Logits are unrestricted raw scores, not probabilities.
  • Match integer or one-hot labels to the chosen loss.
  • Regression uses numeric outputs with a regression loss.

3.2 Turn scores into class probabilities with softmax

Softmax turns a row of class scores into positive probabilities that sum to 1. Every probability depends on all the scores in that row, so raising one score changes the distribution over the competing classes.

Exponentiate, add and divide

For K logits, the probability of class k is

pk=ezk∑j=1Kezj.

Exponentials make each contribution positive. Dividing by their shared total makes the probabilities sum to 1. Dividing the raw logits by their sum is a different operation that can produce negative values or divide by zero.

For logits (2,1,0.1), the exponentials are about 7.389, 2.718 and 1.105. Their unrounded total is about 11.213. Dividing gives probabilities of about 0.659, 0.242 and 0.099. The first class wins. Carry full precision inside the calculation; rounded printed probabilities may total slightly above or below 1.

The exponential preserves order, and all classes share the same positive denominator. The largest logit therefore has the largest probability. If only a class index is needed, argmax on the logits gives the same winner as argmax after softmax.

Shift scores without changing probabilities

Adding a constant c to every score multiplies every exponential by ec. That factor cancels from numerator and denominator, leaving the probabilities unchanged. Thus (7,6,5.1) gives the same distribution as (2,1,0.1).

Multiplying logits is different because it changes their gaps. Doubling the example to (4,2,0.2) gives about 0.864, 0.117 and 0.019. The winning class stays first, but its probability rises. A positive scaling preserves order while changing confidence.

Prevent overflow

Direct exponentiation of large positive scores can exceed the computer's numeric range. Approximate overflow boundaries are 709.8 for float64 and 88.7 for float32. Use shift invariance to subtract the largest score before exponentiating:

pk=ezk−zmax∑jezj−zmax.

Logits (1000,999) become (0,−1). The exponentials are 1 and about 0.368, giving probabilities about 0.731 and 0.269. This avoids enormous exponentials while preserving the intended distribution. Framework softmax and fused cross-entropy functions handle the stable calculation.

Normalize within each example

For logits with shape (examples, classes), use torch.softmax(logits, dim=1). Applying softmax down the batch would make different examples compete for probability, which has no meaning for independent classifications.

With two logits (z,0), the first softmax probability is ez/(ez+1)=σ(z). This links multiclass classification to a binary sigmoid. In either case, probabilities are model estimates: a reported 0.9 needs calibration evidence before being read as 90% observed accuracy among such predictions.

Key Takeaways

  • Softmax exponentiates logits and normalizes them within an example.
  • Argmax is unchanged by softmax.
  • A common shift leaves softmax unchanged; scaling changes confidence.
  • Subtract the largest logit for stable exponentiation.
  • High predicted confidence and well-calibrated probabilities are different properties.

3.3 Measure prediction quality with cross-entropy loss

Accuracy records whether the winning class is right. Cross-entropy also measures the probability assigned to the true class, giving training a smoother and more informative signal than a correct/incorrect count.

Score the true class

For true class y and its predicted probability py,

L=−ln⁡py.

Here ln⁡ is the natural logarithm. A one-hot target gives the equivalent form L=−∑kykln⁡pk: only the true class has a nonzero label entry.

For probabilities near (0.659,0.242,0.099), the loss is approximately 0.417 if the first class is true, 1.417 if the second is true, and 2.317 if the third is true. The same prediction earns different losses for different labels. Use the true class's probability, even when another class is the argmax.

The loss approaches zero as the true-class probability approaches 1. It grows without bound as that probability approaches zero. This strongly penalizes confident wrong predictions. A loss of exactly zero corresponds to probability 1 on the true class.

For a binary sigmoid probability p=P(y=1),

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

At p≈0.731, label 1 gives about 0.313; label 0 gives about 1.313. For label 0, the true-class probability is 1−p, not p.

Average losses and interpret progress

The cost J is the mean loss over examples or a batch. Minimizing mean cross-entropy maximizes the likelihood of the observed labels. Cross-entropy is the standard classification loss; squared error serves numeric regression targets.

Uniform probabilities give L=ln⁡K for K classes, about 1.099 for three and 2.303 for ten. Nearly equal initial logits therefore give a useful starting-loss check. This is a check of the scores, not a claim that balanced labels force any particular initial loss.

A later loss near ln⁡K needs accuracy alongside it. A correct class with probability 0.34 against 0.33 and 0.33 gives a correct argmax but loss about 1.079. Conversely, accuracy may stay fixed as loss falls because the model raises its probabilities on already correct predictions. Loss and accuracy capture different information.

Give framework losses the right representation
Framework pathPredictions suppliedTargets supplied
Keras sparse categorical, from_logits=TrueRaw logitsInteger class labels
Keras categorical, from_logits=TrueRaw logitsOne-hot labels
PyTorch CrossEntropyLoss, class-index pathRaw logitstorch.long class indices

The fused loss computes the probability/logarithm combination stably. Adding softmax before PyTorch cross-entropy makes it treat probabilities as if they were logits, compressing their differences again. In Keras, a mismatch between the last activation and from_logits also changes the intended calculation. Verify the model output, label encoding and loss settings together before diagnosing learning from a curve.

Key Takeaways

  • Cross-entropy uses the probability of the true class.
  • For a binary label of zero, score 1 − p.
  • Mean loss is the cost minimized during training.
  • Uniform predictions give ln K; read loss alongside accuracy.
  • Use raw logits with fused losses configured for logits.
4

Explain how a network learns from data

Learning changes the parameters used by the forward calculation. A loss measures prediction quality, backpropagation finds derivatives, and an optimizer applies updates. Work through a numerical update and follow an error signal into a hidden layer to see these jobs separately. Batches, epochs, initialization and the learning rate then explain how those operations become a repeatable training process.

4.1 Describe training as minimizing a cost with gradient descent

Training chooses parameters that reduce average prediction loss. A model defines the forward calculation, a loss scores its predictions, and an optimizer repeatedly changes the weights and biases using gradients.

Step against the gradient

A gradient measures how cost changes when a parameter increases slightly. Gradient descent updates every parameter using

w←w−α∂J∂w.

The learning rate α sets the step size. A positive gradient makes the parameter decrease; a negative gradient makes it increase. Calculate all gradients at the current parameters, then update them together. A sufficiently small local step follows a downhill direction, but an excessive step can overshoot and raise the loss.

For sigmoid with binary cross-entropy, the loss derivative with respect to the output sum is a−y. For softmax cross-entropy, the corresponding vector is the probabilities minus the one-hot label. A weight feeding directly into that output gets the error multiplied by its input.

Follow one complete update

Take inputs (1,2), weights (0.3,−0.1), bias 0.1 and label 1. The output sum is z=0.3−0.2+0.1=0.2. Sigmoid gives a≈0.550 and loss L≈0.598.

The output error is a−y≈−0.450. Multiplying by inputs gives weight gradients about −0.450 and −0.900. The bias gradient is about −0.450, because the bias enters the sum with coefficient 1.

At learning rate 0.5, subtracting these negative gradients gives weights about 0.525 and 0.350 and bias 0.325. Recomputing with unrounded values gives z≈1.550, a≈0.825 and loss about 0.192. This update moves the probability toward the true label. The sign comes from subtracting the gradient, not from a rule that weights always rise during learning.

Count updates and passes

A mini-batch supplies the examples for one update, or step. An epoch is a pass through the training set. With 60,000 examples and batch size 32, an epoch has 1,875 updates. With 12,000 examples and batch size 64, it has 188 updates: 187 full batches and a final batch of 32. A smaller final batch still receives an update.

A very small learning rate makes progress slow. A very large one can produce oscillating losses, growth or nan. Hidden-layer network costs are generally nonconvex, so different starts can reach different solutions. Use validation results to assess their usefulness.

Let units learn different features

If hidden units have identical incoming weights, biases and outgoing weights, they compute the same values and receive the same updates. All-zero initialization creates this symmetry. Random initial weights break it; biases can still start at zero. Keras and PyTorch initialize layer weights when layers are created.

An optimizer applies the update rule. Adam is a common ready-made choice that adapts parameter step sizes during training. It uses gradients produced by backpropagation; the optimizer and the gradient calculation have separate jobs.

Key Takeaways

  • Gradient descent subtracts the gradient times the learning rate.
  • Compute gradients at the current parameters before updating.
  • One mini-batch gives one step; one pass through the data is an epoch.
  • Random weights break symmetry between hidden units.
  • The learning rate controls step size and can make training slow or unstable.
  • An optimizer applies updates using the computed gradients.

4.2 Explain backpropagation through the chain rule

A hidden weight affects the loss through later computations. Backpropagation follows those connections backward to calculate derivatives efficiently, using intermediate values saved by the forward pass.

Multiply local derivatives

For a weight feeding a unit's pre-activation z and activation a, the chain rule gives

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

The last factor is the input multiplied by the weight. The activation supplies its local slope. The first factor tells how the later network and loss respond to this unit's activation. Where a value feeds several later computations, their gradient contributions are added.

A computation graph records these dependencies. The forward pass evaluates its operations. The backward pass combines local derivatives in reverse order. Backpropagation computes gradients; an optimizer then uses them to change parameters.

Trace the two-hidden-unit network backward

For input (1,2) and label 1, the earlier forward calculation gave hidden activations h1=0.5 and h2=0, output sum 1 and sigmoid output about 0.731. With binary cross-entropy, the output-sum derivative is a−y≈−0.269.

The output weight from hidden unit 1 has gradient −0.269(0.5)≈−0.134. The weight from hidden unit 2 has gradient zero because its input is zero. The output bias gradient is −0.269.

To move into hidden unit 1, multiply the arriving error by its outgoing weight 1.5: ∂L/∂h1≈−0.403. Its positive pre-activation gives ReLU slope 1, so the gradient entering its sum stays about −0.403. Multiplying by original inputs 1 and 2 gives incoming weight gradients about −0.403 and −0.807. Its bias gradient is about −0.403.

Hidden unit 2 had pre-activation −0.5. ReLU's slope is zero there, so its incoming weights and bias have zero gradients for this example. An inactive unit for one example may still learn from others. A unit inactive for every training example is a dead ReLU.

Understand weak or large gradients

Backpropagation repeatedly multiplies factors. Sigmoid's slope is at most 0.25, so ten sigmoid activation derivatives multiply to at most 0.2510≈9.5×10−7. Weight factors also affect the full gradient. Very small gradients leave early layers learning slowly: the vanishing-gradient problem. ReLU passes slope 1 for positive inputs, which eases this source of shrinking. Large factors can instead produce exploding gradients.

Automatic differentiation handles these calculations in frameworks. PyTorch's loss.backward() stores parameter gradients in .grad; optimizer.step() applies the update. Gradients accumulate, so reset them before the next ordinary training step. Keras performs the backward pass inside fit.

One backward pass produces all parameter gradients at a cost comparable to a few forward passes. Perturbing every parameter separately would require many additional evaluations, making it impractical for networks with over 100,000 parameters.

Key Takeaways

  • Backpropagation applies the chain rule backward and computes gradients.
  • The optimizer, not backpropagation itself, updates parameters.
  • An inactive ReLU blocks its incoming gradients for that example.
  • Vanishing gradients can result from many small derivative factors.
  • Automatic differentiation reuses the recorded forward computation.
5

Train a small classifier with TensorFlow or PyTorch

A small flower classifier connects the mathematics to a complete Python workflow. Split and scale the data, define matching dense networks, and train with either Keras on TensorFlow or PyTorch. Monitor validation results before choosing the final training duration, then evaluate once on held-out test data. New predictions require the same feature order and fitted preprocessing as training, so preserve them with the model.

5.1 Prepare the data and define the model in code

A useful classifier begins with a clean data split. The Iris example has 150 flowers, 50 per species, with four measurements in centimeters. The model predicts setosa, versicolor or virginica from those measurements.

Split before fitting preprocessing

Use Python with NumPy, scikit-learn and either TensorFlow with Keras 3 or PyTorch 2 installed. The shared preparation is:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

iris = load_iris()
X, y = iris.data, iris.target
X_dev, X_test, y_dev, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=0
)
X_train, X_val, y_train, y_val = train_test_split(
    X_dev, y_dev, test_size=0.2, stratify=y_dev, random_state=0
)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train).astype("float32")
X_val = scaler.transform(X_val).astype("float32")
X_test = scaler.transform(X_test).astype("float32")

The first split reserves 30 test flowers and leaves 120 for development. The second reserves 24 validation flowers and leaves 96 for training. Stratification preserves the species proportions. Validation guides model choices; test data stays untouched until the final evaluation.

StandardScaler learns feature means and standard deviations from the training set. It subtracts each learned mean and divides by its learned standard deviation. Reuse those values for validation, test and new examples. Fitting on all 150 flowers would leak held-out information into preprocessing. Scaling also helps prevent large-magnitude features from dominating the optimization's numerical behavior.

Define the Keras model

For the TensorFlow path, select the backend before importing Keras:

import os
os.environ["KERAS_BACKEND"] = "tensorflow"
import keras

keras.utils.set_random_seed(0)
model = keras.Sequential([
    keras.Input(shape=(4,)),
    keras.layers.Dense(16, activation="relu"),
    keras.layers.Dense(3),
])
model.summary()

The last layer has no activation and produces three logits. The hidden layer has 4(16)+16=80 parameters; the output has 16(3)+3=51. The total is 131.

Or define the PyTorch model

Run this alternative in a separate session using the same prepared arrays:

import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(4, 16), nn.ReLU(), nn.Linear(16, 3))
X_t = torch.tensor(X_train, dtype=torch.float32)
y_t = torch.tensor(y_train, dtype=torch.long)
X_val_t = torch.tensor(X_val, dtype=torch.float32)
y_val_t = torch.tensor(y_val, dtype=torch.long)
X_test_t = torch.tensor(X_test, dtype=torch.float32)
y_test_t = torch.tensor(y_test, dtype=torch.long)
train_loader = DataLoader(TensorDataset(X_t, y_t), batch_size=16, shuffle=True)
print(sum(p.numel() for p in model.parameters()))

This also has 131 parameters. ReLU is a separate module, and labels use integer class indices with torch.long. Float32 features match the model weights; float64 inputs can cause a data-type error.

Iris rows are sorted by species. Keras validation_split=0.2 on the original sorted arrays would take the last 30 flowers before shuffling, all from one species. The explicit stratified split avoids that problem and gives both framework paths the same data.

Key Takeaways

  • Split training, validation and test data before fitting a scaler.
  • Fit preprocessing on training data and reuse it for all other data.
  • The 4–16–3 classifier has 131 learned parameters and produces logits.
  • PyTorch class-index labels use torch.long and features match the model’s float32 type.
  • An explicit stratified validation set avoids a sorted-array validation split.

5.2 Train the network and monitor its progress

Training alternates prediction, loss calculation, differentiation and an update. Keras wraps these operations in fit; PyTorch exposes the loop. Both paths should monitor held-out validation performance as well as training loss.

Train with Keras

Continue from the Keras model and prepared arrays:

model.compile(
    optimizer="adam",
    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=["accuracy"],
)
history = model.fit(
    X_train, y_train, epochs=100, batch_size=16,
    validation_data=(X_val, y_val),
)

Integer labels match the sparse loss; from_logits=True matches the last layer. Keras shuffles NumPy training rows by default. With 96 training flowers and batches of 16, there are six updates per epoch and 600 across 100 epochs. Validation measures progress without updating parameters. The default batch size would be 32 if none were supplied.

The returned history contains loss, accuracy, val_loss and val_accuracy. Plot them against epoch to inspect the course of learning:

import matplotlib.pyplot as plt
plt.plot(history.history["loss"], label="training")
plt.plot(history.history["val_loss"], label="validation")
plt.xlabel("Epoch")
plt.ylabel("Cross-entropy")
plt.legend()
plt.show()
Train with PyTorch

Continue from the alternative PyTorch setup:

loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
curves = []
for epoch in range(100):
    model.train()
    total = 0.0
    for xb, yb in train_loader:
        optimizer.zero_grad()
        logits = model(xb)
        loss = loss_fn(logits, yb)
        loss.backward()
        optimizer.step()
        total += loss.item() * len(yb)
    model.eval()
    with torch.no_grad():
        val_loss = loss_fn(model(X_val_t), y_val_t).item()
    curves.append((total / len(y_t), val_loss))

Reset gradients, compute logits and loss, backpropagate, then update. PyTorch adds gradients to stored gradients, so omitting the reset accumulates old contributions. Multiplying each batch mean by its size produces an example-weighted epoch mean. The training mean is collected while parameters change; validation uses the parameters at epoch end.

shuffle=True changes the training batch order each epoch. It reduces persistent grouping by class, although any one batch may still be uneven. The learning rates in the two examples are separate starting choices, not a controlled comparison of frameworks.

Read what the curves show

If both losses fall, the model is learning useful structure. If training loss falls while validation loss rises, the pattern signals overfitting. If both remain high, investigate underfitting, optimization settings and data preparation. Select the number of epochs from validation performance, then train a fresh model for that selected duration before the final test.

Nearly equal logits on three classes give an initial loss near ln⁡3≈1.099. A different value calls for inspecting logits, labels and loss configuration; random weights do not guarantee equal logits. For nan, inspect data for invalid values and check the learning rate. Seeds help repeat runs on the same setup, while several seeds give a fairer picture when comparing designs.

Key Takeaways

  • Use a logits-compatible classification loss.
  • Reset PyTorch gradients before each ordinary training step.
  • Track validation loss without gradient updates.
  • Falling training loss with rising validation loss signals overfitting.
  • Choose the training duration from validation performance.
  • Read loss, accuracy and data checks together when diagnosing training.

5.3 Evaluate the model and make predictions

Final evaluation asks how well the chosen model predicts examples that played no part in fitting or model selection. Freeze the architecture, preprocessing and training duration before examining test results.

Measure held-out performance

For the Keras path, evaluate the selected, trained model:

test_loss, test_accuracy = model.evaluate(X_test, y_test, verbose=0)
probability_model = keras.Sequential([model, keras.layers.Softmax()])
probabilities = probability_model.predict(X_test, verbose=0)
preds = probabilities.argmax(axis=1)

For the PyTorch path:

model.eval()
with torch.no_grad():
    logits = model(X_test_t)
    test_loss = loss_fn(logits, y_test_t).item()
    probabilities = torch.softmax(logits, dim=1)
    preds = logits.argmax(dim=1)
    test_accuracy = (preds == y_test_t).float().mean().item()

model.eval() changes the behavior of layers such as dropout. torch.no_grad() separately disables gradient tracking, saving work and memory. This simple model has no dropout, but keeping both calls makes the evaluation pattern correct when such layers are present.

If 28 of 30 test flowers are correct, accuracy is 28/30≈0.933. Each flower changes accuracy by about 3.3 percentage points, so small differences on this test set are coarse evidence. A confusion matrix identifies which species are confused. The overlapping versicolor and virginica measurements commonly make those classes harder to separate than setosa.

Prepare a new example exactly as before

A new flower needs the same measurement order, units and fitted transformation. For Keras:

new_X = scaler.transform([[5.1, 3.5, 1.4, 0.2]]).astype("float32")
new_p = probability_model.predict(new_X, verbose=0)
name = iris.target_names[new_p.argmax(axis=1)[0]]

The nested list gives one row with four features, shape (1, 4). For PyTorch, use the same new_X:

model.eval()
with torch.no_grad():
    new_logits = model(torch.tensor(new_X, dtype=torch.float32))
name = iris.target_names[new_logits.argmax(dim=1).item()]

Argmax gives an index; target_names maps it to a species. A large raw logit is not itself a probability.

Compare and preserve the whole predictor

A baseline such as logistic regression should use the same data split and metric. Train it on the prepared training arrays and check validation accuracy:

from sklearn.linear_model import LogisticRegression
baseline = LogisticRegression(max_iter=1000).fit(X_train, y_train)
baseline_val_accuracy = baseline.score(X_val, y_val)

Compare candidates on validation data, with comparable tuning effort, before selecting a model for final testing. Iris is small and clean; a network is useful practice here, while simpler classifiers can reach similar accuracy with less work.

Reporting training accuracy overstates evidence about new examples. Repeatedly choosing designs from test scores turns the test into a development set and makes the selected score optimistic.

Save the Keras model with model.save("iris.keras") and reload with keras.models.load_model("iris.keras"). In PyTorch, save model.state_dict() with torch.save; rebuild the same architecture and load that state with model.load_state_dict(torch.load("iris.pt", weights_only=True)). Preserve the fitted scaler, feature order and class-name mapping too. The weights alone cannot reproduce correct predictions if preprocessing changes.

Key Takeaways

  • Use the test set after development choices are fixed.
  • PyTorch evaluation mode and disabled gradient tracking serve different purposes.
  • Apply the training scaler and preserve feature order for new examples.
  • Map argmax indices to the correct class names.
  • Save preprocessing and label information along with the model.
6

Decide when a neural network is the right tool

Choosing a network is a practical modeling decision. Learned features can help with complex inputs and large datasets, while computing needs, tuning effort and explanation requirements can favor simpler methods. Use concrete scenarios to weigh those tradeoffs, then design a fair comparison. The decision should connect validation evidence to the task’s real requirements before the final model is tested.

6.1 Weigh the strengths and costs of neural networks

Neural networks are flexible models with costs that must earn their place in a project. Their value depends on the structure and amount of data, the performance required, and practical limits on explanation, training and prediction.

Where learned features help

Images, audio and text are unstructured data: useful predictive patterns are not neatly supplied as a small set of human-designed columns. Networks can learn intermediate features from these inputs. Specialized architectures are especially effective for image, speech and language tasks with large datasets.

The output building blocks also adapt to many targets: binary labels, one of several classes, several independent labels, or real numbers. With sufficient useful data and computing resources, larger networks can continue improving after simpler models level off. Reusing a network trained on a large related dataset can also provide a strong starting point.

Those successes concern a match among architecture, task and evidence. They do not make a small dense network the best choice for every input type. An image task can justify a specialized network even though a dense classifier is the best starting point for learning the mechanics.

Account for the costs

A large number of parameters creates many ways to fit the training set, including its noise. Networks often need substantial data to generalize well. Architecture, layer widths, learning rate and training duration all require choices. Random initialization and batch shuffling also introduce variation between runs.

Large training jobs can require significant computing time and graphics processors. Prediction cost matters separately: a model may be practical to train once but too slow to run at the required volume. Measure both costs against the task's constraints.

Interpretability is another cost. A logistic regression coefficient describes a feature's effect on log-odds with the other features fixed. Individual network weights are mixed through layers, so reading them does not provide the same direct explanation. When someone needs a clear reason for each decision, explanation quality belongs in the model choice alongside accuracy.

Start simply on ordinary tables

Tabular data has examples in rows and defined features in columns, such as customer records. On moderate-size tabular datasets, tree ensembles often match or beat networks with less tuning. A 2022 benchmark comparing 45 tabular datasets of roughly 10,000 rows found tree-based models ahead overall. That dated result supports trying strong tree baselines; a particular new task still needs its own comparison.

Occam's razor is a useful selection principle: when performance is similar, prefer the simpler, more interpretable model. A slight score difference may matter less than clearer explanations, lower prediction cost or a more stable workflow.

The universal approximation theorem concerns functions that a sufficiently wide network can represent. It provides no guarantee that a chosen training run will find useful weights or generalize to new data. Model capacity, successful optimization and reliable evaluation are separate questions. A sound decision requires evidence about all three.

Key Takeaways

  • Networks learn useful features for complex unstructured inputs.
  • Training data, computing cost and tuning effort affect suitability.
  • Network weights are harder to interpret directly than simple-model coefficients.
  • Tree ensembles are strong candidates for moderate-size tabular data.
  • Prefer a simpler model when its performance meets the task’s needs.

6.2 Choose a model for a concrete problem

Choose a model by connecting the task's requirements to evidence from a fair comparison. Start with a useful baseline and make additional complexity answer a specific need.

Make the decision in order
  1. Identify the input type: a table, images, audio or text.
  2. Count labeled examples and inspect how well they represent the intended prediction setting.
  3. Determine what explanations users need.
  4. Set limits on training time, computing resources and prediction speed.
  5. Build a simple baseline with suitable preprocessing.
  6. Try a network when the baseline falls short and the data and resources support it.
  7. Compare on the same validation data and confirm the selected model once on the test set.

A baseline should be credible. On a classification table, logistic regression may be a simple first model, while a tree ensemble offers a stronger flexible comparison. A deliberately weak baseline makes a network's gain look larger without answering whether the extra work is useful.

Apply the requirements to realistic tasks

A company has 2,000 customer records with 15 columns and needs reasons for cancellation predictions. The data is tabular, the sample is modest and explanations matter. Start with logistic regression or a suitable tree model. Check whether a more complex candidate brings enough useful improvement to justify its explanation and maintenance costs.

A research team has 500,000 labeled plant photos and prioritizes recognition accuracy over explaining each decision. A specialized image network is a strong candidate: the inputs have complex visual structure and the large labeled collection supports feature learning.

A payment service has one million labeled transactions with many interacting features and no per-prediction explanation requirement. Both gradient-boosted trees and a network deserve consideration. A large row count alone does not settle the choice. Compare held-out performance with training and prediction costs.

For 150 Iris flowers, a small network can learn the task, but logistic regression or k-nearest neighbors can achieve similar accuracy more simply. The network serves as an exercise in the workflow, while the model-selection decision can still favor the simpler predictor.

Make the comparison fair

Give candidates the same training, validation and test split, the same relevant metric, and comparable tuning effort. Keep preprocessing fitted only on each model's training data. Account for initialization variation when a small apparent gain could come from a lucky network run.

Select using validation results and the practical requirements. Then report the chosen model's test score along with the candidates' validation scores, the metric, and useful costs such as training time and prediction latency. When two scores are close, explain how the explanation requirement or resource limit affected the choice. Do not test many designs and choose the one with the best test result: that process spends the evidence reserved for the final check.

Key Takeaways

  • Choose from data type, data size, explanation needs and resource limits together.
  • Build a credible baseline before adding complexity.
  • Compare candidates using shared splits and metrics with comparable tuning.
  • Use validation for selection and the test set for final confirmation.

Neural Networks examples

6 Walkthroughs

1

Build a network from small calculations

12 steps
Calculate a neuron, introduce nonlinear responses and count the parameters in a layered model.
  1. 1
    IntroductionFrom measurements to learned features

    A network combines a few operations repeatedly: multiply inputs by weights, add a bias and apply an activation. A layer runs several such units, and the next layer combines their outputs. Follow the calculation inside one unit first, then use it to explain why a hidden layer changes what a classifier can learn.

  2. 2
    ExplanationKeep the two stages separate

    The pre-activation is z=𝐰⋅𝐱+b. The activation is a=g(z). A weight changes how one input contributes to the sum; the bias shifts the whole sum. These learned parameters stay fixed while one example passes through the unit. Apply the activation once to the complete sum, after adding the bias.

  3. 3
    ExampleCalculate the products first

    Use inputs (2,1,4), weights (0.5,−1,0.25) and bias −0.5. The three products are 1, −1 and 1, totaling 1. Adding the bias gives z=0.5. Sigmoid turns that into about 0.622. ReLU would instead return 0.5 from the same pre-activation, showing that the activation choice matters after the arithmetic.

  4. 4
    ChallengeFind the probability from a new sum

    A sigmoid neuron has inputs (2,3), weights (1,−0.5) and bias −0.5. What probability of class 1 does it produce?

    ---reveal---

    The sum is 2−1.5−0.5=0. Sigmoid of zero is 0.5, so the probability estimate is 0.5. The sum zero is not the final probability: it still passes through sigmoid. At a threshold that includes 0.5 in class 1, the predicted label would be 1.

  5. 5
    ExplanationGive hidden layers a bend

    If h=2x+1 and o=3h−4, substitution gives o=6x−1. Two affine layers have become one affine function. Nonlinear hidden activations prevent this collapse. ReLU supplies a bend at zero: it clips negative sums while passing positive ones. Its two straight pieces therefore still produce a nonlinear function.

  6. 6
    ConnectionChoose the output’s meaning

    A hidden layer often starts with ReLU, but the output serves a different job. One sigmoid gives a binary probability; softmax represents one class out of several; separate sigmoids represent tags that may coexist. A linear output permits real-valued regression predictions, including negative temperatures in degrees Celsius. Choose from the target before deciding the last activation.

  7. 7
    ChallengeRepair a temperature predictor

    A model predicts temperature in degrees Celsius, including negative values. Its hidden layers use ReLU, and its single output uses sigmoid. What should change in the output, and why?

    ---reveal---

    Use a linear output so predictions can be any real number. Sigmoid confines them to values between 0 and 1 and cannot represent the negative targets. The hidden ReLU units can stay: they provide nonlinear features without imposing the final prediction’s range.

  8. 8
    ExplanationCount connections into each unit

    A dense layer with n inputs and u units has nu weights and u biases. For a 4–8–3 model, the hidden layer has 4(8)+8=40 parameters and the output has 8(3)+3=27, totaling 67. The input values have no parameters of their own. Here the model has two parameter-bearing layers; the input is layer 0.

  9. 9
    ExampleBuild features that separate XOR

    Let h1=ReLU(x1+x2) and h2=ReLU(x1+x2−1). The output h1−2h2 gives 0 at (0,0), 1 at each mixed pair, and 2−2=0 at (1,1). The hidden activations turn an inseparable pattern in the original two features into a pattern the output can express.

  10. 10
    Key InsightCapacity leaves training work to do

    Universal approximation concerns the functions a sufficiently wide nonlinear network can represent on a compact region. It guarantees that suitable weights exist. Finding them from a finite training set and predicting well on new examples are separate tasks. Extra width adds parameters and can increase overfitting, so architecture should be judged with validation evidence.

  11. 11
    ChallengeCheck a complete architecture

    A model has 3 inputs, 7 ReLU hidden units and one sigmoid output, with biases. How many parameters does it have, and why does replacing the hidden ReLU with a linear activation reduce its flexibility?

    ---reveal---

    The layers have 3(7)+7=28 and 7(1)+1=8 parameters, totaling 36. Linear hidden activations would collapse their computation into one affine score before sigmoid, returning the boundary form of logistic regression.

  12. 12
    RecapRead a model before training it

    For a new architecture, identify what each layer receives, which activation it applies and what its output means. Count weights and biases at the connections into each layer. Those checks reveal the model’s size and representational choices before data is used to fit its parameters.

2

Follow a prediction through layers and batches

10 steps
Trace activations for one example, then organize the same forward computation into matrices.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTrace the values that move forward
  2. 2
    ExplanationSet up the hidden calculations
  3. 3
    ExampleApply ReLU before moving onward
  4. 4
    ExampleTurn the final score into a probability
  5. 5
    ChallengeFollow another input through the same model
  6. 6
    ExplanationUse one row for every example
  7. 7
    ExampleCompute two examples in one product
  8. 8
    TipCheck storage before transposing anything
  9. 9
    ChallengeCombine shapes and the probability axis
  10. 10
    RecapUse shapes to check a prediction pipeline
3

Turn scores into useful classification feedback

13 steps
Choose the output structure, calculate stable softmax and interpret cross-entropy with accuracy.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeparate scores, probabilities and errors
  2. 2
    ExplanationDecide whether labels compete
  3. 3
    ChallengeChoose an output for equipment tags
  4. 4
    TipMatch label encoding to the configured loss
  5. 5
    ExplanationMake every score positive before normalizing
  6. 6
    Key InsightChange the offset without changing the answer
  7. 7
    ChallengeNormalize three large scores
  8. 8
    ExplanationScore the probability of the true class
  9. 9
    ExampleUse the complement for a negative binary label
  10. 10
    ChallengeRead loss when the winning class stays fixed
  11. 11
    TipLet the loss handle logits once
  12. 12
    ChallengeUse one prediction for a decision and a score
  13. 13
    RecapCheck the whole output contract
4

Follow an error backward and update the weights

12 steps
Connect gradient signs, the chain rule and mini-batch training with a worked numerical update.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionGive each training operation one job
  2. 2
    ExplanationMove against the current gradient
  3. 3
    ExampleCalculate an output error
  4. 4
    ExampleApply the parameter changes
  5. 5
    ChallengeFind a gradient before updating
  6. 6
    ConnectionOrganize the repeated updates
  7. 7
    ExplanationMultiply through the path to the loss
  8. 8
    ExampleReach a hidden unit from the output
  9. 9
    ExampleApply the hidden activation’s slope
  10. 10
    ChallengeTrace a hidden gradient and its update
  11. 11
    Key InsightNotice when backward signals shrink
  12. 12
    RecapInspect a training step from end to end
5

Train and inspect a small flower classifier

14 steps
Use the Iris workflow to connect data preparation, framework code, validation and final prediction.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKeep a prediction workflow consistent
  2. 2
    ExplanationMake the three data roles explicit
  3. 3
    TipReuse training statistics
  4. 4
    ExampleDefine the matching networks
  5. 5
    ChallengeDiagnose a validation split
  6. 6
    ExampleConfigure Keras for logits
  7. 7
    ExplanationPut PyTorch operations in order
  8. 8
    ChallengeChoose a duration from the curves
  9. 9
    TipInvestigate unusual loss before training longer
  10. 10
    ExplanationKeep mode and gradient tracking separate
  11. 11
    ExampleRead a small test result
  12. 12
    ChallengeMake one new prediction correctly
  13. 13
    ChallengeDecide whether a saved model is complete
  14. 14
    RecapCarry the complete predictor into use
6

Choose complexity that earns its cost

9 steps
Use data, explanation needs and a fair held-out comparison to decide whether a network is useful.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake model choice answer a practical need
  2. 2
    ExplanationRecognize where learned features help
  3. 3
    ConnectionCount costs beyond accuracy
  4. 4
    ChallengeWeigh a small gain against the requirements
  5. 5
    ExampleChoose initial candidates from the data
  6. 6
    ExplanationGive every candidate a fair comparison
  7. 7
    ChallengeRepair an unfair comparison
  8. 8
    ChallengeUse the whole decision
  9. 9
    RecapReport a decision others can assess

Neural Networks practice questions

50 Practice Questions in 5 sets

Set 1: From individual neurons to batch predictions10 Practice Questions

Question 1 of 10

A neuron has input 3, weight −2 and bias 1. What is its pre-activation?
  1. −6
  2. −5
  3. −8
  4. −3
Show answerHide answer
Answer: B
The weighted input is (−2)(3)=−6, and adding the bias gives −6+1=−5. The bias shifts the total once; leaving it out gives −6. Activation comes afterward, so no activation function is needed to find this pre-activation.

Question 2 of 10

A sigmoid neuron receives inputs (4,−2) with weights (0.25,0.5) and bias 0. What class does it predict at threshold 0.5, counting a value at the threshold as class 1?
  1. Class 0, with probability 0.5.
  2. Class 1, with probability 0.881.
  3. Class 0, with probability 0.119.
  4. Class 1, with probability 0.5.
Show answerHide answer
Answer: D
The products are 0.25(4)=1 and 0.5(−2)=−1, so the sum is zero and sigmoid gives 0.5. The stated decision rule includes the threshold in class 1. A probability near 0.881 comes from losing the negative sign and obtaining a sum of 2.

Question 3 of 10

What does a ReLU activation output for pre-activation −1.8?
  1. 0
  2. −1.8
  3. 1.8
  4. −0.018
Show answerHide answer
Answer: A
ReLU computes the maximum of zero and the pre-activation, so its output is zero. Passing −1.8 unchanged would use a linear activation. The small negative result −0.018 would fit a leaky ReLU with slope 0.01, which is a different activation function.

Question 4 of 10

A network has hidden computation h=4x−2 and output o=2h+5, with no nonlinear activation. What single expression gives the output?
  1. o=8x+3
  2. o=6x+3
  3. o=8x+1
  4. o=8x−9
Show answerHide answer
Answer: C
Substitution gives o=2(4x−2)+5=8x−4+5=8x+1. The multiplier 2 applies to the entire hidden expression, including its bias. Keeping the hidden bias unchanged would produce 8x+3 and would miss that distribution step.

Question 5 of 10

A dense classifier has 5 inputs, 6 hidden units and 2 outputs, with a bias for every computed unit. How many learned parameters does it have?
  1. 42
  2. 50
  3. 44
  4. 52
Show answerHide answer
Answer: B
The hidden layer has 5(6)+6=36 parameters, and the output layer has 6(2)+2=14. Their sum is 50. Counting only the 42 connections omits eight biases; the input values do not have additional learned parameters of their own.

Question 6 of 10

A 3–4–2 dense network is changed to 3–5–2, retaining all biases. How many parameters are added, and where do they come from?
  1. 5: three entering the new unit and two leaving it.
  2. 7: four entering the new unit and three leaving it.
  3. 6: four entering the new unit and two leaving it.
  4. 4: three entering the new unit and one bias.
Show answerHide answer
Answer: C
The extra hidden unit needs three incoming weights and one bias, plus one outgoing weight to each of the two existing outputs. This adds six parameters. The output biases already exist and stay unchanged; adding a new bias for each outgoing connection overcounts them.

Question 7 of 10

Two hidden ReLU units have pre-activations −2 and 3. Their output unit has weights 0.4 and −0.5, bias 2 and a linear activation. What does the network output?
  1. 0.5
  2. −0.3
  3. 3.5
  4. 1.5
Show answerHide answer
Answer: A
The hidden activations are 0 and 3, so the output sum is 0.4(0)−0.5(3)+2=0.5. The linear activation leaves this unchanged. Using the hidden sum −2 without applying ReLU would instead give −0.3 and would skip a required layer operation.

Question 8 of 10

A network has h1=ReLU(x1−x2), h2=ReLU(x2−x1) and sigmoid output σ(2h1−h2−1). What class is predicted for (1,4) at threshold 0.5?
  1. Class 1, from an output sum of 2.
  2. Class 0, from an output sum of −10.
  3. Class 1, from an output sum of 5.
  4. Class 0, from an output sum of −4.
Show answerHide answer
Answer: D
The hidden sums are −3 and 3, so ReLU gives h1=0 and h2=3. The output sum is 2(0)−3−1=−4, whose sigmoid is below 0.5, giving class 0. The sum −10 results from passing the negative hidden pre-activation forward unchanged.

Question 9 of 10

A Keras Dense layer receives batches with 7 features per example and has 5 units. What is its kernel shape?
  1. (5, 7)
  2. (7, 7)
  3. (5, 5)
  4. (7, 5)
Show answerHide answer
Answer: D
Keras stores one kernel row per input feature and one column per output unit, giving (7, 5). The transposed shape (5, 7) is the storage convention used by PyTorch Linear. Batch size controls the input row count and does not add a kernel dimension.

Question 10 of 10

A PyTorch batch has shape (12, 7) and enters nn.Linear(7, 5). What are the stored weight shape and output shape?
  1. Weights (7, 5); output (12, 5).
  2. Weights (5, 7); output (12, 5).
  3. Weights (5, 7); output (5, 12).
  4. Weights (7, 12); output (7, 5).
Show answerHide answer
Answer: B
PyTorch stores weights as output features by input features, so their shape is (5, 7). Linear applies the transpose internally, preserving the 12 examples and producing five values each. Using (7, 5) for stored weights confuses PyTorch storage with the row-wise matrix formula.
Set 2: Choose outputs and interpret classification loss10 Practice Questions

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

Question 1 of 10

A classifier produces logits (ln⁡2,0,0). What probabilities does softmax produce?
  1. (1,0,0)
  2. (0.333,0.333,0.333)
  3. (0.667,0.167,0.167)
  4. (0.5,0.25,0.25)
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A multiclass model returns logits (0.2,−0.4,1.1). Which zero-based class index has the largest softmax probability?
  1. 0
  2. 2
  3. 1
  4. 3
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A document can receive any combination of four topic tags. What output activation fits these labels?
  1. Four outputs joined by softmax.
  2. One sigmoid output for all tags.
  3. Four separate sigmoid outputs.
  4. One linear output for a tag index.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A Keras model returns five raw scores per example, and labels are integer indices from 0 to 4. What loss configuration matches this output?
  1. Sparse categorical cross-entropy with from_logits=True.
  2. Sparse categorical cross-entropy with from_logits=False.
  3. Categorical cross-entropy with from_logits=True.
  4. Binary cross-entropy with from_logits=True.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A system receives logits (1200,1198,1198). It must report probabilities without overflowing. What transformed scores give the same probabilities, and what is the winning probability approximately?
  1. (0,−2,−2); 0.881.
  2. (1,0.998,0.998); 0.334.
  3. (2,0,0); 0.881.
  4. (0,−2,−2); 0.787.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Two classifiers give logits (1,0,−1) and (3,1,−1) for the same example. How do their winners and confidence compare?
  1. Both choose class 0; the second gives it higher probability.
  2. Both choose class 0; their probabilities are identical.
  3. They choose different classes; the second is more confident.
  4. Both choose class 0; the first gives it higher probability.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A binary classifier predicts probability 0.8 for class 1, but the true label is 0. What is its cross-entropy loss approximately?
  1. 0.223
  2. 0.800
  3. 1.609
  4. 1.386
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A batch has two examples with true-class probabilities 0.5 and 0.25. What is the mean cross-entropy loss approximately?
  1. 2.079
  2. 1.040
  3. 0.375
  4. 0.981
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

On two examples with true labels 0 and 1, a model changes probabilities from (0.6,0.4),(0.4,0.6) to (0.9,0.1),(0.49,0.51). What happens to accuracy and mean cross-entropy?
  1. Accuracy stays 100%; mean loss rises.
  2. Accuracy falls to 50%; mean loss falls.
  3. Accuracy stays 100%; mean loss falls.
  4. Accuracy stays 100%; mean loss stays fixed.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A three-class PyTorch model applies softmax in its final layer and trains with CrossEntropyLoss and integer labels. What change restores the intended logits-based loss without changing the hidden layers?
  1. Remove final softmax; keep the three raw output scores.
  2. Keep final softmax; convert class indices to float32.
  3. Replace final softmax with three separate sigmoids.
  4. Keep final softmax; subtract each row’s largest probability.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Trace gradients and training updates10 Practice Questions

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

Question 1 of 10

A weight is 0.7, its gradient is −0.4, and the learning rate is 0.1. What is its next gradient descent value?
  1. 0.66
  2. 0.30
  3. 0.71
  4. 0.74
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A training set has 250 examples, batch size 32 and no dropped final batch. How many updates occur in 12 epochs?
  1. 84
  2. 93
  3. 96
  4. 3000
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A sigmoid neuron has input 2, weight 0, bias 0 and target 1. After one binary-cross-entropy gradient descent step with learning rate 0.2, what are its new weight and bias?
  1. Weight 0.2; bias 0.1.
  2. Weight 0.1; bias 0.1.
  3. Weight −0.2; bias −0.1.
  4. Weight 0.2; bias 0.2.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

In a PyTorch training step, what operation computes parameter gradients from the loss?
  1. optimizer.step()
  2. loss.backward()
  3. optimizer.zero_grad()
  4. model.eval()
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A ReLU hidden unit has pre-activation −0.7 for one example. What gradient contribution does that example make to this unit’s incoming weights?
  1. Zero for each incoming weight.
  2. The output error for each weight.
  3. The incoming gradient times −0.7.
  4. The outgoing weight for each input.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A network has h=ReLU(wx+b) and sigmoid output a=σ(vh+c) with binary cross-entropy. For x=3,w=1,b=−1,v=2,c=−4,y=1, what is the gradient with respect to w?
  1. −1
  2. −1.5
  3. −3
  4. 3
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

For h=ReLU(wx+b) and a=σ(vh+c), take x=2,w=−1,b=1,v=3,c=0,y=1 with binary cross-entropy. What are the gradients with respect to w and c?
  1. Gradient of w: −3; gradient of c: −0.5.
  2. Gradient of w: 0; gradient of c: 0.
  3. Gradient of w: −1; gradient of c: −0.5.
  4. Gradient of w: 0; gradient of c: −0.5.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Two hidden units start with identical incoming weights, biases and outgoing weights and receive ordinary gradient descent updates. Why can this initialization waste the extra unit?
  1. The units receive gradients with opposite signs.
  2. The units keep matching outputs and matching updates.
  3. The output loss becomes constant for every input.
  4. The units acquire distinct features from training order alone.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A path through four hidden units has sigmoid derivative 0.2 at each unit and connecting weight factor 0.5 at each backward stage. What multiplier reaches the beginning of this four-stage path?
  1. 0.0016
  2. 0.0001
  3. 0.0625
  4. 0.4096
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A PyTorch loop calls backward() and step() for each batch but never clears gradients. What changes in the update calculation?
  1. Weights reset to their initial values each batch.
  2. The backward pass switches to evaluation mode.
  3. Only the final example contributes to each batch.
  4. Stored gradients accumulate across batches.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Prepare, train and evaluate a classifier10 Practice Questions

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

Question 1 of 10

Which data should determine the means and standard deviations used to scale a classifier’s features?
  1. The training features only.
  2. The training and test features.
  3. The validation features only.
  4. Each prediction batch alone.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A dataset has 600 examples. You reserve 20% for testing, then 25% of the remainder for validation. How many examples remain for training?
  1. 330
  2. 450
  3. 360
  4. 480
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A sorted dataset has 60 rows of class 0, then 60 of class 1, then 60 of class 2. Keras uses validation_split=0.2. A constant predictor always chooses class 0. What is its validation accuracy, and what fraction of the remaining training rows belong to class 2?
  1. Accuracy 33.3%; class-2 fraction 1/3.
  2. Accuracy 0%; class-2 fraction 1/3.
  3. Accuracy 100%; class-2 fraction 1/6.
  4. Accuracy 0%; class-2 fraction 1/6.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A PyTorch classifier uses nn.CrossEntropyLoss() with class-index labels and float32 weights. What input types fit this workflow?
  1. Float64 features and long integer labels.
  2. Float32 features and long integer labels.
  3. Float32 features and float32 class indices.
  4. Long integer features and float32 labels.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

At epoch 18, validation batches contain 10 examples with mean loss 0.2 and 2 examples with mean loss 1.4. At epoch 40, the same batches have mean losses 0.45 and 0.5. Training loss is lower at epoch 40. Which duration has better validation loss, and what is that loss?
  1. Epoch 40; mean validation loss 0.458.
  2. Epoch 18; mean validation loss 0.800.
  3. Epoch 18; mean validation loss 0.400.
  4. Epoch 40; mean validation loss 0.475.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Training and validation accuracy remain unchanged, but both cross-entropy losses decrease. How can this happen?
  1. Cross-entropy counts correct predictions with a different scale.
  2. True-class probabilities improve without changing argmax labels.
  3. Each loss decrease must change at least one predicted class.
  4. Only the winning probability is scored, regardless of the label.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A model correctly classifies 45 of 50 held-out examples. What is its accuracy?
  1. 0.90
  2. 0.10
  3. 0.45
  4. 0.95
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A PyTorch model with dropout gives varying predictions during testing. The code uses torch.no_grad() but has not changed the model’s mode. What change addresses the cause?
  1. Call optimizer.zero_grad() before producing predictions.
  2. Set dim=0 when normalizing its class scores.
  3. Call loss.backward() after producing predictions.
  4. Call model.eval() before producing predictions.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

The training scaler has feature mean 10 and standard deviation 2. A scaler refitted on a prediction batch has mean 12 and standard deviation 4. A classifier gives logits (0,s−0.5), with scaled feature s. For a new value 12, what classes result using the saved versus refitted scaler?
  1. Saved scaler: class 0; refitted scaler: class 0.
  2. Saved scaler: class 1; refitted scaler: class 1.
  3. Saved scaler: class 1; refitted scaler: class 0.
  4. Saved scaler: class 0; refitted scaler: class 1.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A network receives 80 tuning trials and a tree baseline receives one default run; the network’s validation accuracy is slightly higher. What comparison would give stronger evidence that the network earns its added complexity?
  1. Give both comparable tuning effort and compare validation costs and scores.
  2. Keep tuning only the network until its training accuracy reaches 100%.
  3. Choose the winner from repeated test evaluations of both models.
  4. Remove validation and compare the final training loss of both models.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Combine the ideas and choose a useful model10 Practice Questions

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

Question 1 of 10

A project needs directly interpretable coefficients for a binary prediction from 900 tabular records. What model is a suitable first baseline?
  1. A wide ReLU network.
  2. Logistic regression.
  3. A k-nearest-neighbor classifier.
  4. A random forest classifier.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A team has 700,000 labeled machine-sound recordings, ample training compute and a strong accuracy requirement. What model family deserves serious consideration after a simple baseline?
  1. A neural network suited to audio.
  2. Only a single-neuron classifier.
  3. A linear model with no comparison.
  4. A tabular model chosen by row count.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A tree model and a dense network have similar validation scores on a moderate-size table, but the tree trains faster and is easier for the team to explain. What choice follows the simplest-model principle?
  1. Prefer the network because it has more parameters.
  2. Prefer the network because approximation ensures better testing.
  3. Prefer the tree if it meets the task’s requirements.
  4. Prefer whichever reaches lower training loss, ignoring validation.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A team selects among 20 networks by test accuracy, then reports the best test score as its final estimate. The scaler was fitted only on training data. What problem remains, and what evidence is needed now?
  1. The scaler leaks test data; refit it on the full dataset before reporting.
  2. The test set is too large; move half of it into the training set.
  3. Only network randomness matters; report the same test winner repeatedly.
  4. Test-based selection biases the score; obtain fresh untouched evaluation data.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A batch of 9 examples has 6 features each. A dense hidden layer has 4 units and a multiclass output has 3. A colleague gets a final array (3, 9) whose columns sum to 1. What layout should the row-wise workflow produce, and across what axis should probabilities sum to 1?
  1. Shape (9, 3); sum across each row’s classes.
  2. Shape (9, 3); sum down each column’s examples.
  3. Shape (3, 9); sum across each row’s examples.
  4. Shape (9, 4); sum across each row’s hidden units.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A dense network has 8 inputs, two hidden layers of 5 and 4 units, and 3 outputs, with all biases. Removing only the second hidden layer leaves a direct 5-to-3 output. How many parameters are removed overall?
  1. 24
  2. 12
  3. 9
  4. 21
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Two equally accurate three-class models are evaluated on the same two examples. Their true-class probabilities are 0.8 and 0.4 for model A, and 0.6 and 0.6 for model B. Which has lower mean cross-entropy, and why?
  1. Model A; its highest true-class probability is larger.
  2. They tie; their mean true-class probabilities match.
  3. Model B; its true-class probability product is larger.
  4. Model A; its spread in true-class probabilities is larger.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A sigmoid output with binary cross-entropy receives hidden activation 2 through weight 0.5 and has bias −1. The true label is 0. What are the gradients of the output weight and the hidden activation?
  1. Weight gradient 0.25; hidden-activation gradient 1.
  2. Weight gradient 1; hidden-activation gradient 0.25.
  3. Weight gradient −1; hidden-activation gradient −0.25.
  4. Weight gradient 0.5; hidden-activation gradient 0.5.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A classifier is built for six measured features, but new records contain the same six values in a different column order. What should happen before using the saved scaler and model?
  1. Keep the new order because matching the feature count is sufficient.
  2. Restore the training feature order before transforming the records.
  3. Fit a new scaler and keep the changed order for every prediction.
  4. Transpose each batch so that its six features become six examples.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A model for a real-valued change in temperature uses only affine hidden layers and a sigmoid output. Records include negative target changes. What two design issues follow?
  1. Hidden depth adds nonlinear features; sigmoid cannot represent negative targets.
  2. Hidden depth adds no nonlinear features; sigmoid represents every real target.
  3. Hidden depth adds no nonlinear features; sigmoid cannot represent negative targets.
  4. Hidden depth adds nonlinear features; sigmoid represents every real target.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

67 Key Terms, each with its definition

A

Accuracy
Accuracy is the fraction of predictions whose chosen class matches the true label, recording correctness without measuring probability confidence.
Accuracy stays fixed when a correct class remains the winner while its probability increases.
Activation
An activation is the output of a neuron after its activation function has been applied to the weighted sum and bias for the current example.
The next layer receives the hidden activations instead of the original measurements.
Activation function
An activation function is the rule that transforms a neuron’s pre-activation, shaping its response and the meaning or range of its output.
Changing a hidden activation from linear to ReLU adds a bend to the unit’s response.
Argmax
Argmax is the operation that returns an index where a collection has its largest value, used to select the highest-scoring class in a classifier.
Argmax on logits selects the same winning class as argmax after applying softmax.
Artificial neuron
An artificial neuron is a mathematical unit that combines weighted inputs with a bias and applies an activation function to produce one output.
A classifier combines many artificial neurons to transform measurements into a prediction.
Automatic differentiation
Automatic differentiation computes derivatives from the operations used to build a result, tracking their dependencies and combining local derivative rules.
PyTorch records the forward calculation so backward() can populate parameter gradients.

B

Backpropagation
Backpropagation is an efficient algorithm that applies the chain rule backward through a network to compute gradients for its weights and biases.
The backward pass reuses hidden activations stored during the forward computation.
Baseline
A baseline is a credible initial model or method that supplies a comparison point for judging whether a more complex candidate adds useful value.
Logistic regression can establish a simple classification baseline before a dense network is tried.
Batch
A batch is a group of examples processed together; in the row-wise convention, its matrix has one row per example and one column per feature.
A batch of 20 flowers with four measurements enters the model as an array shaped (20, 4).
Bias
A bias is a learned constant added to a neuron’s weighted inputs, allowing the pre-activation to shift independently of the current input values.
A nonzero bias can give a neuron a nonzero pre-activation even when every input is zero.
Binary cross-entropy
Binary cross-entropy is the negative log probability of the observed binary label, using p for label 1 and 1 − p for label 0.
For a true negative, a high predicted class-1 probability creates a large binary cross-entropy.
Broadcasting
Broadcasting is automatic shape expansion that allows an operation such as adding the same bias vector to every row of a batch matrix.
A three-entry output bias is broadcast across all rows of a three-class score matrix.

C

Calibration
Calibration is agreement between predicted probabilities and observed outcome frequencies across comparable predictions made by a model.
To assess predictions near 0.9, check whether their stated class is correct about 90% of the time.
Chain rule
The chain rule calculates derivatives through composed functions by multiplying local derivatives along a path and combining contributions from multiple paths.
A hidden weight’s derivative includes the activation slope and the input multiplied by that weight.
Confusion matrix
A confusion matrix counts predictions by true class and predicted class, showing which class pairs contribute to a classifier’s errors.
A flower classifier’s confusion matrix can reveal confusion between versicolor and virginica.
Cost
A cost is an aggregate loss used as a training objective, commonly the mean of the individual example losses in a dataset or mini-batch.
Two batches of different sizes need example-weighted aggregation to obtain a per-example mean cost.
Cross-entropy
Cross-entropy is a classification loss that scores the probability of the observed label using a negative logarithm, heavily penalizing confident mistakes.
A true-class probability of 0.1 gives a larger cross-entropy than a probability of 0.8.

D

Data leakage
Data leakage occurs when information reserved for evaluation influences model fitting or development, making the resulting evaluation misleadingly favorable.
Fitting the feature scaler on all rows lets test-set information influence preparation.
Dead ReLU
A dead ReLU is a unit inactive for every training example, whose zero local slopes prevent those examples from updating its incoming parameters.
One negative pre-activation does not make a unit dead if it activates for other training inputs.
Decision threshold
A decision threshold is a cutoff used to turn a probability estimate into a class decision, chosen according to the task’s decision rule.
At a class-1 threshold of 0.4, a sigmoid probability of 0.45 produces the class 1 label.
Dense layer
A dense layer is a group of units in which each unit receives every activation from the preceding layer through its own learned weights.
A dense layer with four inputs and six units has 24 weights plus six biases.

E

Epoch
An epoch is one complete pass through the training examples, generally divided into several mini-batches that each supply a parameter update.
Training 96 examples with batch size 16 takes six updates to complete one epoch.
Evaluation mode
Evaluation mode is a framework setting that changes the behavior of mode-dependent layers, such as disabling dropout’s random training-time masking.
In PyTorch, model.eval() and torch.no_grad() serve distinct purposes during final evaluation.

F

Feedforward network
A feedforward network passes information from inputs toward outputs through a sequence of computations, without loops back to earlier layers.
A multilayer perceptron predicts a class by passing features through dense hidden layers.
Forward propagation
Forward propagation is the layer-by-layer calculation that uses a network’s current parameters to transform inputs into output scores or predictions.
A forward pass applies each hidden activation before calculating the next layer’s weighted sums.

G

Gradient
A gradient is a collection of derivatives describing how a loss or cost changes when each trainable parameter increases by a small amount.
A negative weight gradient tells gradient descent to increase that weight for a positive learning rate.
Gradient descent
Gradient descent is an optimization method that repeatedly subtracts a learning-rate-scaled cost gradient from the current parameter values.
With gradient 2 and learning rate 0.01, one step decreases a weight by 0.02.

H

Held-out data
Held-out data consists of examples separated from parameter fitting so that validation or testing can assess predictions beyond the training examples.
Use validation examples for model selection and keep the final test examples untouched until that choice is fixed.
Hidden layer
A hidden layer is a layer between the input and output that learns intermediate feature combinations useful for predicting the target.
Two hidden units can respond to different combinations of the same original measurements.
Hyperparameter
A hyperparameter is a chosen model or training setting, such as layer width or learning rate, that is not fitted as an ordinary weight or bias.
Validation performance helps a learner compare networks with different hidden widths.

I

Inference
Inference is the use of a trained model to calculate predictions for inputs, applying its learned parameters without performing a training update.
A saved classifier performs inference on a new flower after a scaler fitted on the training data transforms its measurements.
Interpretability
Interpretability is the extent to which people can understand how a model’s inputs and internal relationships contribute to its predictions.
Clear coefficient interpretations can favor a simple model when decisions need understandable reasons.

L

Leaky ReLU
A leaky ReLU is an activation function that keeps a small slope for negative inputs while retaining slope one for positive inputs.
With a negative-side slope of 0.01, a leaky ReLU turns pre-activation −5 into −0.05.
Learning curve
A learning curve plots a training or validation metric against training progress, helping reveal improvement, underfitting or overfitting over time.
A widening gap between falling training loss and rising validation loss signals overfitting.
Learning rate
A learning rate is a positive setting that controls the size of gradient-based parameter changes and affects training speed and stability.
An excessive learning rate can make loss oscillate instead of improving steadily.
Logit
A logit is a raw output score before sigmoid or softmax, which can take any real value and is not itself constrained to be a probability.
A final dense layer for three classes produces three logits, and a loss configured for logits interprets them during training.

M

Multiclass classification
Multiclass classification assigns each example exactly one class from several alternatives, with softmax often used to model their competing probabilities.
When each flower has exactly one of three species labels, those species form a multiclass target.
Multilabel classification
Multilabel classification predicts several binary labels for one example, allowing any combination of those labels to be true at the same time.
One equipment inspection can receive both a corrosion tag and a damaged-seal tag.

N

Numerical overflow
Numerical overflow occurs when a computed value exceeds the range of the chosen number type, such as exponentiating a very large positive logit.
Stable softmax shifts scores before exponentiation to avoid overflow from large logits.

O

Occam’s razor
Occam’s razor is a guiding principle that favors a simpler explanation or model when more complex alternatives offer similar useful performance.
A faster baseline can be preferable when a network adds little validation accuracy and obscures explanations.
One-hot encoding
One-hot encoding represents one class as a vector with a 1 in that class’s position and zeros in every other class position.
Class index 2 among four classes becomes the vector (0,0,1,0) when labels are one-hot encoded.
Optimizer
An optimizer is the algorithm that uses calculated gradients to change a model’s parameters, such as ordinary gradient descent or Adam.
The optimizer applies its update after the backward pass has calculated the gradients.
Overfitting
Overfitting occurs when a model fits training-specific details that do not generalize well, often seen as worsening validation loss during better training fit.
Continuing long after validation loss starts rising can make the final predictor less useful.

P

Parameter
A parameter is a value learned during training, such as a weight or bias, that controls how the network transforms inputs into outputs.
Changing a hidden width changes how many parameters the training process must estimate.
Pre-activation
A pre-activation is the weighted sum plus bias computed inside a neuron before its activation function transforms that value into an output.
The same pre-activation of −2 becomes zero under ReLU but stays −2 under a linear activation.
Prediction latency
Prediction latency is the time required to produce a model’s output for an input, a practical constraint that can affect which model is suitable.
A small accuracy gain may not justify a network that cannot meet the task’s prediction-speed requirement.

R

Random seed
A random seed sets the starting state of a pseudorandom generator, helping repeat random choices such as initialization within a consistent setup.
Compare multiple seeds to check whether a small validation improvement survives different initial weights.
ReLU
A rectified linear unit is an activation function that returns zero for a negative input and passes a positive input through unchanged.
A hidden ReLU with pre-activation −0.4 sends an activation of zero to the next layer.

S

Saturation
Saturation is a nearly flat region of an activation function in which a large change in input produces only a small change in output.
A sigmoid near one can have a very small slope, weakening its backward gradient signal.
Shift invariance
Softmax shift invariance is the property that adding the same constant to every logit of one example leaves its class probabilities unchanged.
Subtracting the largest logit uses shift invariance to avoid exponentiating large positive scores.
Sigmoid
The sigmoid is a smooth activation function that maps a real input to a value strictly between zero and one, often used for binary probabilities.
A binary classifier’s sigmoid output of 0.8 estimates the probability of its class 1 label.
Softmax
Softmax converts an example’s competing class logits into positive probabilities by exponentiating them and dividing by the sum of their exponentials.
A softmax runs across class columns so each example’s probabilities total one.
Standardization
Standardization rescales a feature by subtracting its fitted mean and dividing by its fitted standard deviation, using training statistics in this workflow.
Apply the same training-derived standardization to a new flower before its measurements enter the network.
State dictionary
A PyTorch state dictionary stores named parameter and buffer values that can be loaded into a model built with a compatible architecture.
Rebuild the network architecture before loading its saved state dictionary for predictions.

T

Tabular data
Tabular data organizes examples in rows and defined features in columns, such as measurements or customer attributes used to predict a target.
Tree ensembles are a strong comparison for a network trained on moderate-size customer tables.
Tanh
The hyperbolic tangent is an activation function with outputs between −1 and 1, centered at zero and approaching flat regions at either end.
Tanh produces a negative activation for a negative input and gives exactly zero at zero.
Tensor shape
A tensor’s shape lists the sizes of its dimensions, identifying how examples, input features or output units are arranged in its stored values.
The shape (32, 3) means 32 example rows with three values in each row.
Test set
A test set is held-out data reserved to evaluate the chosen predictor after model and training choices have been fixed using development data.
Selecting the best of many test scores would turn that set into part of model development.
Training loop
A training loop repeatedly processes batches by calculating predictions and loss, resetting and computing gradients, and applying parameter updates.
The PyTorch loop calls zero_grad(), computes loss, calls backward() and then applies step().
Training set
A training set is the part of the data used to fit model parameters and any learned preprocessing statistics before held-out evaluation.
The scaler learns feature means from training rows and then transforms validation rows without refitting.

U

Underfitting
Underfitting is insufficient fit to the predictive structure, often reflected in high training and validation errors from limited capacity or poor optimization.
If both losses stay high, inspect architecture, learning rate and data preparation before training longer.
Universal approximation theorem
The universal approximation theorem establishes that suitable nonlinear networks can approximate continuous functions on compact input regions arbitrarily well.
The theorem supports representational capacity but leaves training success and generalization to be assessed.
Unstructured data
Unstructured data includes inputs such as images, audio and text whose useful patterns are not supplied as a small fixed table of designed features.
A large collection of plant photos can support a network that learns visual features.

V

Validation set
A validation set is held-out development data used to compare model choices and training settings without fitting ordinary network parameters on its labels.
The lowest validation loss helps select a useful training duration before final testing.
Vanishing gradients
Vanishing gradients are backward derivative signals that become very small through repeated multiplication, slowing learning in earlier layers.
Many sigmoid slopes can multiply into a tiny signal before the first layer’s weights are updated.
Vectorization
Vectorization expresses repeated numerical calculations as array or matrix operations, allowing many examples or units to be processed efficiently together.
One matrix product calculates a dense layer’s weighted sums for every example in a batch.

W

Weight
A weight is a learned multiplier on one input to a neuron, controlling that input’s contribution to the neuron’s pre-activation.
A negative weight makes a growing input lower the weighted sum when the other inputs are fixed.

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