Book Image

Keras Deep Learning Cookbook

By : Rajdeep Dua, Sujit Pal, Manpreet Singh Ghotra
Book Image

Keras Deep Learning Cookbook

By: Rajdeep Dua, Sujit Pal, Manpreet Singh Ghotra

Overview of this book

Keras has quickly emerged as a popular deep learning library. Written in Python, it allows you to train convolutional as well as recurrent neural networks with speed and accuracy. The Keras Deep Learning Cookbook shows you how to tackle different problems encountered while training efficient deep learning models, with the help of the popular Keras library. Starting with installing and setting up Keras, the book demonstrates how you can perform deep learning with Keras in the TensorFlow. From loading data to fitting and evaluating your model for optimal performance, you will work through a step-by-step process to tackle every possible problem faced while training deep models. You will implement convolutional and recurrent neural networks, adversarial networks, and more with the help of this handy guide. In addition to this, you will learn how to train these models for real-world image and language processing tasks. By the end of this book, you will have a practical, hands-on understanding of how you can leverage the power of Python and Keras to perform effective deep learning
Table of Contents (17 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

Sequence padding


In this recipe, we will learn how Keras can be used for sequence padding. Padding is useful when sequences are sent in batches to the LSTM network. 

Getting ready

Import the function:

from keras.preprocessing.sequence import pad_sequences

pad_sequences is a function defined as follows:

pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncating='pre', value=0.0)

How to do it...

Let's look at the various padding options.

Pre-padding with default 0.0 padding

First, let's look at how to use pad_sequences with default pre-padding:

from keras.preprocessing.sequence import pad_sequences
 # define sequences
 sequences = [
 [1, 2, 3, 4],
 [5, 6, 7],
 [5]
 ]
 # pad sequence
 padded = pad_sequences(sequences)
 print(padded)

An output of the preceding print statement will show all the sequences padded to length 4. 

Post-padding

To pad 0.0 on at the end of shorter arrays, use padding='post', as shown in the following code snippet:

padded_post = pad_sequences(sequences,padding=...