Skip to content
SK Subham KumarTSF Hub · time-series forecasting
Deep learningConvolutionalRecurrent

CNN-LSTM

Convolutional + LSTM network

Convolutions pick out short local patterns; an LSTM then models how those patterns evolve. The building block behind my MvS CNN-BiLSTM model for PM2.5.

Overview

A 1-D convolution slides small filters along the input window, turning raw values into features such as local slopes, spikes and short motifs. Pooling shortens the sequence. An LSTM then reads this compressed feature sequence and carries information across longer spans than the filters can see.

The split of labour helps on noisy real-world data such as air quality, energy and sensor streams. Bidirectional LSTMs and multi-view inputs extend the idea: my MvS CNN-BiLSTM paper stacks CNN-BiLSTM learners over several views of the data for urban PM2.5 prediction.

How it works

A causal 1-D convolution with kernel size \(K\) and filters \(W_k\):

\[h_t=\mathrm{ReLU}\Big(\sum_{k=0}^{K-1}W_k\,x_{t-k}+b\Big)\]

The LSTM then updates its cell state with forget, input and output gates:

\[c_t=f_t\odot c_{t-1}+i_t\odot\tanh(W_c[h_{t-1},x_t]+b_c),\qquad h_t=o_t\odot\tanh(c_t)\]

When to use it

Use it for

  • Sensor, air-quality and energy data with local noise
  • Medium to large datasets (thousands of windows)
  • Multivariate inputs: stack channels on the last axis

Avoid it for

  • Short series (a few hundred points): use statistical models
  • When interpretability is required

Key settings

SettingWhat it controlsTypical value
window lengthHow many past steps the model sees1–3 seasonal cycles
filters / kernel_sizeNumber and width of convolution filters32–64 / 3–7
LSTM unitsHidden state size32–128
dropout + early stoppingRegularisation0.1–0.3; patience 10

Python example

Follows the library’s documented API · needs PyTorch/TensorFlow, not run hereDownload cnn_lstm.py
# pip install tensorflow
import numpy as np
import pandas as pd
from tensorflow import keras
from tensorflow.keras import layers

URL = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv"
y = pd.read_csv(URL, index_col="Date", parse_dates=True)["Temp"].to_numpy(dtype="float32")
L, TEST = 60, 365                                   # 60-day input window, last year held out
mu, sd = y[:-TEST].mean(), y[:-TEST].std()          # scale with training data only
z = (y - mu) / sd

X = np.stack([z[i:i + L] for i in range(len(z) - L)])[..., None]   # (samples, 60, 1)
t = z[L:]
X_tr, t_tr, X_te, t_te = X[:-TEST], t[:-TEST], X[-TEST:], t[-TEST:]

model = keras.Sequential([
    layers.Input(shape=(L, 1)),
    layers.Conv1D(32, kernel_size=5, padding="causal", activation="relu"),   # local patterns
    layers.Conv1D(32, kernel_size=5, padding="causal", activation="relu"),
    layers.MaxPooling1D(pool_size=2),                                         # shorter sequence for the LSTM
    layers.LSTM(64),                                                          # longer-range dependencies
    layers.Dropout(0.2),
    layers.Dense(1),
])
model.compile(optimizer=keras.optimizers.Adam(1e-3), loss="mse")
model.fit(X_tr, t_tr, validation_split=0.1, epochs=100, batch_size=64, verbose=0,
          callbacks=[keras.callbacks.EarlyStopping(patience=10, restore_best_weights=True)])

pred = model.predict(X_te, verbose=0).ravel() * sd + mu
print(f"one-step-ahead MAE on the last year: {np.mean(np.abs(pred - y[-TEST:])):.2f} °C")

Tips & pitfalls

  • Scale inputs with statistics from the training period only.
  • Use causal padding so no filter peeks at future values.
  • Average several random seeds: small networks vary from run to run.

References

  1. Hochreiter, S., & Schmidhuber, J. (1997). Long short-term memory. Neural Computation, 9(8), 1735–1780.
  2. Livieris, I. E., Pintelas, E., & Pintelas, P. (2020). A CNN–LSTM model for gold price time-series forecasting. Neural Computing and Applications, 32, 17351–17360.
  3. Kumar, S., & Kumar, V. (2024). Multi-view Stacked CNN-BiLSTM (MvS CNN-BiLSTM) for urban PM2.5 concentration prediction of India’s polluted cities. Journal of Cleaner Production, 444, 141259.