- Learn
- Computer Science & IT
- Data Science & AI
- Machine Learning
- Neural Networks
Neural Networks Fundamentals
IntermediateLesson 7 of 9 in Machine Learning Course
What you will learn
- 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 neuronCalculate a neuron's weighted sum, bias and activation, and connect a single sigmoid neuron with logistic regression.
- Choose and apply activation functionsCompute 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 parametersDescribe input, hidden and output layers in a fully connected network, explain what hidden units can learn, and count a network's weights and biases.
- Compute the output of a single artificial neuron
- 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 handCompute 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 examplesWrite a dense layer as a matrix product plus a bias, track the shapes through a network, and compute a batch of predictions at once.
- Carry out forward propagation by hand
- 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 taskSet up the output units, activation and label format for binary, multiclass, multilabel and regression tasks.
- Turn scores into class probabilities with softmaxCalculate softmax probabilities, use their properties, and compute them in a numerically stable way.
- Measure prediction quality with cross-entropy lossCompute cross-entropy for multiclass and binary predictions, interpret its values, and use the framework loss functions correctly.
- Match the output layer to the prediction task
- 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 descentFollow one gradient descent update by hand and explain batches, epochs, the learning rate and random initialization.
- Explain backpropagation through the chain ruleTrace how the error at the output is passed backward to give the gradient of every weight, and recognize why gradients can vanish.
- Describe training as minimizing a cost with gradient descent
- 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 codeSplit and scale a small dataset correctly and define the same network in Keras and in PyTorch.
- Train the network and monitor its progressWrite the training step in Keras and in PyTorch, follow the losses during training, and read learning curves.
- Evaluate the model and make predictionsMeasure test performance correctly, turn outputs into probabilities and class names, and compare the network with a simple baseline.
- Prepare the data and define the model in code
- 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 networksIdentify 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 problemApply a step-by-step decision to realistic scenarios and compare a network with simpler models fairly.
- Weigh the strengths and costs of neural networks
Neural Networks study guide
1Explain 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 , the neuron computes
Each input has its own weight. The bias is added once to the total. The number is the pre-activation; the number , after applying the activation function, is the output. Vector notation shortens the first calculation to . A dot product means multiplying matching entries and adding their products.
A positive weight makes an increase in its input raise , with the other inputs fixed. A negative weight makes it lower . 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 , and . Match each weight to its input:
The products add to . Adding the bias gives . Only now apply the activation. With the sigmoid,
With ReLU, the same sum gives . 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 instead of .
Connect the neuron to logistic regression
A single sigmoid neuron computes , exactly the form of logistic regression. Its output is a probability estimate. A separate threshold converts it to a class: at threshold , outputs at or above predict class 1.
Sigmoid reaches when . The decision boundary is therefore . 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: and have label 0, while and 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
| Function | Rule or range | Useful role |
|---|---|---|
| Sigmoid | , between 0 and 1 | Binary probability |
| Tanh | Between −1 and 1, with | Zero-centered hidden activations |
| ReLU | Default starting point for hidden layers | |
| Leaky ReLU | Small negative slope, positive slope 1 | Allows a signal for negative sums |
| Linear | Real-valued regression output |
Sigmoid gives , and . Tanh is related by . For , this gives about . 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 and . With negative slope , leaky ReLU instead gives for input . 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 and a second gives . Substitution produces . 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:
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 , at most . At its output is already about , 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 inputs and units,
Each unit needs one weight per input and one bias. A 4–8–3 network has hidden weights and 8 hidden biases, totaling 40. Its output layer has weights and 3 biases, totaling 27. The full count is .
For 784 inputs, 128 hidden units and 10 outputs, the first layer has parameters. The second has , giving 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
At , both hidden outputs are zero, so . At and , they are and , so . At , they are and , so . 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.
2Compute 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 and bias . Hidden unit 2 has weights and bias . The sigmoid output has weights and bias .
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 , hidden unit 1 gives
Its activation is . Hidden unit 2 gives
Its activation is . Pass to the output layer. Passing would skip ReLU and produce a different network result.
Calculate and interpret the output
The output pre-activation is
The sigmoid produces . This is the estimated probability of class 1. At the threshold , 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 , the first hidden sum is , giving . The second is , giving . Now the output sum is , so .
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 has shape and the layer has units, its Keras-style weight matrix has shape . Then
both have shape . The bias has 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 . 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
Each column of contains one hidden unit's weights. Multiplication gives
Add the bias to both rows, then clip the negative entries:
With output weights and bias , the output sums are and . Sigmoid gives about and . Each row agrees with running that example alone through the network.
Read framework storage correctly
| Layer | Stored weight shape | Operation |
|---|---|---|
| Keras Dense | inputs × units | |
| PyTorch Linear | units × inputs |
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.
3Produce 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
| Task | Output | Typical loss |
|---|---|---|
| Binary classification | One sigmoid probability | Binary cross-entropy |
| One of K classes | K logits, interpreted with softmax | Multiclass cross-entropy |
| Several possible labels | One sigmoid probability per label | Binary cross-entropy per label |
| Regression | One linear output per numeric target | Squared 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 become sigmoid probabilities of about , and . At threshold , 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 . 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 logits, the probability of class is
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 , the exponentials are about , and . Their unrounded total is about . Dividing gives probabilities of about , and . 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 to every score multiplies every exponential by . That factor cancels from numerator and denominator, leaving the probabilities unchanged. Thus gives the same distribution as .
Multiplying logits is different because it changes their gaps. Doubling the example to gives about , and . 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 for float64 and for float32. Use shift invariance to subtract the largest score before exponentiating:
Logits become . The exponentials are and about , giving probabilities about and . 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 , the first softmax probability is . 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 and its predicted probability ,
Here is the natural logarithm. A one-hot target gives the equivalent form : only the true class has a nonzero label entry.
For probabilities near , the loss is approximately if the first class is true, if the second is true, and 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 ,
At , label 1 gives about ; label 0 gives about . For label 0, the true-class probability is , not .
Average losses and interpret progress
The cost 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 for classes, about for three and 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 needs accuracy alongside it. A correct class with probability against and gives a correct argmax but loss about . 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 path | Predictions supplied | Targets supplied |
|---|---|---|
Keras sparse categorical, from_logits=True | Raw logits | Integer class labels |
Keras categorical, from_logits=True | Raw logits | One-hot labels |
PyTorch CrossEntropyLoss, class-index path | Raw logits | torch.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.
4Explain 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
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 . 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 , weights , bias and label 1. The output sum is . Sigmoid gives and loss .
The output error is . Multiplying by inputs gives weight gradients about and . The bias gradient is about , because the bias enters the sum with coefficient 1.
At learning rate , subtracting these negative gradients gives weights about and and bias . Recomputing with unrounded values gives , and loss about . 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 and activation , the chain rule gives
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 and label 1, the earlier forward calculation gave hidden activations and , output sum 1 and sigmoid output about . With binary cross-entropy, the output-sum derivative is .
The output weight from hidden unit 1 has gradient . The weight from hidden unit 2 has gradient zero because its input is zero. The output bias gradient is .
To move into hidden unit 1, multiply the arriving error by its outgoing weight 1.5: . Its positive pre-activation gives ReLU slope 1, so the gradient entering its sum stays about . Multiplying by original inputs 1 and 2 gives incoming weight gradients about and . Its bias gradient is about .
Hidden unit 2 had pre-activation . 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 , so ten sigmoid activation derivatives multiply to at most . 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.
5Train 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 parameters; the output has . 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 . 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 . 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.
6Decide 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
- Identify the input type: a table, images, audio or text.
- Count labeled examples and inspect how well they represent the intended prediction setting.
- Determine what explanations users need.
- Set limits on training time, computing resources and prediction speed.
- Build a simple baseline with suitable preprocessing.
- Try a network when the baseline falls short and the data and resources support it.
- 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
1Build a network from small calculations
12 steps
- 1IntroductionFrom 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.
- 2ExplanationKeep the two stages separate
The pre-activation is . The activation is . 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.
- 3ExampleCalculate the products first
Use inputs , weights and bias . The three products are , and , totaling . Adding the bias gives . Sigmoid turns that into about . ReLU would instead return from the same pre-activation, showing that the activation choice matters after the arithmetic.
- 4ChallengeFind the probability from a new sum
A sigmoid neuron has inputs , weights and bias . What probability of class 1 does it produce?
---reveal---
The sum is . Sigmoid of zero is , 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.
- 5ExplanationGive hidden layers a bend
If and , substitution gives . 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.
- 6ConnectionChoose 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.
- 7ChallengeRepair 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.
- 8ExplanationCount connections into each unit
A dense layer with inputs and units has weights and biases. For a 4–8–3 model, the hidden layer has parameters and the output has , totaling 67. The input values have no parameters of their own. Here the model has two parameter-bearing layers; the input is layer 0.
- 9ExampleBuild features that separate XOR
Let and . The output gives 0 at , 1 at each mixed pair, and at . The hidden activations turn an inseparable pattern in the original two features into a pattern the output can express.
- 10Key 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.
- 11ChallengeCheck 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 and parameters, totaling 36. Linear hidden activations would collapse their computation into one affine score before sigmoid, returning the boundary form of logistic regression.
- 12RecapRead 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.
2Follow a prediction through layers and batches
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTrace the values that move forward
- 2ExplanationSet up the hidden calculations
- 3ExampleApply ReLU before moving onward
- 4ExampleTurn the final score into a probability
- 5ChallengeFollow another input through the same model
- 6ExplanationUse one row for every example
- 7ExampleCompute two examples in one product
- 8TipCheck storage before transposing anything
- 9ChallengeCombine shapes and the probability axis
- 10RecapUse shapes to check a prediction pipeline
3Turn scores into useful classification feedback
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeparate scores, probabilities and errors
- 2ExplanationDecide whether labels compete
- 3ChallengeChoose an output for equipment tags
- 4TipMatch label encoding to the configured loss
- 5ExplanationMake every score positive before normalizing
- 6Key InsightChange the offset without changing the answer
- 7ChallengeNormalize three large scores
- 8ExplanationScore the probability of the true class
- 9ExampleUse the complement for a negative binary label
- 10ChallengeRead loss when the winning class stays fixed
- 11TipLet the loss handle logits once
- 12ChallengeUse one prediction for a decision and a score
- 13RecapCheck the whole output contract
4Follow an error backward and update the weights
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive each training operation one job
- 2ExplanationMove against the current gradient
- 3ExampleCalculate an output error
- 4ExampleApply the parameter changes
- 5ChallengeFind a gradient before updating
- 6ConnectionOrganize the repeated updates
- 7ExplanationMultiply through the path to the loss
- 8ExampleReach a hidden unit from the output
- 9ExampleApply the hidden activation’s slope
- 10ChallengeTrace a hidden gradient and its update
- 11Key InsightNotice when backward signals shrink
- 12RecapInspect a training step from end to end
5Train and inspect a small flower classifier
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep a prediction workflow consistent
- 2ExplanationMake the three data roles explicit
- 3TipReuse training statistics
- 4ExampleDefine the matching networks
- 5ChallengeDiagnose a validation split
- 6ExampleConfigure Keras for logits
- 7ExplanationPut PyTorch operations in order
- 8ChallengeChoose a duration from the curves
- 9TipInvestigate unusual loss before training longer
- 10ExplanationKeep mode and gradient tracking separate
- 11ExampleRead a small test result
- 12ChallengeMake one new prediction correctly
- 13ChallengeDecide whether a saved model is complete
- 14RecapCarry the complete predictor into use
6Choose complexity that earns its cost
9 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake model choice answer a practical need
- 2ExplanationRecognize where learned features help
- 3ConnectionCount costs beyond accuracy
- 4ChallengeWeigh a small gain against the requirements
- 5ExampleChoose initial candidates from the data
- 6ExplanationGive every candidate a fair comparison
- 7ChallengeRepair an unfair comparison
- 8ChallengeUse the whole decision
- 9RecapReport a decision others can assess
Neural Networks practice questions
Set 1: From individual neurons to batch predictions10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
(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
(12, 7) and enters nn.Linear(7, 5). What are the stored weight shape and output shape?Show answerHide answer
(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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
CrossEntropyLoss and integer labels. What change restores the intended logits-based loss without changing the hidden layers?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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
backward() and step() for each batch but never clears gradients. What changes in the update calculation?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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
nn.CrossEntropyLoss() with class-index labels and float32 weights. What input types fit this workflow?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
torch.no_grad() but has not changed the model’s mode. What change addresses the cause?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
(3, 9) whose columns sum to 1. What layout should the row-wise workflow produce, and across what axis should probabilities sum to 1?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Accuracy
Activation
Activation function
Argmax
Artificial neuron
Automatic differentiation
backward() can populate parameter gradients.B
Backpropagation
Baseline
Batch
(20, 4).Bias
Binary cross-entropy
Broadcasting
C
Calibration
Chain rule
Confusion matrix
Cost
Cross-entropy
D
Data leakage
Dead ReLU
Decision threshold
Dense layer
E
Epoch
Evaluation mode
model.eval() and torch.no_grad() serve distinct purposes during final evaluation.F
Feedforward network
Forward propagation
G
Gradient
Gradient descent
H
Held-out data
Hidden layer
Hyperparameter
I
Inference
Interpretability
L
Leaky ReLU
Learning curve
Learning rate
Logit
M
Multiclass classification
Multilabel classification
N
Numerical overflow
O
Occam’s razor
One-hot encoding
Optimizer
Overfitting
P
Parameter
Pre-activation
Prediction latency
R
Random seed
ReLU
S
Saturation
Shift invariance
Sigmoid
Softmax
Standardization
State dictionary
T
Tabular data
Tanh
Tensor shape
(32, 3) means 32 example rows with three values in each row.Test set
Training loop
zero_grad(), computes loss, calls backward() and then applies step().Training set
U
Underfitting
Universal approximation theorem
Unstructured data
V
Validation set
Vanishing gradients
Vectorization
W
Weight
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.