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
€20.98 €29.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (9 Ratings)
eBook Mar 2024 274 pages 1st Edition
eBook
€20.98 €29.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Cerqueira Profile Icon Luís Roque
Arrow right icon
€20.98 €29.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (9 Ratings)
eBook Mar 2024 274 pages 1st Edition
eBook
€20.98 €29.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€20.98 €29.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
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 : 9781805122739
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 114.97
Bayesian Analysis with Python
€37.99
Mastering PyTorch
€38.99
Deep Learning for Time Series Cookbook
€37.99
Total 114.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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.