Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Keras Deep Learning Cookbook

You're reading from   Keras Deep Learning Cookbook Over 30 recipes for implementing deep neural networks in Python

Arrow left icon
Product type Paperback
Published in Oct 2018
Publisher Packt
ISBN-13 9781788621755
Length 252 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (3):
Arrow left icon
Sujit Pal Sujit Pal
Author Profile Icon Sujit Pal
Sujit Pal
Manpreet Singh Ghotra Manpreet Singh Ghotra
Author Profile Icon Manpreet Singh Ghotra
Manpreet Singh Ghotra
Rajdeep Dua Rajdeep Dua
Author Profile Icon Rajdeep Dua
Rajdeep Dua
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Keras Installation 2. Working with Keras Datasets and Models FREE CHAPTER 3. Data Preprocessing, Optimization, and Visualization 4. Classification Using Different Keras Layers 5. Implementing Convolutional Neural Networks 6. Generative Adversarial Networks 7. Recurrent Neural Networks 8. Natural Language Processing Using Keras Models 9. Text Summarization Using Keras Models 10. Reinforcement Learning 11. Other Books You May Enjoy

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=...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime