Deep Learning with PyTorch
- 172Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is deep learning, and how are its models commonly structured?
172 questions
- 1
What is deep learning, and how are its models commonly structured?
Model answer
Deep learning is a subset of machine learning that uses neural networks composed of input, hidden, and output layers. Networks can have one or many hidden layers.
Explanation
The layered structure is the defining model form described for deep learning.
- 2
What inspired the term neural network, and what do neurons represent in this analogy?
Model answer
The original intuition was to draw inspiration from how the human brain learns through interconnected cells. The model's connected units are therefore called neurons.
Explanation
The biological analogy explains the terminology, not a claim that artificial networks work exactly like brains.
- 3
How does deep learning's data requirement generally compare with that of other machine-learning models?
Model answer
Deep-learning models generally require substantially more data to identify patterns, often at least hundreds of thousands of data points.
Explanation
The source attributes the larger requirement to the layered model structure.
- 4
Name several kinds of applications powered by deep learning.
Model answer
Examples include language translation, self-driving cars, medical diagnostics, and chatbots.
Explanation
These examples illustrate the range of applications mentioned.
- 5
What is PyTorch, and what design qualities make it useful?
Model answer
PyTorch is a popular, maintained framework for implementing deep-learning algorithms. It is designed to be intuitive and user-friendly, with similarities to NumPy.
Explanation
These qualities support PyTorch's use for building and working with neural networks.
- 6
How did PyTorch's organizational affiliation change?
Model answer
PyTorch was originally developed by Meta AI as part of Facebook's AI research lab and later moved under the Linux Foundation.
Explanation
This describes the framework's development history.
- 7
What is a PyTorch tensor, and what role does it play?
Model answer
A tensor is PyTorch's fundamental data structure, similar to an array or matrix. It supports mathematical operations and serves as a building block for neural networks.
Explanation
Models use tensors to represent data and carry out computations.
- 8
How can tensors be created from common Python data structures?
Model answer
Tensors can be created from Python lists or NumPy arrays using PyTorch's tensor-construction method, which converts the data into a compatible format.
Explanation
Converting these inputs produces data that PyTorch operations can use.
- 9
How can you inspect a tensor's shape and data type, and why are these checks useful?
Model answer
Use a tensor's shape and data-type attributes to inspect its dimensions and element type. Checking them helps ensure compatibility with model layers and can aid debugging.
Explanation
Shape and data type describe important properties of a tensor's contents and layout.
- 10
When can two tensors be added or subtracted element by element?
Model answer
They can be added or subtracted when their shapes are compatible; in the examples described, compatibility means identical shapes. Incompatible shapes produce an error.
Explanation
Matching dimensions lets corresponding elements be paired in these operations.
- 11
What does element-wise multiplication do?
Model answer
It multiplies corresponding elements of two tensors of the same shape.
Explanation
Each output element comes from the matching positions in the inputs.
- 12
How is each entry of a matrix product calculated?
Model answer
Each entry is obtained by multiplying a row of the first matrix by a column of the second matrix element by element and summing the products.
Explanation
This row-by-column calculation combines two matrices into a new matrix.
- 13
What information do the input and output layers of a neural network represent?
Model answer
The input layer represents the dataset's features, while the output layer represents the model's predictions.
Explanation
Hidden layers, when present, lie between these input and output layers.
- 14
What is a fully connected network?
Model answer
It is a network in which every neuron in a layer connects to every neuron in the preceding layer.
Explanation
The source also calls a network with every input neuron connected to every output neuron fully connected.
- 15
Why is a network with one linear layer and no hidden layers a useful starting point?
Model answer
It is equivalent to a linear model and provides a simple way to understand neural-network fundamentals before adding complexity.
Explanation
Starting with a basic model makes the effects of additional layers easier to study.
- 16
How are the input and output dimensions of a linear layer chosen?
Model answer
The input dimension must match the number of input features, and the output dimension is chosen to match the desired output size, such as the number of classes.
Explanation
The input-size match allows the layer to accept the tensor; the output size determines its result's width.
- 17
What computation does a linear layer perform, and what are its learnable quantities?
Model answer
A linear layer combines its inputs using weights and biases. The weights determine the contribution of input features, while the bias provides an additional baseline term.
Explanation
Weights and biases define the neuron's linear transformation.
- 18
How are linear-layer weights and biases set before training?
Model answer
They are initially assigned random values and are tuned during training.
Explanation
Training adjusts these parameters so the model can improve its predictions.
- 19
In the weather-prediction example, what do weights and bias represent?
Model answer
A larger humidity weight represents humidity's stronger predictive influence on rain or clouds. The bias represents baseline information, such as a tropical region's high probability of rain.
Explanation
Weights capture feature importance; bias can account for a baseline prediction.
- 20
What does a sequential container do when used to build a neural network?
Model answer
It stacks layers so that the network passes its input through them in sequence and returns the resulting output.
Explanation
Layers inside the container can form the network's hidden layers.
- 21
What dimension-matching rule must hold when linear layers are stacked?
Model answer
The input dimension of each layer must equal the output dimension of the preceding layer.
Explanation
This makes the output tensor from one layer a valid input to the next.
- 22
For a three-layer network with dimensions 10-to-18, 18-to-20, and 20-to-5, what is the output size?
Model answer
The output size is 5, because the final layer maps 20 inputs to 5 outputs.
Explanation
The last layer's output dimension determines the network's final number of values.
- 23
How many learnable parameters does one neuron have if it receives inputs from n previous-layer neurons?
Model answer
It has n weights and one bias, for a total of n+1 learnable parameters.
Explanation
Each incoming connection has a weight, and the neuron also has a bias.
- 24
How does adding hidden layers affect model capacity and training?
Model answer
Adding hidden layers generally increases the number of parameters and thus model capacity. Higher-capacity models can represent more complex patterns but may take longer to train.
Explanation
Parameter count is one way to assess model capacity.
- 25
How many parameters are in the described two-layer network if the first layer has four neurons with eight inputs each and the second has two neurons with four inputs each?
Model answer
The first layer has 4(8+1)=36 parameters, and the second has 2(4+1)=10, giving 46 in total.
Explanation
Each neuron contributes one weight per input plus one bias.
- 26
How can PyTorch calculate the total number of model parameters?
Model answer
Loop through the model's parameters and sum the number of elements in each tensor, using the tensor element-count method.
Explanation
The resulting sum is the total number of learnable parameter values.
- 27
What trade-off can arise from using too many or too few parameters?
Model answer
Too many parameters can increase training time or cause overfitting, while too few can limit the model's ability to learn.
Explanation
Model size must balance learning capacity and efficiency.
- 28
Why do neural networks use activation functions between linear operations?
Model answer
Activation functions add nonlinearity, allowing networks to learn complex interactions that cannot be represented by only linear relationships.
Explanation
Without nonlinear transformations, stacking linear layers alone does not provide the same ability to model complex patterns.
- 29
What is a pre-activation output?
Model answer
It is the output of the final linear layer before an activation function transforms it.
Explanation
The activation function converts this raw output into a form appropriate to the task.
- 30
When is sigmoid commonly used, and what range does it produce?
Model answer
Sigmoid is commonly used for binary classification and transforms its input into a value between 0 and 1, interpretable as a probability.
Explanation
The bounded output can be compared with a classification threshold.
- 31
How does a sigmoid probability determine a binary class in the described example?
Model answer
A probability greater than 0.5 is labeled class 1; a value below 0.5 is labeled class 0.
Explanation
The example uses the threshold to convert a probability into a class label.
- 32
What happens to tensor shape when sigmoid is applied element by element?
Model answer
The output has the same shape as the input tensor.
Explanation
Sigmoid transforms values without changing the number or arrangement of tensor elements.
- 33
What is the relationship between a network of linear layers with sigmoid output and logistic regression?
Model answer
A neural network with only linear layers and a sigmoid activation behaves like logistic regression. Additional nonlinear layers and activations enable more complex deep-learning behavior.
Explanation
The source distinguishes this simple setup from deeper nonlinear networks.
- 34
When is softmax typically used, and what properties does its output have?
Model answer
Softmax is used for classification among more than two classes. Its outputs form a probability distribution: each value is between 0 and 1, and the values sum to 1.
Explanation
This makes the outputs comparable as probabilities across classes.
- 35
How is a multiclass label selected from softmax outputs?
Model answer
Choose the class with the highest probability.
Explanation
The largest softmax value indicates the model's most likely class.
- 36
What does specifying the last dimension for softmax indicate?
Model answer
It tells softmax to apply the transformation across the tensor's last dimension, which holds the class scores.
Explanation
The probabilities for a sample must be normalized across its class dimension.
- 37
How do the output-layer designs differ for binary classification, multiclass classification, and regression?
Model answer
Binary classification produces one output and commonly uses sigmoid; multiclass classification produces one score per class and uses softmax; regression produces continuous values and needs no final sigmoid or softmax.
Explanation
The output layer and activation should match the prediction task.
- 38
What is a forward pass?
Model answer
A forward pass sends input data through each network layer, transforming it at each stage until the final prediction or output is produced.
Explanation
It uses the model's current weights and biases to compute outputs.
- 39
Why are forward passes used both during training and when making predictions?
Model answer
They produce model outputs from inputs using the current learned parameters, which are needed both to calculate training loss and to make predictions on new data.
Explanation
Training uses the output to assess and update the model; inference uses it to predict.
- 40
What does a loss function measure?
Model answer
It compares a model prediction with the ground-truth value and returns a numerical measure of prediction error; training aims to minimize this loss.
Explanation
A lower loss indicates a better match between predictions and targets under that loss function.
- 41
How do correct and incorrect predictions affect the loss in the bear-classification example?
Model answer
If the model predicts the bear's correct class, mammal, the loss is low; an incorrect prediction produces a higher loss.
Explanation
The loss reflects the discrepancy between the predicted class scores and the true label.
- 42
What is one-hot encoding, and how does it represent a class label?
Model answer
One-hot encoding converts an integer class label into a vector of zeros with a one at the position for the correct class. For three classes, class 0 is represented as [1,0,0].
Explanation
It provides a vector representation of the ground-truth class.
- 43
What are the one-hot encodings for classes 1 and 2 in a three-class task?
Model answer
Class 1 is [0,1,0], and class 2 is [0,0,1].
Explanation
The one is placed at the index corresponding to the target class.
- 44
What does cross-entropy loss take as inputs in the described multiclass setup?
Model answer
It takes the model's raw class scores before softmax and the one-hot-encoded ground-truth label, then returns a single loss value.
Explanation
The scores and target are provided in compatible formats for the classification loss.
- 45
What is the role of a derivative when minimizing a loss function?
Model answer
The derivative gives the local slope of the loss curve and indicates how the loss changes as a parameter changes.
Explanation
The slope's direction and size guide parameter updates.
- 46
What does a zero derivative indicate at the minimum in the valley illustration?
Model answer
The slope is flat at that point, and the derivative is zero; the minimum is the desired target for loss minimization.
Explanation
The illustration uses the flat valley floor to represent a minimum.
- 47
How do global and local minima differ?
Model answer
A global minimum is the lowest value overall, while a local minimum is lower than nearby points but may not be the lowest value of the entire function.
Explanation
Non-convex loss functions can have multiple local minima.
- 48
What is backpropagation, and what does it do to model parameters?
Model answer
Backpropagation computes loss gradients with respect to model parameters and uses them to update weights and biases.
Explanation
Repeating these updates tunes the layers to reduce loss.
- 49
In what order are gradients propagated through a multilayer network?
Model answer
Gradients are calculated from the loss backward, beginning with the parameters of the last layer and continuing toward earlier layers.
Explanation
Each layer's local gradients are found as the backward calculation proceeds.
- 50
Where does PyTorch store parameter gradients after backpropagation?
Model answer
It stores them in the parameters' gradient attributes.
Explanation
These gradients can then be used to update the corresponding weights and biases.
- 51
How is a parameter manually updated using its gradient and a learning rate?
Model answer
Subtract the gradient multiplied by the learning rate from the parameter.
Explanation
This update moves the parameter in the direction intended to reduce loss.
- 52
What is gradient descent?
Model answer
Gradient descent uses loss gradients to update parameters iteratively in an effort to find a minimum of the loss function.
Explanation
PyTorch optimizers automate the gradient-based update process.
- 53
What does an optimizer's parameter iterator provide?
Model answer
It provides an iterable containing the model parameters that the optimizer should update.
Explanation
The optimizer needs access to those parameters to perform its update step.
- 54
What is the role of the optimizer's step operation?
Model answer
It updates model parameters using the gradients computed from the loss.
Explanation
The step applies the optimizer's chosen update rule.
- 55
Why must gradients be cleared during a training loop?
Model answer
Gradients are stored by default and can accumulate across steps, so they are reset before processing a new batch.
Explanation
Clearing them ensures the next update uses the intended batch's gradients.
- 56
What are the functions of training, validation, and test sets?
Model answer
Training data updates model parameters, validation data guides hyperparameter choices, and test data evaluates final performance.
Explanation
Keeping these roles separate supports a meaningful assessment of generalization.
- 57
What is an epoch?
Model answer
An epoch is one complete pass through the training data.
Explanation
Training commonly repeats this pass for multiple epochs.
- 58
What is a batch, and why is batching useful?
Model answer
A batch is a group of samples processed in one iteration. Batching lets models process multiple examples at once and can make training more efficient.
Explanation
A data loader can organize samples into batches.
- 59
What does shuffling a training dataset do, and why can it help?
Model answer
Shuffling randomizes sample order, commonly at each epoch, and can help the model generalize rather than rely on a fixed data order.
Explanation
The source presents shuffling as a way to improve generalization.
- 60
How does a data loader handle a dataset of five samples with a batch size of two?
Model answer
It produces two batches of two samples and a final batch containing the one remaining sample.
Explanation
The last batch can be smaller when the dataset size is not divisible by the batch size.
- 61
How are features and class labels prepared from the animal CSV example?
Model answer
The animal-name column is excluded, the feature columns are converted to a NumPy array, and the type column is stored separately as target labels.
Explanation
The name is not needed for predicting the animal's type.
- 62
What does indexing an individual sample from a tensor dataset return?
Model answer
It returns a tuple containing that sample's input features and target label.
Explanation
The tuple can be unpacked into an input and its corresponding target.
- 63
What is the purpose of a training loop?
Model answer
A training loop repeatedly processes batches, computes predictions and loss, calculates gradients, and updates model parameters over multiple epochs.
Explanation
The loop coordinates the repeated steps needed to train the model.
- 64
What loss function is appropriate for regression, and how is it defined?
Model answer
Mean squared error is commonly used for regression; it is the mean of the squared differences between predictions and true values.
Explanation
It measures the size of numerical prediction errors.
- 65
What tensor type is required for predictions and targets used with the described MSE loss?
Model answer
Both predictions and targets should be floating-point tensors.
Explanation
The regression model parameters and outputs use floating-point values.
- 66
Why should gradients be reset before each training batch?
Model answer
The optimizer retains gradients from previous steps by default, so they must be zeroed before the new batch's forward and backward passes.
Explanation
This prevents gradient accumulation from unintentionally affecting the update.
- 67
How is the mean training loss for an epoch calculated in the described procedure?
Model answer
Sum the loss across training batches and divide by the number of batches.
Explanation
This produces the mean batch loss for that epoch.
- 68
Why use evaluation mode and disable gradient calculations during validation?
Model answer
Evaluation mode makes layers behave as intended for evaluation, while disabling gradients avoids calculations that are unnecessary because validation does not update weights.
Explanation
These settings support efficient validation without training updates.
- 69
Why does the model return to training mode after validation?
Model answer
It must be returned to training mode so it is ready to update its parameters during the next training epoch.
Explanation
Some layers behave differently in training and evaluation modes.
- 70
What pattern in training and validation loss indicates overfitting?
Model answer
Overfitting is indicated when training loss continues to decrease while validation loss begins to rise.
Explanation
The model is fitting the training data increasingly well but not generalizing to unseen data.
- 71
How is multiclass accuracy calculated from predicted class probabilities?
Model answer
Select the class with the highest probability, compare those class indices with the true labels, and compute accuracy over the examples.
Explanation
An argmax operation converts each probability vector to its predicted class.
- 72
Why reset a metric after computing its epoch result?
Model answer
Resetting clears the metric's accumulated state so the next epoch starts with a fresh calculation.
Explanation
Without resetting, the next result could include earlier batches.
- 73
What is overfitting, and what performance pattern does it produce?
Model answer
Overfitting occurs when a model memorizes training data instead of generalizing. It can perform well on training data but poorly on validation or other unseen data.
Explanation
The model has learned the training examples too specifically.
- 74
What factors in the content can contribute to overfitting?
Model answer
A small dataset, excessive model capacity, and large weight values can all contribute to overfitting.
Explanation
Each can make it easier for the model to fit training-specific details.
- 75
What is dropout, and when is it typically placed in a network?
Model answer
Dropout randomly deactivates a fraction of neurons during training to reduce dependence on particular features. It is typically placed after activation functions.
Explanation
This is a regularization strategy for reducing overfitting.
- 76
What does dropout's probability parameter control?
Model answer
It sets the probability that a neuron is set to zero during training; for example, a probability of 0.5 drops half the neurons on average.
Explanation
The parameter controls the fraction of activations randomly removed during training.
- 77
How does dropout differ between training and evaluation?
Model answer
During training, dropout randomly deactivates neurons; during evaluation, dropout is disabled so all neurons are active for stable predictions.
Explanation
The model's mode controls this behavior.
- 78
What is weight decay, and how can it reduce overfitting?
Model answer
Weight decay adds a penalty that encourages smaller parameter values, making excessive weight growth less likely and helping the model generalize.
Explanation
A small weight-decay setting, such as 0.001, is one example given.
- 79
How does increasing weight decay affect regularization?
Model answer
A higher weight-decay value applies stronger regularization and can make overfitting less likely.
Explanation
The penalty increasingly discourages large weights.
- 80
What is data augmentation, and how can it help when additional data is unavailable?
Model answer
Data augmentation creates altered versions of existing examples, expanding the effective dataset and potentially reducing overfitting.
Explanation
It is a way to increase data diversity without collecting new examples.
- 81
What sequence of steps is recommended for tackling a new deep-learning problem?
Model answer
First verify the problem is learnable, establish a model that can overfit the training data and a validation baseline, reduce overfitting, and then tune hyperparameters.
Explanation
This workflow starts by checking solvability before optimizing generalization.
- 82
Why begin by training on a single example?
Model answer
A model that is set up correctly should quickly reach near-zero loss and perfect accuracy on that example, helping reveal bugs before training on the full dataset.
Explanation
The single-example test checks whether the training setup can learn at all.
- 83
How should regularization experiments be compared when trying to improve validation performance?
Model answer
Track the settings used and their corresponding validation accuracy, while checking that regularization has not become so strong that both training and validation performance fall.
Explanation
The goal is to balance reduced overfitting with adequate learning.
- 84
How do grid search and random search differ?
Model answer
Grid search tests specified parameter values at fixed intervals, while random search samples values from specified ranges.
Explanation
Random search can explore a wider variety of settings without testing every point in a grid.
- 85
What are the described typical ranges for learning rate and momentum?
Model answer
The content gives learning-rate values from 0.01 to 0.0001 and momentum values from 0.85 to 0.99 as typical ranges.
Explanation
These are example ranges for optimizer hyperparameters, not universal requirements.
- 86
What does the learning rate control in gradient-based optimization?
Model answer
It controls the step size of parameter updates.
Explanation
The update size depends on the gradient as well as the learning rate.
- 87
What can happen if the learning rate is too small?
Model answer
The optimizer may move toward the minimum very slowly and require many more steps.
Explanation
Small update steps can make training progress inefficient.
- 88
What can happen if the learning rate is too large?
Model answer
The optimizer can overshoot the minimum and bounce between sides of the loss curve instead of settling.
Explanation
Excessively large steps prevent stable convergence.
- 89
Why do gradient-descent steps become smaller near the bottom of a smooth valley?
Model answer
The slope becomes less steep near the minimum, so the gradient decreases and the update step, which depends on the gradient, also becomes smaller.
Explanation
The learning rate scales the gradient rather than imposing a fixed step size.
- 90
What role does momentum play in an optimizer?
Model answer
Momentum adds inertia based on previous steps, helping updates move smoothly and potentially pass through local minima.
Explanation
It can keep steps large even when the current gradient is small if earlier steps were large.
- 91
How can momentum help on a non-convex loss surface?
Model answer
It can help an optimizer move past a local minimum that would trap it when momentum is absent.
Explanation
The content's example finds a better minimum using momentum of 0.9 rather than none.
- 92
What is the difference between vanishing and exploding gradients?
Model answer
Vanishing gradients become so small that earlier layers receive ineffective updates; exploding gradients become so large that updates can be huge and training can diverge.
Explanation
Both are forms of gradient instability that can prevent effective learning.
- 93
What three-part approach is presented for addressing unstable gradients?
Model answer
Use appropriate weight initialization, suitable activation functions, and batch normalization.
Explanation
The three techniques address gradient stability at initialization and during training.
- 94
What variance properties should a suitable weight initialization aim to preserve?
Model answer
It should keep the variance of layer inputs close to the variance of layer outputs, and keep gradient variance similar before and after passing through the layer.
Explanation
These properties help prevent gradients from shrinking or growing unstably.
- 95
What initialization is suggested for ReLU and similar activations?
Model answer
He initialization, also called Kaiming initialization, is suggested for ReLU and similar activation functions.
Explanation
The content describes applying Kaiming initialization to a layer's weights.
- 96
What is the dying-neuron problem associated with standard ReLU?
Model answer
A neuron can stop learning if its inputs become negative, because ReLU outputs zero for negative inputs.
Explanation
With zero output for negative values, the neuron can receive no useful gradient in that region.
- 97
How does ELU address a limitation of ReLU?
Model answer
ELU has nonzero gradients for negative inputs, helping avoid dying neurons; its average output is also near zero, making it less prone to vanishing gradients.
Explanation
These properties are presented as reasons to use ELU as an alternative activation.
- 98
What is batch normalization?
Model answer
It normalizes layer outputs by subtracting their mean and dividing by their standard deviation, then scales and shifts them using learned parameters.
Explanation
The learned scale and shift allow the model to choose a useful distribution for the next layer's inputs.
- 99
How can batch normalization improve training?
Model answer
It can speed loss reduction and make training more resistant to unstable-gradient problems by controlling the distribution of layer inputs.
Explanation
Its learned transformations adjust the normalized outputs for subsequent layers.
- 100
Why initialize linear-layer weights and normalize input features to small or stable ranges?
Model answer
A neuron's output is a weighted sum of its inputs, so keeping inputs and weights controlled helps produce stable outputs and avoid extreme values that can slow training.
Explanation
The content identifies data normalization and small initial weights as ways to support stability.
- 101
What is transfer learning?
Model answer
Transfer learning reuses a model trained on one task as a starting point for a second task.
Explanation
Previously learned weights can be loaded instead of beginning with random weights.
- 102
How does fine-tuning differ from using a model's weights as a starting point generally?
Model answer
Fine-tuning trains a previously trained model on a related second task, typically using a smaller learning rate.
Explanation
The smaller learning rate adjusts existing useful parameters more cautiously.
- 103
What does it mean to freeze a network layer during fine-tuning?
Model answer
It means preventing that layer's parameters from being updated, for example by setting their gradient requirement attribute to false.
Explanation
Frozen parameters are not trained on the new task.
- 104
Which layers are commonly frozen as a rule of thumb during transfer learning?
Model answer
Early layers are commonly frozen, while layers closer to the output are fine-tuned.
Explanation
This is the rule of thumb given for deciding which parts of a pretrained network to train.
- 105
What does image augmentation need to preserve for supervised classification?
Model answer
It should preserve the example's class label; an augmentation that changes what the image depicts can introduce misleading labels.
Explanation
For example, a vertical flip can make a handwritten W resemble an M.
- 106
What image augmentations are proposed for cloud classification, and what variations do they represent?
Model answer
Random rotation represents different cloud angles, horizontal flips represent different sky viewpoints, and random contrast adjustment represents lighting variation.
Explanation
These transformations are selected to reflect plausible variations in cloud images.
- 107
What is a pixel, and how are grayscale and color pixels represented?
Model answer
A pixel is the smallest image unit. Grayscale pixels can be represented by an intensity from black to white, while color pixels are typically represented by red, green, and blue channel values.
Explanation
The content describes grayscale intensity as an integer from 0 to 255 and color as three channel intensities.
- 108
Why can a fully connected layer be inefficient for image inputs?
Model answer
Images can contain tens of thousands of pixels, so fully connected layers can require many parameters, increasing training cost and overfitting risk.
Explanation
A grayscale image of 256 by 256 pixels already has over 65,000 input values.
- 109
Why may a linear layer fail to recognize the same object when it moves within an image?
Model answer
Its connections do not inherently capture spatial patterns, so a detector learned at one location may not recognize the object at another location.
Explanation
Convolutional layers are better suited to detecting image patterns across locations.
- 110
What is a convolutional filter, and what does it produce?
Model answer
A filter is a small grid of parameters that slides across the input and performs a convolution at each position, producing a feature map.
Explanation
Each feature map records responses to patterns detected by its filter.
- 111
How is one convolution value calculated from an input patch and a filter?
Model answer
Multiply corresponding elements of the patch and filter, then sum the products to produce one feature-map value.
Explanation
This is the dot-product operation described for a convolution.
- 112
What is the effect of using multiple convolutional filters?
Model answer
Each filter produces a separate feature map, and activations can be applied to those maps to form the convolutional layer's output.
Explanation
Different filters can respond to different input patterns.
- 113
What is zero padding, and why is it used in convolutional layers?
Model answer
Zero padding adds zeros around the input. It can preserve spatial dimensions and lets border pixels be treated more evenly.
Explanation
Without padding, filters overlap border pixels fewer times, which can lose border information.
- 114
What does max pooling do?
Model answer
It applies a window to the input and passes forward the maximum value within each window.
Explanation
A non-overlapping window of size 2 by 2 halves the feature map's height and width.
- 115
Why is max pooling commonly used after convolutional layers?
Model answer
It reduces feature-map spatial dimensions, which reduces computation and the number of values passed through later layers.
Explanation
Pooling summarizes local regions using their maximum values.
- 116
What are the two main parts of the cloud-classifier architecture described?
Model answer
It has a feature extractor made of convolution, activation, and max-pooling layers, followed by a classifier that uses a linear layer.
Explanation
The feature extractor transforms the image before the classifier predicts its class.
- 117
How do convolution and pooling affect the dimensions in the described two-stage image network?
Model answer
Convolution changes the number of feature maps, while padding preserves height and width; each size-two pooling operation halves height and width.
Explanation
The described example ultimately produces feature maps of size 64 by 16 by 16.
- 118
Why should test-image transformations generally exclude random data augmentation?
Model answer
Evaluation should measure predictions for the specific test images, not randomly altered versions; test transformations should therefore retain necessary conversions and resizing without random augmentation.
Explanation
The source recommends separate, non-augmented test transforms.
- 119
How do precision and recall differ?
Model answer
Precision is the fraction of positive predictions that are correct, while recall is the fraction of actual positive examples that are correctly predicted.
Explanation
Precision concerns predicted positives; recall concerns all actual positives.
- 120
What does macro-averaged precision or recall do in a multiclass task?
Model answer
It calculates the metric separately for each class and takes the unweighted mean, giving every class equal influence regardless of size.
Explanation
Macro averaging can be useful when performance on smaller classes matters.
- 121
How does micro averaging aggregate multiclass precision and recall?
Model answer
It totals true positives, false positives, and false negatives across all classes, then calculates the metric from those global totals.
Explanation
The result reflects the combined counts across classes.
- 122
How does weighted averaging differ from macro averaging?
Model answer
Weighted averaging takes the mean of per-class scores with weights proportional to the number of samples in each class, so larger classes have more influence.
Explanation
Macro averaging instead gives each class equal weight.
- 123
When might macro, micro, or weighted averaging be appropriate?
Model answer
Macro averaging is useful when smaller classes deserve equal consideration; micro averaging aggregates performance globally; weighted averaging is useful when class imbalance matters and errors in larger classes should have more influence.
Explanation
The preferred average depends on how class sizes and class-specific performance should affect the result.
- 124
What is sequential data, and why does order matter?
Model answer
Sequential data is ordered in time or space and can contain dependencies between data points; changing the order can change its meaning or interpretation.
Explanation
Examples include time series, text, and audio.
- 125
Why should a sequential dataset generally be split by time rather than randomly?
Model answer
A random split can create lookahead bias by letting training include information from later times than the test examples. Splitting by time better reflects forecasting future data.
Explanation
The example trains on the first three years and tests on the fourth.
- 126
What is lookahead bias in a forecasting task?
Model answer
It occurs when a model has information about the future when making a forecast that should be based only on past information.
Explanation
A random time-series split can inadvertently create this problem.
- 127
How is a sequence-length choice of 96 justified for forecasting electricity use from 15-minute measurements?
Model answer
A day contains 24 hours, with four 15-minute intervals per hour, so a 24-hour input sequence contains 24×4=96 data points.
Explanation
The target is the data point immediately after that input sequence.
- 128
How are input and target examples formed when chunking a time series?
Model answer
Each input is a fixed-length run of consecutive values, and its target is the next value immediately following that run.
Explanation
This creates supervised examples for next-value forecasting.
- 129
Why does a sequence-generation loop stop before the final data points?
Model answer
It must stop where a complete input sequence and its subsequent target are still available.
Explanation
Otherwise, the final input would lack enough data points or a next-value target.
- 130
What are recurrent neural networks, and how do they differ from feedforward networks?
Model answer
RNNs process inputs over time and include connections that pass a hidden state forward to later time steps; feedforward networks pass data in one direction through layers.
Explanation
The recurrent connection lets an RNN retain information from earlier inputs.
- 131
What information does an RNN receive and produce at a time step?
Model answer
It receives the current input and previous hidden state, then produces an output and a new hidden state.
Explanation
The new hidden state is passed to the next time step.
- 132
How is an RNN's hidden state initialized at the first time step?
Model answer
It is typically initialized to zero because there is no previous hidden state.
Explanation
The initial state provides a starting point for processing the sequence.
- 133
How can an RNN output at a time step depend on earlier inputs?
Model answer
The current hidden state carries information from previous steps, so later outputs can depend on earlier inputs in the sequence.
Explanation
This recurrent memory is why RNNs can handle sequential data.
- 134
What does it mean to unroll a recurrent neuron through time?
Model answer
It means depicting the same recurrent computation once at each time step, with each instance receiving the preceding step's hidden state.
Explanation
Unrolling makes the time-dependent sequence of computations visible.
- 135
How does stacking recurrent layers create a deep recurrent network?
Model answer
The output of one recurrent layer is passed to another recurrent layer, so each input is processed through multiple layers in sequence.
Explanation
This resembles stacking layers in dense or convolutional networks.
- 136
What defines a sequence-to-sequence RNN architecture?
Model answer
It receives a sequence and uses the output produced at every time step.
Explanation
Real-time speech recognition is one example described.
- 137
What defines a sequence-to-vector RNN architecture, and what is one use case?
Model answer
It receives a sequence and uses only the final output to produce one result, such as a topic classification for an entire text.
Explanation
The model processes the full input before deciding on the output.
- 138
What defines a vector-to-sequence architecture, and what is one use case?
Model answer
It receives a single input, with other time-step inputs replaced by zeros, and uses outputs from every time step to generate a sequence, such as text.
Explanation
A vector representing a topic, style, or sentiment can condition generated text.
- 139
How does an encoder-decoder architecture differ from sequence-to-sequence processing?
Model answer
An encoder-decoder processes the complete input sequence before beginning output generation, whereas sequence-to-sequence processing produces outputs while input is still being received.
Explanation
Machine translation is a canonical encoder-decoder use case in the content.
- 140
Why can plain RNNs struggle to retain information from the beginning of a long sequence?
Model answer
Their hidden-state memory is short-term, so information from early inputs can fade as the sequence is processed.
Explanation
This limits a plain RNN's ability to use distant context.
- 141
What extra state distinguishes an LSTM cell from a plain RNN cell?
Model answer
An LSTM maintains both a short-term hidden state and a long-term cell state.
Explanation
The cell state helps preserve information over longer sequences.
- 142
What are the roles of the LSTM forget, input, and output gates?
Model answer
The forget gate removes parts of long-term memory, the input gate selects information to store, and the output gate determines the current output.
Explanation
Gate controllers use the input and hidden state to regulate memory and output.
- 143
How does a GRU differ from an LSTM?
Model answer
A GRU combines long- and short-term memory into one hidden state and does not use an output gate.
Explanation
This makes the GRU a simpler recurrent cell than the LSTM.
- 144
How should a practitioner choose between a plain RNN, LSTM, and GRU?
Model answer
Plain RNNs are less common because of their short-term memory limitation; LSTMs and GRUs are often compared for a task, since GRUs are less complex but relative performance varies by use case.
Explanation
The content recommends trying LSTM and GRU models and comparing results.
- 145
Why does MSE penalize large regression errors more strongly than small ones?
Model answer
It squares each prediction error before averaging, so larger errors contribute disproportionately more to the loss.
Explanation
Squaring also prevents positive and negative errors from canceling.
- 146
What input shape do recurrent layers expect in the described setup?
Model answer
They expect tensors shaped as batch size by sequence length by number of features.
Explanation
For one-feature electricity data, a feature dimension must be added to the batch-and-sequence tensor.
- 147
Why expand a one-feature sequence tensor before passing it to an RNN?
Model answer
The data loader may omit the feature dimension, so reshaping adds the final dimension required by recurrent layers.
Explanation
The expanded shape includes batch size, sequence length, and one feature.
- 148
Why might model outputs need to be squeezed before loss calculation?
Model answer
The model may return outputs shaped as batch size by one while labels have shape batch size; squeezing removes the extra singleton dimension so the shapes match.
Explanation
The loss function requires predictions and targets to have the same shape.
- 149
What is object-oriented programming, and what are attributes and methods?
Model answer
Object-oriented programming organizes programs around objects. Attributes store an object's data, while methods are functions that perform tasks for the object.
Explanation
The bank-account example stores a balance as an attribute and uses a deposit method to change it.
- 150
What does a class's initialization method do in the bank-account example?
Model answer
It runs when an object is created and assigns the supplied balance to the object's balance attribute.
Explanation
The special initialization method receives the object itself and the initial balance.
- 151
What is the purpose of a custom PyTorch dataset's length and item methods?
Model answer
The length method returns the number of samples, and the item method returns the features and label for a requested sample index.
Explanation
These methods let PyTorch and data loaders access the dataset consistently.
- 152
Why does a custom dataset call its parent class's initializer?
Model answer
The parent initializer sets up the inherited dataset behavior needed by the custom dataset.
Explanation
The water dataset example uses this to behave as a PyTorch dataset.
- 153
Why define a PyTorch model as a class rather than only as a sequential model?
Model answer
A class provides more flexibility to customize model behavior as complexity grows, while sequential models can be sufficient for small, simple models.
Explanation
The class can define layers and explicitly describe how inputs flow through them.
- 154
What are the roles of a model class's initialization and forward methods?
Model answer
The initialization method defines the model's layers, while the forward method specifies how an input passes through those layers to produce outputs.
Explanation
Separating layer definition from computation makes model structure explicit.
- 155
How does SGD choose the direction and size of a parameter update?
Model answer
The gradient's sign determines the update direction, while the learning rate determines the update size.
Explanation
For a positive gradient, decreasing the parameter can reduce the loss.
- 156
How does AdaGrad adapt its learning rates, and what data is it suited to?
Model answer
AdaGrad decreases learning rates for parameters that are updated infrequently, making it suitable for sparse data where some features are rarely observed.
Explanation
Its adaptation is intended to account for differences in how often parameters are updated.
- 157
What limitation of AdaGrad is addressed by RMSprop?
Model answer
AdaGrad can reduce learning rates too aggressively; RMSprop adapts each parameter's learning rate based on the size of previous gradients.
Explanation
This approach addresses overly rapid learning-rate decay.
- 158
How does Adam combine ideas from other optimizers?
Model answer
Adam combines RMSprop-style adaptive learning rates with momentum based on a weighted average of past gradients, giving more weight to recent gradients.
Explanation
The combined approach can accelerate training and makes Adam a versatile default choice.
- 159
How are predicted probabilities converted into binary labels during evaluation?
Model answer
Apply a threshold of 0.5: probabilities above it are assigned the positive class, and the others are assigned the negative class.
Explanation
The resulting labels are compared with the true labels to calculate accuracy.
- 160
What are common applications of multi-input models?
Model answer
They can combine multiple views or modalities, compare two inputs to determine whether they represent the same object, or learn representations from paired augmented versions of an input.
Explanation
Examples include comparing passport images and combining image and text information.
- 161
How does the described Omniglot two-input model use its two inputs?
Model answer
It processes the character image and its alphabet one-hot vector separately, concatenates their representations, and classifies the character among 964 classes.
Explanation
The dataset contains characters from 30 alphabets.
- 162
What does tensor concatenation do, and what determines its direction?
Model answer
Concatenation joins tensors along a specified dimension; the chosen dimension determines how their entries are joined.
Explanation
For two-dimensional tensors, the described convention uses dimension 0 for horizontal and dimension 1 for vertical concatenation.
- 163
What kinds of problems can multi-output models address?
Model answer
They can predict multiple tasks from one input, assign multiple labels to an example, or provide extra outputs from intermediate blocks in a deep network.
Explanation
Examples include predicting a car's make and model or identifying both a beach and people in an image.
- 164
Why add auxiliary outputs to intermediate blocks of a deep model?
Model answer
They encourage early parts of the model to learn features useful to the task and can act as a form of regularization.
Explanation
These additional predictions can improve the robustness of the network.
- 165
How does the Omniglot multi-output model predict both a character and its alphabet?
Model answer
It processes the image once to obtain a representation, then sends that representation to separate classifiers for the character and alphabet.
Explanation
The two classifiers have output sizes corresponding to 964 characters and 30 alphabets.
- 166
How are partial losses combined when a model has multiple outputs?
Model answer
The partial losses can be summed, or assigned weights that reflect the relative importance of each task.
Explanation
An unweighted sum treats the tasks as equally important for optimization.
- 167
How can loss weighting express that character classification is twice as important as alphabet classification?
Model answer
Multiply the character-classification loss by two before combining it with the alphabet loss, or use normalized weights that express the same relative emphasis.
Explanation
The weights tell the optimizer which task should have greater influence.
- 168
What problem can occur when combining losses that have very different numerical scales?
Model answer
The larger-magnitude loss can dominate the combined objective, causing the model to effectively ignore the smaller loss.
Explanation
For example, a large-scale MSE loss can overwhelm a single-digit cross-entropy loss.
- 169
How can differently scaled losses be brought to comparable ranges before weighting?
Model answer
The described approach scales each loss by dividing it by the maximum value in the batch.
Explanation
This can make the losses more comparable so that chosen weights can meaningfully balance them.
- 170
Why can joint alphabet and character prediction improve character recognition?
Model answer
Learning to recognize the alphabet can provide information that helps the model recognize individual characters, so solving both tasks can have a combined positive effect.
Explanation
The described results show alphabet prediction as easier, but useful to character prediction.
- 171
What topics are identified as useful foundations for further deep-learning study?
Model answer
Probability, linear algebra, and calculus are identified as useful foundations.
Explanation
These subjects support understanding the mathematics used in deep learning.
- 172
What are transformers and self-supervised learning presented as next steps for study?
Model answer
Transformers are an architecture used in areas including language processing and computer vision, while self-supervised learning trains models to create labels from unlabeled data.
Explanation
The content identifies both as directions for continuing deep-learning study.

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