Deep Learning with Keras
- 99Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is Keras, and how is it related to TensorFlow in the setup described?
99 questions
- 1
What is Keras, and how is it related to TensorFlow in the setup described?
Model answer
Keras is a high-level neural network API integrated with TensorFlow. In the described setup, installing TensorFlow also provides Keras.
Explanation
Keras offers a high-level interface for building neural networks, while TensorFlow provides the integrated framework beneath it.
- 2
What was Keras’s historical relationship to lower-level neural network backends, and how did that change?
Model answer
Historically, Keras could run on top of separate backends such as TensorFlow, Theano, or CNTK. It later became integrated with TensorFlow rather than being a separate library that selected among those backends.
Explanation
The earlier arrangement separated the high-level Keras API from the lower-level engines; the described later arrangement integrates Keras with TensorFlow.
- 3
Why is Keras useful for trying out neural network ideas?
Model answer
Keras is designed to enable fast experimentation, allowing users to move from an idea to an implementation in relatively few steps.
Explanation
Its high-level API reduces the amount of implementation work needed to test an idea.
- 4
Why might a neural network practitioner learn more than one neural network API?
Model answer
Once the underlying concepts are understood, the differences in syntax and implementation between APIs are easier to learn. Familiarity with multiple APIs also helps practitioners compare their strengths and suitability for different problems.
Explanation
Knowledge of more than one API supports informed comparisons rather than dependence on a single tool.
- 5
How can TensorFlow be installed from the command line in the setup described?
Model answer
Run
pip install tensorflowfrom the command line.Explanation
Keras is included with the TensorFlow installation in the described setup.
- 6
Is a GPU required to run the neural network examples described, and what is the recommended approach if a machine is not already configured for GPU use?
Model answer
No. The code can run on a CPU, so a learner who is not already set up for GPU use can work with a CPU first.
Explanation
GPU support is optional; the examples are described as running on a CPU as well.
- 7
What is one way to compare CPU and GPU execution after completing a CPU run?
Model answer
If a GPU is available, run the same code on it and compare the execution speed or efficiency with the CPU run.
Explanation
Using the same code on both devices makes their execution performance easier to compare.
- 8
What kinds of neural network implementations can be built or adapted with Keras in the described workflow?
Model answer
A practitioner can build and train networks from scratch or adapt pretrained models through fine-tuning for a custom dataset.
Explanation
The workflow includes both newly constructed networks and pretrained models adapted to new tasks.
- 9
In supervised learning, what are samples and labels?
Model answer
Samples are the individual data points in a dataset, and labels are the corresponding target answers for those data points.
Explanation
A supervised training dataset pairs each input example with a target value or class.
- 10
What alternative terms may be used for samples and labels in deep learning?
Model answer
Samples may be called inputs or input data, while labels may be called targets or target data.
Explanation
These terms refer respectively to the examples supplied to a model and the desired outputs associated with them.
- 11
Give two examples of labels corresponding to samples in supervised learning.
Model answer
For sentiment analysis, a headline might have a positive or negative label; for image classification, an image might be labeled cat or dog.
Explanation
Each label identifies the target category or answer for its corresponding sample.
- 12
Why should the intended task be understood before preparing a dataset?
Model answer
The task determines what the samples and labels represent and what data format is appropriate for passing them to the model.
Explanation
Dataset preparation depends both on the problem being solved and on the model’s input requirements.
- 13
What are the first two arguments expected by the Keras
fitfunction, and what do they represent?Model answer
xrepresents input samples, andyrepresents their corresponding labels or targets.Explanation
The model learns from the examples in
xusing the target answers iny. - 14
Name several data formats that can be accepted for the
xinput tofitin the described setup.Model answer
The input can be a NumPy array, a TensorFlow tensor, a dictionary-like mapping, a
tf.datadataset, or a Keras generator.Explanation
Keras supports multiple input representations; the initial numerical example uses NumPy arrays.
- 15
What format constraint applies to the
ytargets when data is passed tofit?Model answer
ymust use an accepted format and must match the format used forx.Explanation
For example, input samples in a NumPy array should not be paired with labels stored as a TensorFlow tensor in the described setup.
- 16
Besides meeting a model’s input-format requirements, why might data be transformed?
Model answer
Data may be normalized or standardized to make learning easier or more efficient for the model.
Explanation
Data processing can improve the suitability of the values for model training, though the method depends on the data type.
- 17
In the clinical-trial example, what did the two input and output values represent?
Model answer
The input sample was a participant’s age, ranging from 13 to 100, and the label indicated whether that participant experienced side effects.
Explanation
The example pairs numerical ages with binary outcomes.
- 18
How were the binary labels in the clinical-trial example encoded?
Model answer
A label of
1indicated that a participant experienced side effects, while0indicated no side effects.Explanation
The numeric labels encode the two possible outcomes.
- 19
What age-related pattern did the imagined clinical trial report?
Model answer
About 95% of participants aged 65 or older experienced side effects, while about 95% of participants under 65 experienced no side effects.
Explanation
The example uses this age-associated pattern to create a simple classification dataset.
- 20
Why were random ages generated for the clinical-trial dataset, and how were they paired with labels?
Model answer
Random ages were generated within the younger and older age ranges, then appended to the sample list with the corresponding side-effect label appended to the label list.
Explanation
Each age and label were added in corresponding positions so that each sample retained its target.
- 21
Why were the generated samples and labels shuffled together?
Model answer
They were shuffled to remove ordering imposed by the data-generation process while preserving the correspondence between each age and its label.
Explanation
Shuffling only one list would break the pairing between samples and targets.
- 22
How was the age data rescaled in the numerical example, and what range did it use afterward?
Model answer
A min-max scaler transformed the ages from their original range of 13 to 100 to a range between 0 and 1.
Explanation
Min-max scaling changes the numerical scale while retaining the relative ordering of values.
- 23
Why did the one-dimensional age data need to be reshaped before applying the scaler?
Model answer
The scaler’s
fit_transformfunction did not accept the one-dimensional data in its original shape, so the data was reshaped to the required form.Explanation
Reshaping changes the array’s dimensions to satisfy the function’s input requirements.
- 24
What does a Keras sequential model represent?
Model answer
It represents a linear stack of layers, with the output of one layer passed to the next.
Explanation
The sequential model is a straightforward way to create a network whose layers follow a single ordered path.
- 25
In the sequential model example, what creates the input layer, and how does the model learn its shape?
Model answer
The input data defines the input layer implicitly. The model learns the expected input shape from the
input_shapeparameter on the first hidden layer.Explanation
The first explicitly added dense layer is a hidden layer; its input-shape specification tells the model what data to expect.
- 26
What does a dense layer mean in the described neural network?
Model answer
A dense layer is a fully connected layer in which units connect to the preceding layer’s outputs.
Explanation
Dense, fully connected layers are a common layer type in artificial neural networks.
- 27
What do units in a dense layer also commonly get called?
Model answer
Units may also be called nodes or neurons.
Explanation
These terms refer to the computational elements in a layer.
- 28
What roles did the hidden layers and output layer serve in the simple side-effect classifier?
Model answer
The model used hidden dense layers with 16 and 32 units, followed by an output dense layer with two units for the two possible classes.
Explanation
The hidden-layer sizes were chosen arbitrarily in this simple example, while the two output units corresponded to the two outcomes.
- 29
What is the role of the ReLU activation function in the described sequential model?
Model answer
ReLU is applied after a hidden dense layer as its activation function.
Explanation
The model’s layer definitions place ReLU after the hidden dense layers.
- 30
What does the softmax function provide at the output of a multiclass classifier?
Model answer
It provides probabilities for the possible output classes.
Explanation
The class with the highest output probability is the model’s most probable prediction.
- 31
Why was an output layer with two units used for the side-effect classifier?
Model answer
There were two possible classes: the patient experienced side effects or did not experience them.
Explanation
The output units correspond to the possible class outcomes.
- 32
What does the input shape
(224, 224, 3)represent for RGB image input?Model answer
It specifies an image height of 224 pixels, a width of 224 pixels, and three color channels.
Explanation
The three channels correspond to the red, green, and blue components of an RGB image.
- 33
What is the purpose of a convolutional layer in the image-classification network described?
Model answer
A convolutional layer processes image data using filters that move across the image.
Explanation
The example uses
Conv2Dlayers as the main image-processing layers in its CNN. - 34
What do the filter count and kernel size specify in a convolutional layer?
Model answer
The filter count specifies how many filters the layer uses, while the kernel size specifies the spatial dimensions of each filter.
Explanation
The example uses a 3×3 kernel and illustrates filter counts of 32 and 64.
- 35
What does
padding='same'do in the described convolutional layers?Model answer
It adds padding around the image so that the convolution does not reduce the image’s spatial dimensions.
Explanation
The example describes this as zero padding around the outside of the image.
- 36
What is the purpose of a max-pooling layer, and what happens to image dimensions with a 2×2 pool and stride 2?
Model answer
Max pooling reduces the spatial dimensions of feature maps; with a 2×2 pool and stride 2, the image dimensions are halved.
Explanation
The stride determines how far the pooling window moves between operations.
- 37
Why is a flattening operation used before a dense output layer in the described CNN?
Model answer
Flattening converts the multidimensional feature maps into a one-dimensional representation that can be passed to a dense layer.
Explanation
The CNN example flattens the pooled convolutional output before its dense classifier.
- 38
What is the purpose of calling
compilebefore training a Keras model?Model answer
Compilation prepares the model for training by specifying choices such as the optimizer, loss function, and performance metrics.
Explanation
The model is compiled before its
fitfunction is called. - 39
What optimizer and learning rate were used in the numerical example?
Model answer
The example used the Adam optimizer with a learning rate of 0.0001.
Explanation
The optimizer updates model parameters during training, and its learning rate controls the size of those updates.
- 40
What is the purpose of a loss function during model training?
Model answer
The loss function measures how different the model’s predictions are from the target values and provides a quantity for training to reduce.
Explanation
The examples select a loss appropriate to their label format and classification task.
- 41
What does accuracy measure when used as a model metric?
Model answer
Accuracy measures the proportion of predictions that match the true labels.
Explanation
It is used in the examples as a measure of classification performance.
- 42
What do batch size and epochs mean when passed to the
fitfunction?Model answer
Batch size is the number of samples processed together at one time, and an epoch is one complete pass through the training dataset.
Explanation
For example, 30 epochs means that the model processes the full training set 30 times.
- 43
What does setting
shuffle=Trueduring training accomplish?Model answer
It shuffles the training data so the model does not rely on an imposed ordering of the samples.
Explanation
Training data is shuffled by default in the described
fitsetup. - 44
What information does the
verbosesetting control during training?Model answer
It controls how much output is displayed while training runs; a value of 2 gives the most verbose output among the options described.
Explanation
The described options are 0, 1, and 2, with 2 displaying the most output.
- 45
How does a validation set differ from the training set in its use during training?
Model answer
The model learns from the training set but evaluates its predictions on the separate validation set without training on that validation data.
Explanation
Validation results indicate how well the model performs on data it did not use to update its learned parameters.
- 46
What is the purpose of creating a validation set?
Model answer
A validation set helps estimate how well a trained model generalizes to data it did not see during training.
Explanation
The validation metrics can reveal whether good training performance carries over to unseen examples.
- 47
How can Keras create a validation set from the training data during a
fitcall?Model answer
Set the
validation_splitparameter to a fraction between 0 and 1; Keras holds out that fraction of the training data for validation.Explanation
For instance, a split of 0.1 holds out 10% of the training data.
- 48
What ordering issue should be considered when using
validation_split?Model answer
The validation subset is selected before the training data is shuffled, so an ordered dataset may produce an unrepresentative validation set.
Explanation
Shuffling during
fithappens after the validation subset is taken; it does not correct the validation subset’s original selection. - 49
How can training and validation metrics indicate overfitting?
Model answer
If training results are strong but validation results are substantially worse, the model may be overfitting.
Explanation
Overfitting means the model has learned the training data well but does not generalize as well to unseen data.
- 50
What did similar training and validation accuracy in the numerical example indicate?
Model answer
It indicated that the model was generalizing well and was not showing a substantial overfitting problem in that example.
Explanation
The two sets had similar accuracy and loss by the final training epoch.
- 51
What is inference in the context of a trained neural network?
Model answer
Inference is using what a model learned during training to make predictions on data it has not seen before.
Explanation
For example, a classifier trained on cat and dog images can infer a class for a new image.
- 52
Why might a test set be used after training and validation?
Model answer
A test set provides a further evaluation of how well the trained model generalizes before it is deployed.
Explanation
The model is tested on held-out data after training and validation are complete.
- 53
How should test data be prepared in relation to the training data?
Model answer
Test data should be processed in the same format and manner as the training data.
Explanation
Consistent preparation ensures that inputs meet the model’s expected requirements.
- 54
How are predictions obtained from a Keras model in the described workflow?
Model answer
Call the model’s
predictfunction and pass the input samples to it.Explanation
The example also passes a batch size; setting
verboseto 0 suppresses prediction output. - 55
How should a softmax prediction for a two-class example be interpreted?
Model answer
Each output gives the probability assigned to one class; the class with the larger probability is the model’s most probable prediction.
Explanation
In the side-effect example, the zero-index class represents no side effects and the first-index class represents side effects.
- 56
How can the most probable class be selected from a model’s class probabilities?
Model answer
Use an argmax operation to find the index of the largest probability.
Explanation
The resulting index identifies the class with the highest predicted probability.
- 57
Why can’t prediction outputs alone establish test-set accuracy?
Model answer
Predictions alone do not show whether they are correct; they must be compared with the test set’s true labels.
Explanation
Inference may occur without known labels, but evaluation requires target labels for comparison.
- 58
What is a confusion matrix used to show?
Model answer
A confusion matrix compares predicted labels with true labels to show correct and incorrect classifications by class.
Explanation
It gives more detail than a single accuracy score by showing how predictions are distributed across classes.
- 59
How are the rows and columns of the confusion matrix oriented in the described plot?
Model answer
True labels are on the vertical axis, and predicted labels are on the horizontal axis.
Explanation
The plotted axes let each cell show counts for a true-class and predicted-class combination.
- 60
What do the cells along the top-left to bottom-right diagonal of a confusion matrix represent?
Model answer
They represent correct predictions, where the predicted class matches the true class.
Explanation
Off-diagonal cells represent misclassifications between classes.
- 61
How can overall accuracy be calculated from a confusion matrix?
Model answer
Add the counts on the main diagonal and divide by the total number of predictions.
Explanation
The diagonal counts are correct predictions, and the sum of all cells is the total number of predictions.
- 62
What does a confusion matrix reveal that an overall accuracy value may hide?
Model answer
It shows which classes are being predicted correctly or confused with other classes.
Explanation
This class-specific detail can help identify where a model needs improvement.
- 63
What does the
model.savemethod preserve in the described Keras workflow?Model answer
It preserves the model architecture, weights, training configuration such as the loss and optimizer, and the optimizer’s state.
Explanation
Because the saved information includes optimizer state, training can resume from the saved point.
- 64
Why is saving the optimizer state useful when training is interrupted?
Model answer
The saved optimizer state allows training to continue from where it left off after the model is loaded again.
Explanation
The optimizer state is part of the comprehensive information saved by
model.save. - 65
How is a model saved and reloaded using the comprehensive save option?
Model answer
Call
model.savewith a file path, then use the Kerasload_modelfunction with that path.Explanation
The loaded model restores the saved architecture and training-related state.
- 66
What does converting a model to JSON preserve, and what does it omit?
Model answer
It preserves the model architecture as a JSON string but does not preserve the weights or training configuration.
Explanation
A model reconstructed from this architecture needs to be compiled and trained or have weights supplied separately.
- 67
How can a model architecture saved as JSON be reconstructed?
Model answer
Use the
model_from_jsonfunction with the saved JSON string.Explanation
This reconstructs the architecture, not the trained weights or optimizer state.
- 68
What is the YAML alternative to saving and reconstructing a model architecture?
Model answer
Use
model.to_yamlto create a YAML representation andmodel_from_yamlto reconstruct the architecture.Explanation
This offers an architecture-only alternative to the JSON procedure described.
- 69
What does
save_weightspreserve, and what must be done before those weights can be loaded?Model answer
save_weightspreserves only the model’s weights. A model with a compatible architecture must be created before those weights can be loaded into it.Explanation
Weights must match the receiving model’s layer and parameter structure.
- 70
Why must a model used to load saved weights have a compatible architecture?
Model answer
The saved weights must map to the receiving model’s layers and parameter shapes.
Explanation
A model with a different structure may not have matching parameters into which the weights can be placed.
- 71
What are the three dataset partitions used in the described image-classification workflow, and how are they used?
Model answer
The training set is used to learn model parameters, the validation set is used to evaluate performance during training, and the test set is used for a final held-out evaluation.
Explanation
Separating these roles helps assess generalization on data not used to fit the model.
- 72
How were image files organized for the cat-and-dog classification example?
Model answer
Images were placed in class-specific directories inside separate training, validation, and test directories.
Explanation
A directory structure organized by class allows directory iterators to associate images with their labels.
- 73
What is the purpose of a Keras image data generator’s
flow_from_directorymethod?Model answer
It reads images from class-organized directories and provides batches that can be supplied to a model.
Explanation
The method also supports settings such as image size, class names, and batch size.
- 74
Why might images be resized before being passed to a CNN?
Model answer
Resizing makes images conform to a consistent target size that the model expects.
Explanation
In the examples, images were resized to 224×224 pixels.
- 75
Why was shuffling disabled for the image test batches?
Model answer
Keeping the test examples in order preserves their correspondence with the unshuffled true labels for later evaluation.
Explanation
Correct pairing of predictions and labels is necessary for constructing a valid confusion matrix.
- 76
Why can a generator provide both images and labels to
fitwithout a separateyargument?Model answer
The generator contains the labels corresponding to its images, so it supplies both inputs and targets.
Explanation
This differs from passing separate
xandyarrays tofit. - 77
What does one-hot encoding represent for the cat-and-dog image labels?
Model answer
It represents each class with a vector that has a 1 in the class’s position and 0 in the other position.
Explanation
For example, the described setup uses one vector for cat and the other for dog.
- 78
What architecture was used for the first CNN built for cat-and-dog classification?
Model answer
It used convolutional layers followed by max-pooling layers, then a flattening operation and a dense output layer with two class units.
Explanation
The output layer used softmax to produce class probabilities.
- 79
Why might a CNN reach high training accuracy but lower validation accuracy?
Model answer
The model may be overfitting the training data and not generalizing well to unseen examples.
Explanation
The from-scratch cat-and-dog CNN reached very high training accuracy but substantially lower validation accuracy.
- 80
How did the from-scratch CNN’s test performance relate to its validation performance in the example?
Model answer
Its test performance was also relatively weak, consistent with the concern about overfitting raised by its lower validation performance.
Explanation
The confusion matrix provided a class-by-class view of its test predictions.
- 81
What preprocessing did the original VGG16 approach apply to RGB images?
Model answer
It subtracted the training-set mean RGB value from the corresponding color values of each image pixel.
Explanation
The mean was computed for the training set, and the same preprocessing approach must be applied to new inputs to the model.
- 82
Why must incoming images be preprocessed in the same way as a pretrained model’s original training images?
Model answer
The model expects inputs represented in the same way as the data on which it was trained.
Explanation
Applying the model-specific preprocessing helps ensure that new data has a compatible numerical representation.
- 83
What was VGG16 trained to classify originally, and what did the cat-and-dog fine-tuning example change?
Model answer
VGG16 was trained on ImageNet’s 1,000 classes; the example replaced its original output layer with one that classified only cat and dog.
Explanation
Cats and dogs were already present among the original classes, so the adaptation was limited.
- 84
What is fine-tuning in the context of a pretrained model?
Model answer
Fine-tuning adapts a pretrained model to a target task, for example by changing its output layer and training selected parameters on new task data.
Explanation
The described cat-and-dog example mainly retrained a new output layer while keeping earlier parameters fixed.
- 85
Why were the VGG16 layers before the new output layer frozen in the cat-and-dog example?
Model answer
They were frozen to preserve features the pretrained model had already learned, while allowing the new output layer to be trained for the target classes.
Explanation
Only the new output layer’s parameters were trainable in the described adaptation.
- 86
Why did the fine-tuned VGG16 model perform well on cat-and-dog images with little training?
Model answer
The pretrained model had already learned features of cats and dogs from its original training data, so only a small amount of adaptation was needed.
Explanation
The new output layer mapped those existing features to the two target classes.
- 87
What trade-off distinguishes MobileNet from larger models such as VGG16?
Model answer
MobileNet models are smaller and faster, using fewer parameters and less memory, but may sacrifice some accuracy.
Explanation
The content describes the accuracy reduction as relatively small compared with the resource savings.
- 88
Why are MobileNet models considered suitable for mobile devices?
Model answer
Their small size, low power requirements, and low latency make them suitable for devices with limited resources.
Explanation
These properties distinguish MobileNet from larger, more resource-intensive neural networks.
- 89
How does the described MobileNet preprocessing transform RGB pixel values?
Model answer
It scales pixel values from the range 0 to 255 to the range −1 to 1.
Explanation
This is the preprocessing expected by the MobileNet model used in the example.
- 90
What is transfer learning, as illustrated by using MobileNet on sign-language digits?
Model answer
Transfer learning applies knowledge from a model trained on one dataset to a different task or dataset.
Explanation
The example adapts a model trained on ImageNet to classify sign-language digits, which were not part of its original dataset.
- 91
Why did the sign-language digit example use RGB images and organize them into class directories?
Model answer
It used RGB images as the input data and arranged images by digit class so the data-loading process could identify their labels.
Explanation
The dataset contained ten classes, corresponding to the digits 0 through 9.
- 92
How was the sign-language dataset divided in the described example?
Model answer
Thirty images per class were placed in validation, five per class in test, and the remaining images in training.
Explanation
With ten classes, this produced 300 validation images and 50 test images.
- 93
How was MobileNet adapted to output the ten sign-language digit classes?
Model answer
The example retained selected earlier MobileNet layers, added a dense output layer with ten units and softmax activation, and omitted later layers.
Explanation
The ten outputs corresponded to the ten digit classes.
- 94
Why might the number of pretrained layers to retain or freeze be chosen through experimentation?
Model answer
The most effective set of layers to retain or train depends on the target dataset and task, so alternative choices can be tested for performance.
Explanation
The example’s selection of trainable layers was a practical choice rather than a universal rule.
- 95
What is data augmentation?
Model answer
Data augmentation creates modified versions of existing data to expand the examples available for training.
Explanation
For images, modifications can include transformations such as rotation, shifting, zooming, or flipping.
- 96
Name several image transformations that can be used for data augmentation.
Model answer
Images can be rotated, shifted, zoomed, changed in color, or flipped horizontally or vertically.
Explanation
An image data generator can apply selected transformations to create varied versions of existing images.
- 97
How can data augmentation help reduce overfitting?
Model answer
It can increase the variety and amount of training data, making it less likely that a model simply memorizes a small training set.
Explanation
Limited training data can contribute to overfitting, and augmentation can provide additional varied examples.
- 98
How does an image data generator apply augmentation settings to an image?
Model answer
It can generate modified image versions by applying configured transformations, such as rotation, shifts, zooming, channel changes, or flipping.
Explanation
One original image can therefore produce multiple varied training examples.
- 99
Why can flipping or rotating images improve the coverage of a training dataset?
Model answer
It can expose the model to valid orientations or positions that are absent from the original images.
Explanation
For example, augmentation can help a model encounter dogs facing different directions instead of learning from only one orientation.

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