1. Home
  2. Explore
  3. Computer Science
  4. Deep Learning with Keras

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Deep Learning with Keras

Speaker 1Speaker 2

Deep Learning with Keras

18:39
0:00-18:39
  1. Simon

    Welcome to our introduction to deep learning with Keras. The course teaches Keras, a neural-network API written in Python and integrated with TensorFlow. Each lesson introduces a deep-learning idea and then demonstrates it in code, moving from preparing data to building and training networks.

  2. Corey

    And the course doesn’t stop at networks built from scratch. It also introduces pretrained, state-of-the-art models that learners can fine-tune for their own datasets. The emphasis is on understanding the workflow and implementing it with the Keras API.

  3. Simon

    For background knowledge, the lessons briefly introduce the concepts they use. If you’re completely new to deep learning, the course recommends studying deep-learning fundamentals first—or taking that course alongside this one. For coding, basic programming and some Python experience are enough.

  4. Corey

    There are learning resources beyond the videos, too: each episode has a corresponding blog post and quiz, and learners can contribute quiz questions. Course code is maintained and updated, while downloadable code files are available to members of the Deep Lizard Hive Mind. The site also has a deep-learning learning path showing where the Keras course fits.

  5. Simon

    Why learn Keras? It was designed to make experimentation fast, helping you move from an idea to an implementation in relatively few steps. But the broader advice is not to commit to just one neural-network API forever. Once you understand the underlying concepts, learning another API’s syntax and implementation differences is easier—and knowing multiple APIs can help you compare which ones suit different problems.

  6. Corey

    There’s also an important historical detail. Keras used to be a high-level API that could run on different backends, including TensorFlow, Theano, and CNTK. It later became integrated with TensorFlow, so the course uses Keras through TensorFlow and focuses mainly on the high-level Keras interface.

  7. Simon

    Installation follows from that integration: installing TensorFlow packages Keras with it. The course gives the command `pip install tensorflow`, while recommending that learners check TensorFlow’s system requirements to confirm their machine is compatible.

  8. Corey

    A GPU is optional. The course code works on a CPU, so there’s no need to delay learning if your computer isn’t set up for GPU use. If you do want GPU support, the course points to a TensorFlow setup guide; one suggested approach is to complete the course on CPU first, then configure the GPU and compare the speed.

  9. Simon

    Let’s start the hands-on work with the basic ingredients of supervised learning: samples and labels. Samples are the data points—such as headlines or images—and labels are their corresponding targets. A headline might be labeled positive or negative; an image might be labeled cat or dog. You may also hear samples called inputs and labels called targets.

  10. Corey

    The model’s expected data format matters. For a Keras Sequential model, training data is passed to `fit`, whose main inputs are `x` and `y`: `x` is the sample data and `y` is its labels. The documentation allows several formats, including NumPy arrays, TensorFlow tensors, dictionaries, datasets, and Keras generators. In the first numerical example, both inputs and labels are NumPy arrays, and they need to use matching formats.

  11. Simon

    The course’s first dataset is deliberately simple and made up for teaching. Imagine a clinical trial of a drug with 2,100 participants, ages 13 to 100. Half are under 65 and half are 65 or older. About 95 percent of the older group experience side effects, while about 95 percent of the younger group do not.

  12. Corey

    The two lists represent that setup: `train_samples` holds participant ages, and `train_labels` holds the matching outcomes. A label of one means side effects; zero means no side effects. The code generates the exceptional five-percent groups as well as the larger groups, then prints the lists to check that they contain ages and zero-or-one labels.

  13. Simon

    Next, both lists are converted to NumPy arrays and shuffled together so each age remains paired with its correct label. The ages are then rescaled with a MinMaxScaler from their original range of 13 to 100 into a range from zero to one. Because the samples are one-dimensional, they’re reshaped to the form the scaler’s transformation function expects.

  14. Corey

    That distinction is worth remembering: preparing data is not only about matching the model’s input format. Scaling or normalizing data can also make it easier or more efficient for a model to learn from. The right processing depends on the data type, and the course starts with numbers before moving on to images.

  15. Simon

    With data ready, the first network is built using Keras’s Sequential model. Think of Sequential as a linear stack of layers. The input layer is implicit: the input data supplies it, and the first Dense layer’s `input_shape` tells the model what shape to expect.

  16. Corey

    The example has two hidden Dense layers, with 16 units in the first and 32 in the next, each followed by a ReLU activation. Those unit counts are arbitrary choices for this simple demonstration. The output Dense layer has two units, one for each outcome, and a softmax activation produces a probability for each class.

  17. Simon

    A Dense layer is also known as a fully connected layer. After creating the model, `model.summary()` gives a view of its architecture. That summary is a useful way to check that the layers you intended to build are actually there.

  18. Corey

    Before training, the model is compiled. Compilation configures what training needs: the example uses the Adam optimizer with a learning rate of 0.0001, sparse categorical cross-entropy loss, and accuracy as its performance metric.

  19. Simon

    Then `fit` trains the network. It receives the scaled samples as `x` and labels as `y`; the example uses batches of 10 and runs for 30 epochs. A batch is the number of samples processed together, while an epoch means the model has trained on the full dataset once. The data is shuffled during training by default.

  20. Corey

    In that demonstration, accuracy rises from about 50 percent at the beginning to roughly 94 percent by the final epoch, while loss decreases. It’s a simple dataset and a simple model, but it shows how little code is needed to get a first training run working.

  21. Simon

    Training scores alone don’t tell us whether a model will work on data it hasn’t seen. That’s why the course introduces a validation set: a portion of the data held aside from training. The model learns from the training set, then each epoch evaluates its predictions on the validation set.

  22. Corey

    Validation data is not used to update the model during training. It gives us a view of generalization—how well the model handles data outside the training examples. If training performance is strong but validation performance is much worse, that suggests overfitting: the model has learned the training data too specifically.

  23. Simon

    One way to provide validation data is to create a separate set and pass it to `fit` as `validation_data`. Another is to set `validation_split` to a fraction, such as 0.1 for ten percent, and let Keras set that portion aside while fitting.

  24. Corey

    There’s a subtle ordering issue with `validation_split`: Keras takes the validation portion before it shuffles the training data. So if the data has an imposed order, the held-out final portion may not represent a shuffled sample. Shuffle the data before passing it to `fit` when that matters. In the example, training and validation accuracy end up close together, suggesting the model generalizes similarly to both sets.

  25. Simon

    A test set provides another check. Inference means using a trained model to make predictions on data it hasn’t seen during training. A test set is held out for this purpose, often after training and validation, to assess the model before deploying it.

  26. Corey

    The test data should be prepared in the same way as the training data—in this example, it’s generated, converted to arrays, shuffled, and scaled to the zero-to-one range. Then `model.predict` receives the test samples and returns predictions. With the two-class model, each prediction gives probabilities for the two labels; taking the index of the highest probability gives the predicted class.

  27. Simon

    Predictions alone don’t tell us how accurate the model was if we don’t compare them with the correct labels. When those labels are available, a confusion matrix gives a visual comparison between predicted and true classes. The example uses scikit-learn to build and plot one.

  28. Corey

    In the confusion matrix, the diagonal from top left to bottom right shows correct predictions; off-diagonal entries are errors. For the numerical example, 396 of 420 predictions are correct, about 94 percent. The matrix also shows which kinds of mistakes the model made, not just the overall accuracy.

  29. Simon

    The course next covers saving and loading a Sequential model in three ways. The most complete option is `model.save`. It stores the architecture, weights, training configuration such as the loss and optimizer, and the optimizer state. Saving that state can let you load the model later and resume training where you left off.

  30. Corey

    A saved model can be restored with `load_model`. A second option is saving only the architecture as JSON, then rebuilding it with `model_from_json`; the YAML equivalents are also mentioned. An architecture-only model does not contain trained weights or training configuration, so you’d need to supply those separately.

  31. Simon

    The third option is `save_weights`, which stores only the weights. To load them later, first create a model with a compatible architecture, then call `load_weights`. The important contrast is that a full save captures the whole training setup, while architecture-only and weights-only saves capture just the parts their names imply.

  32. Corey

    Now the course moves from numerical data to images and convolutional neural networks, or CNNs. The goal is to classify cats and dogs using the Kaggle cats-versus-dogs dataset. The initial file preparation is partly manual: extract the training archive, arrange the images in a usable training directory, and place the data where the notebook can find it.

  33. Simon

    The code then makes `train`, `valid`, and `test` directories, each with `cat` and `dog` subdirectories. Rather than use all 25,000 images, the demonstration selects a smaller balanced subset: 500 cats and 500 dogs for training, 100 of each for validation, and 50 of each for testing. The remaining images are not needed for the examples.

  34. Corey

    Keras’s `ImageDataGenerator.flow_from_directory` creates batches from those folders. The iterators resize images to 224 by 224, use a batch size of 10, and identify the two classes from the directory names. The example also applies VGG 16’s preprocessing function, a detail that will matter when we discuss that pretrained model.

  35. Simon

    For training and validation, the data is shuffled. The test iterator is not shuffled, so its samples remain aligned with their class labels for later evaluation. A plotted batch shows the images and their one-hot labels: one-zero for cat, zero-one for dog. The preprocessing makes the colors look unusual, but the images remain identifiable.

  36. Corey

    The first CNN is another Sequential model. It starts with a two-dimensional convolutional layer using 32 filters and a three-by-three kernel, followed by ReLU and same padding. The input shape is 224 by 224 with three color channels, because the images are RGB.

  37. Simon

    A two-by-two max-pooling layer follows, then another convolution with 64 filters and another max-pooling layer. The result is flattened and passed to a Dense output layer with two units and softmax. The filter choices are examples; the model summary shows the output shapes and parameter counts.

  38. Corey

    The CNN is compiled with Adam, a 0.0001 learning rate, categorical cross-entropy, and accuracy. Because the data comes from generators that already include labels, `fit` can take the training and validation generators without a separate `y` argument.

  39. Simon

    After ten epochs, the scratch-built CNN reaches 100 percent training accuracy but only about 69 percent validation accuracy. That gap is a warning sign for overfitting: strong performance on the examples used to learn, but poorer generalization to held-out examples.

  40. Corey

    The course still demonstrates inference with this model. It predicts on the unshuffled test batches, then compares predicted classes with the corresponding test labels in a confusion matrix. The matrix makes the test errors visible and confirms that the model’s generalization is not as strong as its training score suggested.

  41. Simon

    To improve on the scratch model, the course introduces VGG 16, a pretrained model that won the 2014 ImageNet competition. ImageNet contains many images across 1,000 classes, including cats and dogs. Since VGG 16 has already learned features useful for those classes, only modest fine-tuning is needed for this example.

  42. Corey

    VGG 16 also explains the earlier color changes. Its original preprocessing subtracts the training set’s mean red, green, and blue values from the corresponding pixel values. New images must be processed in the same way, and Keras provides a VGG 16 preprocessing function for that.

  43. Simon

    To adapt the model, the example removes VGG 16’s 1,000-class output layer and adds a two-class output for cats and dogs. The earlier layers are frozen, so their learned weights are not retrained; only the new output layer is trainable. The model summary shows the large original network but only about 8,000 trainable parameters in the adapted version.

  44. Corey

    After compiling it in the same way and training for five epochs, the fine-tuned model reaches about 99 percent training accuracy and 98 percent validation accuracy. On the held-out test set, its confusion matrix shows 96 correct predictions out of 100. That’s much stronger generalization than the scratch-built CNN achieved in this example.

  45. Simon

    Next comes MobileNet, a family of lightweight convolutional networks intended for tasks such as classification and detection. Their relatively small size makes them useful to consider for mobile devices. The course contrasts a roughly 553-megabyte VGG 16 model, with about 138 million parameters, with a MobileNet version around 17 megabytes and 4.2 million parameters.

  46. Corey

    Smaller models also use fewer resources, including memory, but there is a trade-off: MobileNets may be somewhat less accurate than larger models such as VGG 16. The course emphasizes that the accuracy reduction can be relatively small, and demonstrates loading MobileNet through Keras.

  47. Simon

    For a quick check, the course prepares sample images by resizing them to 224 by 224, converting them to arrays, expanding their dimensions, and applying MobileNet’s preprocessing. That preprocessing scales pixel values from zero-to-255 onto a minus-one-to-one range.

  48. Corey

    MobileNet’s predictions are decoded into the top five ImageNet classes. For a lizard image, the leading guesses are lizard categories; for a coffee image, espresso is predicted with 99 percent probability; and for a strawberry image, strawberry is predicted with nearly 100 percent probability. These examples demonstrate inference with a pretrained model, not fine-tuning it yet.

  49. Simon

    The next task is fine-tuning MobileNet on a new custom dataset: sign-language digits from zero through nine. Unlike the cat-and-dog images, these classes were not part of the original ImageNet task. The dataset is available as grayscale images in one source and RGB images in another; the course uses the RGB version.

  50. Corey

    The images are organized into class folders labeled zero through nine, then split into `train`, `valid`, and `test` directories. The script makes the training folders and moves the class images into them, then samples 30 images per class for validation and five per class for testing. The result is 1,712 training images, 300 validation images, and 50 test images across ten classes.

  51. Simon

    As before, directory iterators resize images to 224 by 224 and apply the MobileNet preprocessing function. Training and validation batches are shuffled, while test batches are not, preserving the alignment needed to compare predictions with true labels.

  52. Corey

    For fine-tuning, the example keeps MobileNet’s layers up to the sixth-to-last layer, adds a new Dense output with ten units and softmax, and connects the result using Keras’s functional API. It freezes most layers but leaves the last 23 trainable. That number is an experimental choice, not a universal rule; the course encourages trying alternatives.

  53. Simon

    The adapted MobileNet is compiled with Adam, categorical cross-entropy, and accuracy, then trained for 30 epochs. It reaches 100 percent training accuracy and about 92 percent validation accuracy. The test confusion matrix shows 45 correct predictions out of 50, or 90 percent.

  54. Corey

    That example illustrates transfer learning: using what a model learned on its original data for a different task. The MobileNet layers provide learned features, while fine-tuning updates selected layers and the new output layer for sign-language digits. The training and test results are useful, but the remaining gap also shows why experimentation with the fine-tuning setup can matter.

  55. Simon

    Finally, the course introduces image data augmentation: creating modified versions of existing data. Image examples include flipping, rotating, shifting, zooming, or changing color. A Keras image data generator can apply combinations of these transformations.

  56. Corey

    Why augment? It can help when there isn’t much training data and can expand the variety of examples available to the model. A broader training set can also help reduce overfitting. The course plots one dog image alongside augmented versions, making transformations like shifts, rotations, and flips easy to spot.

  57. Simon

    The key is that augmentation creates variations of existing examples; it doesn’t change the basic goal of the task. The episode points learners to the generator documentation for parameter details and to the blog for instructions on saving augmented images if they want to add them to a training set.

  58. Corey

    So the course has taken us from choosing and preparing samples, through Sequential models, training, validation, inference, and evaluation, into CNNs and pretrained models. It also introduced model saving, transfer learning, MobileNet, and image augmentation. The recurring lesson is to match the data to the model, measure performance on held-out data, and use tools like summaries and confusion matrices to understand what the model is doing.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent