• Stars
    star
    222
  • Rank 179,123 (Top 4 %)
  • Language
    Python
  • License
    MIT License
  • Created over 5 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Conditional RNNs for Tensorflow / Keras.

Conditional Recurrent for Tensorflow/Keras

Downloads Downloads CI

  • Conditions time series predictions on time-invariant data.
  • ConditionalRecurrent is a fully compatible Keras wrapper which supports any recurrent layer.
  • Tested with all versions of Tensorflow (until 2.10, Sep 2022).

Installation / PyPI

ConditionalRecurrent is on PyPI. You can also install it from the sources.

pip install cond-rnn

What is Conditional RNN?

The ConditionalRecurrent layer is useful if you have time series data with external inputs that do not depend on time. Let's consider some weather data for two different cities: Paris and San Francisco. The aim is to predict the next temperature data point. Based on our knowledge, the weather behaves differently depending on the city. You can either:

  • Combine the auxiliary features with the time series data (ugly!).
  • Concatenate the auxiliary features with the output of the RNN layer. It's some kind of post-RNN adjustment since the RNN layer won't see this auxiliary info.
  • Or just use this library! Long story short, we initialize the RNN states with a learned representation of the conditions (e.g. Paris or San Francisco). This way, you model elegantly P(x_{t+1}|x_{0:t}, cond).

API

This Keras wrapper ConditionalRecurrent initiates the internal states of recurrent layers with conditions given as separate inputs. It can be used with any recurrent layer supported by Keras and supports wrappers like Bidirectional.

Arguments

  • layer: a tf.keras.layers.Layer instance (LSTM, GRU or SimpleRNN...).

Call arguments

  • inputs: 3-D Tensor with shape [batch_size, timesteps, input_dim].
  • inputs_cond: 2-D Tensor or list of tensors with shape [batch_size, cond_dim]. In the case of a list, the tensors can have a different cond_dim.
  • training: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the wrapped layer.

Raises

AssertionError: If not initialized with a tf.keras.layers.Layer instance.

Example

from tensorflow.keras import Input
from tensorflow.keras.layers import LSTM

from cond_rnn import ConditionalRecurrent

time_steps, input_dim, output_dim, batch_size, cond_size = 128, 6, 12, 32, 5
inputs = Input(batch_input_shape=(batch_size, time_steps, input_dim))
cond_inputs = Input(batch_input_shape=(batch_size, cond_size))

outputs = ConditionalRecurrent(LSTM(units=output_dim))([inputs, cond_inputs])
print(outputs.shape)  # (batch_size, output_dim)

You can also have a look at a real world example to see how ConditionalRecurrent performs: here.

A bit more background...

This implementation was inspired from the very good answer: Adding Features To Time Series Model LSTM, which I quote below. The option 3 was implemented in this library (with a slight modification: we do not add 𝑣⃗ to the hidden state but rather overwrite the hidden state by 𝑣⃗. We can argue that this is almost exactly the same thing as 𝑣⃗ is obtained 𝑣⃗ =𝐖π‘₯βƒ— +𝑏⃗ where 𝑏⃗ could be the hidden state).

For RNNs (e.g., LSTMs and GRUs), the layer input is a list of timesteps, and each timestep is a feature tensor. That means that you could have a input tensor like this (in Pythonic notation):

# Input tensor to RNN
[
    # Timestep 1
    [ temperature_in_paris, value_of_nasdaq, unemployment_rate ],
    # Timestep 2
    [ temperature_in_paris, value_of_nasdaq, unemployment_rate ],
    # Timestep 3
    [ temperature_in_paris, value_of_nasdaq, unemployment_rate ],
    ...
]

So absolutely, you can have multiple features at each timestep. In my mind, weather is a time series feature: where I live, it happens to be a function of time. So it would be quite reasonable to encode weather information as one of your features in each timestep (with an appropriate encoding, like cloudy=0, sunny=1, etc.).

If you have non-time-series data, then it doesn't really make sense to pass it through the LSTM, though. Maybe the LSTM will work anyway, but even if it does, it will probably come at the cost of higher loss / lower accuracy per training time.

Alternatively, you can introduce this sort of "extra" information into your model outside of the LSTM by means of additional layers. You might have a data flow like this:

TIME_SERIES_INPUT ------> LSTM -------\
                                       *---> MERGE ---> [more processing]
AUXILIARY_INPUTS --> [do something] --/

So you would merge your auxiliary inputs into the LSTM outputs, and continue your network from there. Now your model is simply multi-input.

For example, let's say that in your particular application, you only keep the last output of the LSTM output sequence. Let's say that it is a vector of length 10. You auxiliary input might be your encoded weather (so a scalar). Your merge layer could simply append the auxiliary weather information onto the end of the LSTM output vector to produce a single vector of length 11. But you don't need to just keep the last LSTM output timestep: if the LSTM outputted 100 timesteps, each with a 10-vector of features, you could still tack on your auxiliary weather information, resulting in 100 timesteps, each consisting of a vector of 11 datapoints.

The Keras documentation on its functional API has a good overview of this.

In other cases, you may want to condition the LSTM on non-temporal data. For example, predict the weather tomorrow, given location. In this case, here are three suggestions, each with positive/negatives:

  1. Have the first timestep contain your conditioning data, since it will effectively "set" the internal/hidden state of your RNN. Frankly, I would not do this, for a bunch of reasons: your conditioning data needs to be the same shape as the rest of your features, makes it harder to create stateful RNNs (in terms of being really careful to track how you feed data into the network), the network may "forget" the conditioning data with enough time (e.g., long training sequences, or long prediction sequences), etc.

  2. Include the data as part of the temporal data itself. So each feature vector at a particular timestep includes "mostly" time-series data, but then has the conditioning data appended to the end of each feature vector. Will the network learn to recognize this? Probably, but even then, you are creating a harder learning task by polluting the sequence data with non-sequential information. So I would also discourage this.

  3. Probably the best approach would be to directly affect the hidden state of the RNN at time zero. This is the approach taken by Karpathy and Fei-Fei and by Vinyals et al. This is how it works:

    • For each training sample, take your condition variables π‘₯βƒ— .
    • Transform/reshape your condition variables with an affine transformation to get it into the right shape as the internal state of the RNN: 𝑣⃗ =𝐖π‘₯βƒ— +𝑏⃗ (these 𝐖 and 𝑏⃗ are trainable weights). You can obtain it with a Dense layer in keras.
    • For the very first timestep, add 𝑣⃗ to the hidden state of the RNN when calculating its value. This approach is the most "theoretically" correct, since it properly conditions the RNN on your non-temporal inputs, naturally solves the shape problem, and also avoids polluting your inputs timesteps with additional, non-temporal information. The downside is that this approach often requires graph-level control of your architecture, so if you are using a higher-level abstraction like Keras, you will find it hard to implement unless you add your own layer type.

Citation

@misc{CondRNN,
  author = {Philippe Remy},
  title = {Conditional RNN for Keras},
  year = {2020},
  publisher = {GitHub},
  journal = {GitHub repository},
  howpublished = {\url{https://github.com/philipperemy/cond_rnn}},
}

FAQ

References

More Repositories

1

keras-attention

Keras Attention Layer (Luong and Bahdanau scores).
Python
2,804
star
2

tensorflow-1.4-billion-password-analysis

Deep Learning model to analyze a large corpus of clear text passwords.
Python
1,902
star
3

keras-tcn

Keras Temporal Convolutional Network.
Python
1,863
star
4

yolo-9000

YOLO9000: Better, Faster, Stronger - Real-Time Object Detection. 9000 classes!
1,179
star
5

keract

Layers Outputs and Gradients in Keras. Made easy.
Python
1,040
star
6

deep-speaker

Deep Speaker: an End-to-End Neural Speaker Embedding System.
Python
897
star
7

n-beats

Keras/Pytorch implementation of N-BEATS: Neural basis expansion analysis for interpretable time series forecasting.
Python
852
star
8

name-dataset

The Python library for names.
Python
810
star
9

stanford-openie-python

Stanford Open Information Extraction made simple!
Python
628
star
10

deep-learning-bitcoin

Exploiting Bitcoin prices patterns with Deep Learning.
Python
525
star
11

FX-1-Minute-Data

HISTDATA - Dataset composed of all FX trading pairs / Crude Oil / Stock Indexes. Simple API to retrieve 1 Minute data (and tick data) Historical FX Prices (up to date).
Python
477
star
12

timit

The DARPA TIMIT Acoustic-Phonetic Continuous Speech Corpus.
287
star
13

Deep-Learning-Tinder

Simple Tinder algorithm able to swipe left and right based on the recommendations of a pre-trained deep neural network (Machine Learning).
Python
276
star
14

financial-news-dataset

Reuters and Bloomberg
223
star
15

my-first-bitcoin-miner

For the curious minds who want to understand how Bitcoin Blockchain works!
Python
189
star
16

expressvpn-python

ExpressVPN - Python Wrapper (IP auto switch).
Python
182
star
17

tensorflow-multi-dimensional-lstm

Multi dimensional LSTM as described in Alex Graves' Paper https://arxiv.org/pdf/0705.2011.pdf
Jupyter Notebook
155
star
18

tensorflow-class-activation-mapping

Learning Deep Features for Discriminative Localization (2016)
Python
152
star
19

easy-encryption

A very simple C++ module to encrypt/decrypt strings based on B64 and Vigenere ciper.
C++
144
star
20

Order-Book-Matching-Engine

Order Book Matching Engine for Stock Exchanges (1us latency for matching)
Java
139
star
21

tensorflow-ctc-speech-recognition

Application of Connectionist Temporal Classification (CTC) for Speech Recognition (Tensorflow 1.0 but compatible with 2.0).
Python
131
star
22

tensorflow-phased-lstm

Phased LSTM: Accelerating Recurrent Network Training for Long or Event-based Sequences (NIPS 2016) - Tensorflow 1.0
Python
130
star
23

fractional-differentiation-time-series

As described in Advances of Machine Learning by Marcos Prado.
Python
121
star
24

amazon-reviews-scraper

Yet another multi language scraper for Amazon targeting reviews.
Python
116
star
25

lead-lag

Estimation of the lead-lag parameter from non-synchronous data.
Jupyter Notebook
108
star
26

google-news-scraper

Google News Scraper for languages like Japanese, Chinese... [VPN Support]
Python
95
star
27

stock-volatility-google-trends

Deep Learning Stock Volatility with Google Domestic Trends: https://arxiv.org/pdf/1512.04916.pdf
Python
92
star
28

mercari-python-api

The Python Mercari API.
Python
84
star
29

japanese-words-to-vectors

Word2vec (word to vectors) approach for Japanese language using Gensim and Mecab.
Python
84
star
30

Stanford-NER-Python

Stanford Named Entity Recognizer (NER) - Python Wrapper
Python
75
star
31

very-deep-convnets-raw-waveforms

Tensorflow - Very Deep Convolutional Neural Networks For Raw Waveforms - https://arxiv.org/pdf/1610.00087.pdf
Python
74
star
32

speaker-change-detection

Paper: https://arxiv.org/abs/1702.02285
Python
63
star
33

tensorflow-maxout

Maxout Networks TensorFlow implementation presented in https://arxiv.org/abs/1302.4389
Python
57
star
34

tensorflow-cnn-time-series

Feeding images of time series to Conv Nets! (Tensorflow + Keras)
Python
50
star
35

3.7-billion-passwords-tools

Tools to manipulate the data behind Collection #1 (and #2–5) - AntiPublic.
Python
48
star
36

keras-seq2seq-example

Toy Keras implementation of a seq2seq model with examples.
Python
48
star
37

tensorflow-fifo-queue-example

Example on how to use a Tensorflow Queue to feed data to your models.
Python
39
star
38

python-darknet-yolo-v4

Python to interface with Darknet Yolo V4 (multi GPU with load balancer supported).
Python
37
star
39

bitmex-liquidations

Minimal code to show how to receive the liquidations in realtime on Bitmex.
Python
33
star
40

Statistical-Arbitrage

Using Particle Markov Chain Monte Carlo
MATLAB
33
star
41

vision-api

Google Vision API made easy!
Python
30
star
42

tensorflow-grid-lstm

Implementation of the paper https://arxiv.org/pdf/1507.01526v3.pdf (Tensorflow 1.0, Python 3)
Python
29
star
43

advanced-deep-learning-keras

File repository for the course [Advanced Deep Learning with Keras]. Packt Publishing.
Jupyter Notebook
28
star
44

Facebook-Profile-Pictures-Downloader

πŸ˜† Download public profile pictures from Facebook.
Python
26
star
45

bitcoin-market-data

Largest tick market data for Bitcoin (mirror server of bitcoincharts.com).
Shell
24
star
46

beer-dataset

The biggest beer database is in this repo!
Python
23
star
47

NiceHash-api-monitoring-client

Simple NiceHash client to monitor your mining rigs. Configure alerts and emails!
Python
22
star
48

information-extraction-with-dominating-rules

Information extraction based on Stanford open IE Library and domination decision rules. http://philipperemy.github.io/information-extract/
Python
22
star
49

Market-Data

Module to retrieve realtime stock quotes of Paris stock exchange
Java
20
star
50

instant-music-playlist-downloader

Download MP3 songs from the web.
Python
20
star
51

Sentiment-Analysis-NLP

Sentiment Analysis applied to different datasets such as IMDB
Python
19
star
52

wavenet

A general TensorFlow implementation of the Wavenet network to be used to model long term sequences with less trainable parameters.
Python
18
star
53

keras-snail-attention

SNAIL Attention Block for Keras.
Python
17
star
54

which-of-your-friends-are-on-tinder

Discover which of your Facebook friends are on Tinder!
Python
16
star
55

LSTM-text-generation

Generating NEW Reuters articles from Reuters articles.
Python
16
star
56

Candlestick-Chart-Generator

Candlestick Charts in JavaScript.
JavaScript
15
star
57

keras-frn

Keras Filter Response Normalization Layer.
Python
15
star
58

keras-sde-net

Keras implementation of SDE-Net (ICML 2020).
Python
14
star
59

Peer-Group-Analysis-Clustering

Unsupervised Clustering of Time Series using Peer Group Analysis PGA
MATLAB
14
star
60

OrderBook-TWAP

Programming Test
C++
13
star
61

selenium-python-examples

Selenium examples in Python (web scraper).
Python
12
star
62

python-pubsub

A simple python implementation of a message router with many subscribers and many publishers.
Python
12
star
63

philipperemy.github.io

My blog.
SCSS
11
star
64

fxrt

Realtime FX prices from the Oanda broker.
Python
10
star
65

tensorflow-isan-rnn

Input Switched Affine Networks: An RNN Architecture Designed for Interpretability. http://proceedings.mlr.press/v70/foerster17a/foerster17a.pdf
Python
10
star
66

twitter-arxiv-sanity

Your daily "top hype" papers.
Python
9
star
67

japan-weather-forecast

Japanese Meteorological Agency (scraper + data)
Python
9
star
68

github-backup

Back up all your Github repositories in a directory.
Python
9
star
69

Leboncoin

Management of small ads (editing, publishing, deleting, re-publishing)
Java
9
star
70

Github-full-data-set

Generating GitHub data (~1M repositories May 2017).
Python
8
star
71

cocktails

Generate the best cocktail ever with Machine Learning !
Python
8
star
72

Technical-Analysis

Technical Analysis Tool based on TA Lib
C
8
star
73

Ransac-Java

Implementation of the Ransac algorithm written in Java.
Java
8
star
74

Data-Mining-Automaton

Quantitative Algobox based on Data Mining techniques
Java
8
star
75

HFT-FIX-Parser

Ultra low latency FIX Parser
7
star
76

GPU-Activity-Monitoring

Python monitoring tool for the nvidia-smi command on Linux.
Python
7
star
77

japanese-street-addresses-scraper

Scraper for Japanese street addresses (住所).
Python
7
star
78

bitstamp-realtime-order-book

Gives you low latency access to Bitstamp Realtime Order Book.
Python
7
star
79

arma-scipy-fit

Estimating coefficients of ARMA models with the Scipy package.
Python
7
star
80

urban-dictionary-transformers

Transformers applied to Urban Dictionary for fun.
Python
7
star
81

digital-setting-circles

Compatible with Raspberry Pi. Setting circles are used on telescopes equipped with an equatorial mount to find astronomical objects in the sky by their equatorial coordinates.
C++
7
star
82

binance-futures

Straightforward API endpoint to receive market data for Binance Futures.
Python
6
star
83

keras-mode-normalization

Keras Implementation of Mode Normalization (Lucas Deecke, Iain Murray, Hakan Bilen, 2018)
Python
6
star
84

Ogame-API

Ogame API
Java
6
star
85

bitflyer

Bitflyer API Realtime Feed Python.
Python
6
star
86

Kaggle-PKDD-Taxi-I

https://www.kaggle.com/c/pkdd-15-predict-taxi-service-trajectory-i
Python
6
star
87

ssh-failed-attempts

Tool to detect and analyze failed SSH attempts.
Python
5
star
88

Idealwine-wine-prices

API to retrieve quotes from daily wine auctions
Java
5
star
89

notifier

Receive notifications on your phone when your CLI tasks finish.
Python
5
star
90

API-Ratp

API to retrieve real time schedule times for Paris transports
5
star
91

Visual-Ballistic-Roulette-Vision

Ball and wheel zero tracking.
Python
5
star
92

Visual-Ballistic-Roulette-python

Visual Ballistic Roulette written in Python.
Python
5
star
93

tf-easy-model-saving

An easy way to load and save checkpoints in Tensorflow!
Python
5
star
94

Quantitative-Market-Data-Generator

Equity Prices Generator using Quantitative methods such as Brownian Motion
4
star
95

Monte-Carlo-Pi-Computation

This projects aims at computing PI using Monte Carlo method
4
star
96

Visual-Ballistic-Roulette-Timer-Android

Timer for Roulette written for Android
Java
4
star
97

EGAIN-pytorch

Python
4
star
98

Visual-Ballistic-Roulette-Display-Android

Android App
Java
4
star
99

record-your-internet-speed

Record your internet speed at fixed intervals.
Python
4
star
100

Martingale-Roulette-MonteCarlo

Monte Carlo simulations for Casino Roulette
MATLAB
4
star