Deep Learning with PyTorch
- 111Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
- spaceFlip card
- KI knew it
- DI didn't know it
- ←Previous card
- →Next card
What is deep learning, and how are deep learning models structured?
Deep learning is a subset of machine learning that uses neural networks made of input, hidden, and output layers.
Or swipe the card
111 cards
What is deep learning, and how are deep learning models structured?
Deep learning is a subset of machine learning that uses neural networks made of input, hidden, and output layers.
Why are deep learning models called neural networks?
Their interconnected units were originally inspired by neurons in the human brain.
Why do deep learning models generally require large datasets?
Their layered structures need substantial data to learn patterns, often at least hundreds of thousands of data points.
What is a PyTorch tensor?
A tensor is PyTorch's fundamental data structure, similar to an array or matrix, that supports mathematical operations.
How can tensors be created from ordinary Python data?
Use PyTorch's tensor class to convert a Python list or NumPy array into a tensor.
How can you inspect a tensor's shape and data type in PyTorch?
Use its
shapeanddtypeattributes.When can two tensors be added or subtracted element by element?
When their shapes match exactly.
What does element-wise multiplication do?
It multiplies corresponding elements of two tensors with the same shape.
How is each value in a matrix product calculated?
Multiply a row of the first matrix by a column of the second matrix element by element, then sum the products.
What does a fully connected linear layer do?
It connects every output neuron to every neuron in the preceding layer and applies a linear operation.
How are the input and output dimensions of a linear layer determined?
The input dimension is the number of input features; the output dimension is the desired number of outputs, such as classes.
What roles do weights and biases play in a neuron?
Weights determine how strongly input features contribute; a bias adds an independent baseline term.
How can multiple linear layers be stacked while keeping dimensions compatible?
Place them in sequence, making each layer's input dimension equal to the preceding layer's output dimension.
How many learnable parameters does one neuron have if it receives N inputs?
N weights and one bias, for a total of N plus one parameters.
How many learnable parameters are in a network whose first layer has four neurons with eight inputs each and whose second layer has two neurons with four inputs each?
Forty-six parameters: thirty-six in the first layer and ten in the second.
What is model capacity, and what is one way to estimate it?
Model capacity is the model's ability to represent complex patterns; total learnable parameter count is one way to assess it.
What is an activation function's role in a neural network?
It introduces non-linearity so the network can learn relationships more complex than linear ones.
What does a forward pass do?
It sends input data through the network's layers to produce predictions.
What kinds of outputs can a forward pass produce?
Binary or multiclass predictions, or numerical predictions for regression.
What does the sigmoid function do, and when is it commonly used?
It maps values to the range from zero to one and is commonly used for binary classification.
What does softmax produce for a multiclass prediction?
A probability distribution over classes, with each value between zero and one and all values summing to one.
What is the relationship between a network of linear layers with sigmoid and logistic regression?
A network using only linear layers and a sigmoid activation behaves like logistic regression.
What does a classification loss function measure?
It measures the discrepancy between a model's prediction and the ground-truth label, returning a numerical loss.
What are the ground truth and model scores in classification?
The ground truth is the correct label; scores are the model's raw predictions, often before softmax.
What is one-hot encoding?
It represents a class label as a vector of zeros with a one at the position of the correct class.
What is cross-entropy loss commonly used for?
Classification, including multiclass classification.
What does a derivative or gradient tell us when minimizing a loss?
It indicates the slope and direction of change of the loss with respect to a quantity.
What is backpropagation?
A procedure that computes loss gradients for model parameters by working backward through the network.
What does calling
backwardon a loss do in PyTorch?It calculates gradients and stores them in the parameters' gradient attributes.
How does gradient descent use a gradient to update a parameter?
It changes the parameter in the direction that reduces loss, with the update scaled by the learning rate.
What is stochastic gradient descent (SGD)?
An optimizer that updates model parameters using gradients, with update size controlled by the learning rate.
What is momentum in an optimizer?
A mechanism that uses information from previous updates to help the optimizer move smoothly and overcome local dips.
What is the effect of setting the learning rate too low or too high?
A rate that is too low makes training slow; a rate that is too high can cause the optimizer to overshoot or bounce around the minimum.
What is an epoch, and what is a batch?
An epoch is one complete pass through the training data; a batch is the subset of samples processed in one iteration.
What does shuffling training data in a data loader do?
It randomizes sample order, typically at each epoch.
What are the typical steps in a PyTorch training iteration?
Clear old gradients, run a forward pass, compute loss, backpropagate, and update parameters with the optimizer.
Why must gradients be cleared before processing a new batch?
PyTorch accumulates gradients by default, so old gradients must be cleared to prevent them from contaminating the new update.
Which loss function is commonly used for regression, and how is it calculated?
Mean squared error (MSE), the mean of the squared differences between predictions and targets.
Why does regression generally use a linear output rather than sigmoid or softmax?
Regression predicts continuous numerical values, so its output should not be restricted to class probabilities.
What are the roles of training, validation, and test sets?
Training data fits model parameters; validation data helps tune hyperparameters; test data evaluates final performance.
How is mean training loss across an epoch calculated?
Sum the loss across training batches and divide by the number of batches.
Why use evaluation mode and disable gradient calculations during validation?
Evaluation mode changes layers that behave differently outside training; disabling gradients avoids unnecessary gradient computation.
What pattern in training and validation loss indicates overfitting?
Training loss keeps decreasing while validation loss begins to rise.
How is accuracy calculated for multiclass predictions?
Choose the class with the highest predicted probability, then compare it with the true class.
Why reset a metric after computing it for an epoch?
To clear its accumulated state before measuring the next epoch.
What is precision?
The fraction of positive predictions that are correct.
What is recall?
The fraction of actual positive examples that the model correctly identifies.
How do micro, macro, and weighted averages differ for multiclass precision or recall?
Micro aggregates counts across classes; macro averages class scores equally; weighted averages class scores according to class size.
When might macro averaging be preferable to micro or weighted averaging?
When performance on smaller classes matters as much as performance on larger ones.
What is a vanishing gradient?
A gradient that becomes extremely small as it propagates backward, leaving earlier layers with ineffective updates.
What is an exploding gradient?
A gradient that grows excessively during backpropagation, causing huge parameter updates and potentially divergent training.
What is dropout, and when is it active?
Dropout randomly deactivates a fraction of neurons during training; it is disabled during evaluation.
What is weight decay?
A regularization method that penalizes large weights to encourage smaller parameters and reduce overfitting.
How can data augmentation help prevent overfitting?
It creates varied training examples from existing data, increasing diversity and helping the model become robust to realistic variations.
What is a key risk when choosing data augmentations?
A transformation may change the apparent class while leaving the original label attached.
What is transfer learning?
Reusing a model trained on one task as a starting point for a different task.
What is fine-tuning, and how can layers be frozen?
Fine-tuning trains a pretrained model on a related task, often with a smaller learning rate; freezing prevents selected parameters from updating.
What is a practical sequence for developing a deep-learning model?
Verify the task on one example, make a model overfit the training data, then reduce overfitting and tune hyperparameters.
How do grid search and random search tune hyperparameters?
Grid search tests predefined combinations; random search samples combinations from ranges.
What is object-oriented programming (OOP)?
A programming approach that organizes code into objects with attributes (data) and methods (functions).
What does a class's initialization method do?
It runs when an object is created and can assign values to that object's attributes.
What are the essential methods in a custom PyTorch dataset?
An initialization method, a method returning dataset length, and an item-retrieval method.
What is the purpose of
TensorDataset?It groups feature and target tensors into a dataset whose samples can be indexed together.
What does a PyTorch
DataLoaderprovide?An iterable that serves dataset samples in batches and can shuffle their order.
Why define a PyTorch model as a class instead of only using a sequential container?
A class provides greater flexibility for customizing model structure and computation as complexity grows.
What are the roles of a model's initialization method and
forwardmethod?Initialization defines and stores layers;
forwardspecifies how inputs pass through them.What is the purpose of saving and loading model weights?
It allows learned parameters to be preserved and reused, such as when starting a transfer-learning task.
What are useful steps for addressing unstable gradients?
Use suitable weight initialization, appropriate activation functions, and batch normalization.
What is the goal of variance-aware weight initialization?
To keep the variance of layer inputs and outputs, and of gradients before and after a layer, appropriately balanced.
What is the dying-neuron problem with ReLU, and how can ELU help?
ReLU neurons can stop learning when they continually receive negative inputs; ELU has nonzero gradients for negative inputs.
How does batch normalization work?
It normalizes layer outputs using their mean and standard deviation, then learns scale and shift parameters.
What are the roles of AdaGrad, RMSprop, and Adam?
AdaGrad reduces learning rates for infrequently updated parameters; RMSprop adapts rates using recent gradient magnitudes; Adam combines adaptive updates with momentum.
What is a digital image made of, and how are its colors represented?
An image is made of pixels; grayscale pixels encode shades from black to white, while color pixels commonly encode red, green, and blue intensities.
What does a standard color-image tensor contain?
A batch dimension, three color channels, image height, and image width.
Why resize images when preparing them for a model?
Resizing makes images a consistent size so they can be processed together.
Why might an image tensor need its dimensions rearranged for display?
Plotting tools commonly expect height and width before the channel dimension, unlike many model inputs.
Why are convolutional layers often preferable to dense layers for images?
Convolutions use fewer parameters and detect spatial patterns across image locations.
What is a convolutional filter, and what is a feature map?
A filter is a small grid of learned parameters that slides over an input; the resulting values form a feature map.
How does a convolution calculate one output value?
It multiplies corresponding values in the input patch and filter, then sums the products.
What is zero padding in a convolutional layer?
Adding zeros around the input before convolution.
How does max pooling work, and what is its effect?
It takes the maximum value in each window and passes it forward, reducing feature-map spatial dimensions.
What are the two main parts of a convolutional image classifier?
A feature extractor and a classifier.
How can the input size of a CNN's final linear layer be determined?
Track the feature-map channels, height, and width after each convolution and pooling operation, then flatten their product.
Why should test images generally not receive random training augmentations?
Evaluation should measure predictions on the intended test images, not unpredictable altered versions.
What makes an image augmentation appropriate for a classification task?
It should create realistic variation without changing the image's correct class label.
What is sequential data?
Data ordered in time or space where order and dependencies between elements matter.
Why should sequential data often be split by time rather than randomly?
A random split can create lookahead bias by letting training include information from after test examples.
What is a sequence length in sequence forecasting?
The number of consecutive data points used as one model input example.
How are training examples created for next-step sequence forecasting?
Use a window of consecutive observations as the input and the observation immediately after it as the target.
How do recurrent neural networks differ from feedforward networks?
RNNs pass a hidden state from one time step to the next, allowing information from earlier inputs to influence later outputs.
What do the hidden state and output of an RNN represent?
The hidden state carries information forward through time; the output is the prediction produced at a time step.
What are the four common input-output patterns for recurrent architectures?
Sequence-to-sequence, sequence-to-vector, vector-to-sequence, and encoder-decoder.
What is a sequence-to-sequence RNN architecture suited for?
Tasks that produce an output at every time step of an input sequence.
What is a sequence-to-vector architecture suited for?
Tasks where the model reads a whole input sequence and uses its final output for one prediction.
What is a vector-to-sequence architecture suited for?
Generating a sequence from a single input vector.
How does an encoder-decoder architecture differ from sequence-to-sequence?
An encoder-decoder processes the input sequence before starting output generation; sequence-to-sequence can generate outputs while inputs are still arriving.
What is the short-term memory limitation of a plain RNN?
Its hidden state may lose useful information from the beginning of a long sequence.
How does an LSTM cell handle memory?
It maintains a short-term hidden state and a long-term cell state, using gates to control what to forget, store, and output.
How does a GRU differ from an LSTM?
A GRU is simpler, combines memory into one hidden state, and does not use a separate output gate.
What input shape do recurrent layers expect, and why might a feature dimension need to be added?
They expect batch size, sequence length, and number of features; a univariate series needs an explicit feature dimension.
Why might model outputs need to be squeezed during sequence regression evaluation?
To make their shape match the target labels before passing both to a loss or metric.
What is a multi-input model?
A model that receives more than one source of input data.
What are examples of applications for multi-input models?
Combining multiple images, combining different modalities, comparing two inputs, or matching augmented versions of an input.
How is a two-input image-and-alphabet classifier organized?
Process the image and alphabet vector separately, concatenate their representations, and pass the result to a classifier.
What does tensor concatenation do?
It joins tensors along a specified dimension.
What is a multi-output model?
A model that produces multiple predictions from the same input.
Why might a deep model use additional outputs after intermediate blocks?
They encourage earlier layers to learn task-relevant features and can act as regularization.
How can a model predict both an image's character and its alphabet?
Use a shared image-processing subnetwork followed by separate classifier layers for character and alphabet.
How is a multi-output model's training loss formed?
Calculate a loss for each output and combine the losses into one objective for the optimizer.
Why should loss magnitudes be considered before weighting multiple losses?
A much larger loss can dominate the combined objective and cause the model to neglect a smaller loss.
How can a multi-output model be evaluated?
Track a separate metric for each output and compute each metric over the evaluation data.

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