Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Deep Learning for Time Series Cookbook
Deep Learning for Time Series Cookbook

Deep Learning for Time Series Cookbook: Use PyTorch and Python recipes for forecasting, classification, and anomaly detection

Arrow left icon
Profile Icon Cerqueira Profile Icon Luís Roque
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (9 Ratings)
Paperback Mar 2024 274 pages 1st Edition
eBook
$27.98 $39.99
Paperback
$49.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Cerqueira Profile Icon Luís Roque
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (9 Ratings)
Paperback Mar 2024 274 pages 1st Edition
eBook
$27.98 $39.99
Paperback
$49.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$27.98 $39.99
Paperback
$49.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Deep Learning for Time Series Cookbook

Getting Started with PyTorch

In this chapter, we’ll explore PyTorch, a leading deep learning library in Python.

We go over several operations that are useful for understanding how neural networks are built using PyTorch. Besides tensor operations, we will also explore how to train different types of neural networks. Specifically, we will focus on feedforward, recurrent, long short-term memory (LSTM), and 1D convolutional networks.

In later chapters, we will also cover other types of neural networks, such as transformers. Here, we will use synthetic data for demonstrative purposes, which will help us showcase both the implementation and theory behind each model.

Upon completing this chapter, you will have gained a robust understanding of PyTorch, equipping you with the tools for more advanced deep learning projects.

In this chapter, we will cover the following recipes:

  • Installing PyTorch
  • Basic operations in PyTorch
  • Advanced operations in PyTorch
  • ...

Technical requirements

Before starting, you will need to ensure that your system meets the following technical requirements:

  • Python 3.9: You can download Python from https://www.python.org/downloads/.
  • pip (23.3.1) or Anaconda: These are popular package managers for Python. pip comes with Python by default. Anaconda can be downloaded from https://www.anaconda.com/products/distribution.
  • torch (2.2.0): The main library we will be using for deep learning in this chapter.
  • CUDA (optional): If you have a CUDA-capable GPU on your machine, you can install a version of PyTorch that supports CUDA. This will enable computations on your GPU and can significantly speed up your deep learning experiments.

It’s worth noting that the code presented in this chapter is platform-independent and should run on any system with the preceding requirements satisfied.

The code for this chapter can be found at the following GitHub URL: https://github.com/PacktPublishing/Deep...

Installing PyTorch

To start with PyTorch, we need to install it first. As of the time of writing, PyTorch supports Linux, macOS, and Windows platforms. Here, we will guide you through the installation process on these operating systems.

Getting ready

PyTorch is usually installed via pip or Anaconda. We recommend creating a new Python environment before installing the library, especially if you will be working on multiple Python projects on your system. This is to prevent any conflicts between different versions of Python libraries that different projects may require.

How to do it…

Let’s see how to install PyTorch. We’ll describe how to do this using either pip or Anaconda. We’ll also provide some information about how to use a CUDA environment.

If you’re using pip, Python’s package manager, you can install PyTorch by running the following command in your terminal:

pip install torch

With the Anaconda Python distribution,...

Basic operations in PyTorch

Before we start building neural networks with PyTorch, it is essential to understand the basics of how to manipulate data using this library. In PyTorch, the fundamental unit of data is the tensor, a generalization of matrices to an arbitrary number of dimensions (also known as a multidimensional array).

Getting ready

A tensor can be a number (a 0D tensor), a vector (a 1D tensor), a matrix (a 2D tensor), or any multi-dimensional data (a 3D tensor, a 4D tensor, and so on). PyTorch provides various functions to create and manipulate tensors.

How to do it…

Let’s start by importing PyTorch:

import torch

We can create a tensor in PyTorch using various techniques. Let’s start by creating tensors from lists:

t1 = torch.tensor([1, 2, 3])
print(t1)
t2 = torch.tensor([[1, 2], [3, 4]])
print(t2)

PyTorch can seamlessly integrate with NumPy, allowing for easy tensor creation from NumPy arrays:

import numpy as np
np_array...

Advanced operations in PyTorch

After exploring basic tensor operations, let’s now dive into more advanced operations in PyTorch, specifically the linear algebra operations that form the backbone of most numerical computations in deep learning.

Getting ready

Linear algebra is a subset of mathematics. It deals with vectors, vector spaces, and linear transformations between these spaces, such as rotations, scaling, and shearing. In the context of deep learning, we deal with high-dimensional vectors (tensors), and operations on these vectors play a crucial role in the internal workings of models.

How to do it…

Let’s start by revisiting the tensors we created in the previous section:

print(t1)
print(t2)

The dot product of two vectors is a scalar that measures the vectors’ direction and magnitude. In PyTorch, we can calculate the dot product of two 1D tensors using the torch.dot() function:

dot_product = torch.dot(t1, t3)
print(dot_product...

Building a simple neural network with PyTorch

This section will build a simple two-layer neural network from scratch using only basic tensor operations to solve a time series prediction problem. We aim to demonstrate how one might manually implement a feedforward pass, backpropagation, and optimization steps without leveraging PyTorch’s predefined layers and optimization routines.

Getting ready

We use synthetic data for this demonstration. Suppose we have a simple time series data of 100 samples, each with 10 time steps. Our task is to predict the next time step based on the previous ones:

X = torch.randn(100, 10)
y = torch.randn(100, 1)

Now, let’s create a neural network.

How to do it…

Let’s start by defining our model parameters and their initial values. Here, we are creating a simple two-layer network, so we have two sets of weights and biases:

We use the requires_grad_() function to tell PyTorch that we want to compute gradients with...

Training a feedforward neural network

This recipe walks you through the process of building a feedforward neural network using PyTorch.

Getting ready

Feedforward neural networks, also known as multilayer perceptrons (MLPs), are one of the simplest types of artificial neural networks. The data flows from the input layer to the output layer, passing through hidden layers without any loop. In this type of neural network, all hidden units in one layer are connected to the units of the following layer.

How to do it…

Let’s create a simple feedforward neural network using PyTorch. First, we need to import the necessary PyTorch modules:

import torch
import torch.nn as nn

Now, we can define a simple feedforward neural network with one hidden layer:

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(10...

Training a recurrent neural network

Recurrent Neural Networks (RNNs) are a class of neural networks that are especially effective for tasks involving sequential data, such as time series forecasting and natural language processing.

Getting ready

RNNs use sequential information by having hidden layers capable of passing information from one step in the sequence to the next.

How to do it…

Similar to the feedforward network, we begin by defining our RNN class. For simplicity, let’s define a single-layer RNN:

class RNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(RNN, self).__init__()
        self.hidden_size = hidden_size
        self.rnn = nn.RNN(input_size, hidden_size, batch_first=True)
        self.fc = nn.Linear(hidden_size, output_size...

Training an LSTM neural network

RNNs suffer from a fundamental problem of “vanishing gradients” where, due to the nature of backpropagation in neural networks, the influence of earlier inputs on the overall error diminishes drastically as the sequence gets longer. This is especially problematic in sequence processing tasks where long-term dependencies exist (i.e., future outputs depend on much earlier inputs).

Getting ready

LSTM networks were introduced to overcome this problem. They use a more complex internal structure for each of their cells compared to RNNs. Specifically, an LSTM has the ability to decide which information to discard or to store based on an internal structure called a cell. This cell uses gates (input, forget, and output gates) to control the flow of information into and out of the cell. This helps maintain and manipulate the “long-term” information, thereby mitigating the vanishing gradient problem.

How to do it…

...

Training a convolutional neural network

Convolutional neural networks (CNNs) are a class of neural networks particularly effective for tasks involving grid-like input data such as images, audio spectrograms, and even certain types of time series data.

Getting ready

The central idea of CNNs is to apply a convolution operation on the input data with convolutional filters (also known as kernels), which slide over the input data to produce output feature maps.

How to do it…

For simplicity, let’s define a single-layer 1D convolutional neural network, which is particularly suited for time series and sequence data. In PyTorch, we can use the nn.Conv1d layer for this:

class ConvNet(nn.Module):
    def __init__(self,
        input_size,
        hidden_size,
        output_size,
        ...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn the fundamentals of time series analysis and how to model time series data using deep learning
  • Explore the world of deep learning with PyTorch and build advanced deep neural networks
  • Gain expertise in tackling time series problems, from forecasting future trends to classifying patterns and anomaly detection
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Most organizations exhibit a time-dependent structure in their processes, including fields such as finance. By leveraging time series analysis and forecasting, these organizations can make informed decisions and optimize their performance. Accurate forecasts help reduce uncertainty and enable better planning of operations. Unlike traditional approaches to forecasting, deep learning can process large amounts of data and help derive complex patterns. Despite its increasing relevance, getting the most out of deep learning requires significant technical expertise. This book guides you through applying deep learning to time series data with the help of easy-to-follow code recipes. You’ll cover time series problems, such as forecasting, anomaly detection, and classification. This deep learning book will also show you how to solve these problems using different deep neural network architectures, including convolutional neural networks (CNNs) or transformers. As you progress, you’ll use PyTorch, a popular deep learning framework based on Python to build production-ready prediction solutions. By the end of this book, you'll have learned how to solve different time series tasks with deep learning using the PyTorch ecosystem.

Who is this book for?

If you’re a machine learning enthusiast or someone who wants to learn more about building forecasting applications using deep learning, this book is for you. Basic knowledge of Python programming and machine learning is required to get the most out of this book.

What you will learn

  • Grasp the core of time series analysis and unleash its power using Python
  • Understand PyTorch and how to use it to build deep learning models
  • Discover how to transform a time series for training transformers
  • Understand how to deal with various time series characteristics
  • Tackle forecasting problems, involving univariate or multivariate data
  • Master time series classification with residual and convolutional neural networks
  • Get up to speed with solving time series anomaly detection problems using autoencoders and generative adversarial networks (GANs)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 29, 2024
Length: 274 pages
Edition : 1st
Language : English
ISBN-13 : 9781805129233
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Mar 29, 2024
Length: 274 pages
Edition : 1st
Language : English
ISBN-13 : 9781805129233
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 151.97
Bayesian Analysis with Python
$49.99
Mastering PyTorch
$51.99
Deep Learning for Time Series Cookbook
$49.99
Total $ 151.97 Stars icon

Table of Contents

11 Chapters
Chapter 1: Getting Started with Time Series Chevron down icon Chevron up icon
Chapter 2: Getting Started with PyTorch Chevron down icon Chevron up icon
Chapter 3: Univariate Time Series Forecasting Chevron down icon Chevron up icon
Chapter 4: Forecasting with PyTorch Lightning Chevron down icon Chevron up icon
Chapter 5: Global Forecasting Models Chevron down icon Chevron up icon
Chapter 6: Advanced Deep Learning Architectures for Time Series Forecasting Chevron down icon Chevron up icon
Chapter 7: Probabilistic Time Series Forecasting Chevron down icon Chevron up icon
Chapter 8: Deep Learning for Time Series Classification Chevron down icon Chevron up icon
Chapter 9: Deep Learning for Time Series Anomaly Detection Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(9 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Amazon Customer May 06, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
"Deep Learning for Time Series Cookbook" by Vitor Cerqueira and Luís Roque is a comprehensive guide for those interested in forecasting, classification, and anomaly detection in time series data. The book caters to readers with a basic knowledge of Python and machine learning, offering practical code snippets to reinforce learning. Each chapter covers essential concepts progressively, from basic time series fundamentals to advanced techniques like N-BEATS and Temporal Fusion Transformers. Topics include univariate and multivariate forecasting, hyperparameter optimization, time series classification using various models, and anomaly detection using autoencoders and generative adversarial networks.Overall, this book is a valuable resource for anyone embarking on their time series modeling journey, providing a blend of theoretical explanations and hands-on examples. It's recommended for readers seeking a practical guide to implementing diverse time series analysis techniques, making it a must-read for those interested in mastering this domain.
Amazon Verified review Amazon
Amazon Kunde Apr 17, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is neither an introductory book nor something to read from cover to cover.But if you've already read an introduction into pyTorch and you're working on some kind of Time Series Project - this is what you wanna have on your desk!Dozens of great examples and answers to those typical questions "I want to do xyz, i know it needed something from statsmodels, but what was that again?". It's not just examples/answers but also combined with explanations on HOW and WHY you'd do things as they are described.Really a great book for the more experienced pyTorch user!
Amazon Verified review Amazon
hugomcroque May 11, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
While trying to learn how NeuralForecast works, I ended up using this book to obtain working code to get me started. It is a good resource for that, you can grab code to get started on almost every task in time series analysis. I also learned a lot from reading the probabilistic forecasting chapter, very interesting!
Amazon Verified review Amazon
Didi Apr 21, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Time series forecasting - making predictions based on historical data - is an important subfield of statistics and machine learning (ML). Following the deep learning (DL) revolution that has completely transformed the fields of computer vision and natural language processing in recent years, the field of time series modeling and analysis is now also being revolutionized by DL-based approaches.This book is a unique and comprehensive guide to time series forecasting, classification, and analysis using DL. This practical guide begins with an introduction to time series modeling using Python, including topics such as time series visualization, resampling, and dealing with missing data. It proceeds with an introduction to the PyTorch and PyTorch Lightning libraries and their use for time series forecasting, followed by a description of advanced DL architectures and methods for forecasting, such as the use of transformers and probabilistic forecasting. The last part of the book describes a variety of methods for solving the important problems of time series classification and anomaly detection.To get the most out of this book, readers are expected to have some familiarity with Python, and preferably also with its popular data manipulation libraries such as pandas and NumPy. The accompanying GitHub repo is well-organized and very helpful in reinforcing the concepts described in the book.This book is a wonderful, up-to-date resource for researchers, data scientists, and software engineers interested in building DL-based time series forecasting and analysis models in Python. Highly recommended!
Amazon Verified review Amazon
TM May 10, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have been enrolled in a data science program, and one of my instructors recommended using this book for our time series module. It is very well structured and provides a comprehensive overview of the topic. What I appreciate most is how it gradually increases in complexity. The basics are covered with sufficient detail to help you understand the fundamentals. You then quickly move on to solving real time series forecasting problems, which is motivating and gives a sense of progress. I also learned many new concepts; for example, I was unfamiliar with global time series forecasting models and what sets them apart. The book offers state-of-the-art examples with models such as N-BEATS and Temporal Fusion Transformers. In later chapters, it explores other methods of producing forecasts, for example, by generating probabilistic outputs. By the end, I felt my understanding of time series forecasting was quite strong, and I can now discuss the topic with friends who have been working in this field for many years in the industry.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.