Skip to content
SK Subham KumarTSF Hub · time-series forecasting
Foundation & quantum2022QuantumVariational circuitsResearch

Quantum ML

Quantum machine learning for time series: variational circuits and QLSTM

Use a parameterised quantum circuit as a trainable model: encode a window of past values into qubit rotations, entangle, measure, and train the angles with a classical optimiser.

Overview

A variational quantum circuit (VQC) is a quantum analogue of a small neural network. Inputs are encoded as rotation angles, trainable rotation-and-entanglement layers transform the state, and measuring an observable gives a number between −1 and 1. A classical optimiser updates the angles in a hybrid loop. Gradients come from the parameter-shift rule, which needs only extra circuit evaluations.

QLSTM replaces the linear maps inside each LSTM gate with VQCs, giving a quantum-enhanced recurrent model. This is an active research area, and an interest of mine. Today’s experiments run on simulators or small, noisy hardware, so treat results as research, not production forecasting.

How it works

For an input window \(x\) and trainable angles \(\theta\), the model output is an expectation value:

\[f_\theta(x)=\langle 0\rvert\,U_{\text{enc}}(x)^\dagger\,W(\theta)^\dagger\,Z_0\,W(\theta)\,U_{\text{enc}}(x)\,\lvert 0\rangle\in[-1,1]\]

The parameter-shift rule gives exact gradients for rotation gates:

\[\frac{\partial f}{\partial\theta_j}=\tfrac12\Big[f\big(\theta_j+\tfrac{\pi}{2}\big)-f\big(\theta_j-\tfrac{\pi}{2}\big)\Big]\]

Because the output is bounded, model a stationary target such as log-changes, as the example does, rather than a trending level.

When to use it

Use it for

  • Research on quantum and quantum-inspired sequence models
  • Learning how hybrid quantum–classical training works
  • Small, low-dimensional problems that fit a few qubits

Avoid it for

  • Production forecasting today
  • High-dimensional inputs: simulation cost grows exponentially with qubits
  • Expecting a speed or accuracy advantage: none is established for forecasting yet

Key settings

SettingWhat it controlsTypical value
n_qubitsUsually one per input feature or lag4–8 on simulators
n_layersDepth of entangling layers1–4
embeddingHow inputs become anglesAngleEmbedding, scaled to [0, π]
optimiserClassical update ruleAdam, step size 0.01–0.1

Python example

✓ Tested: runs end to endDownload quantum_vqc.py
import numpy as np
import pandas as pd
import pennylane as qml
from pennylane import numpy as pnp

URL = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
level = pd.read_csv(URL)["Passengers"].to_numpy(dtype=float)
# a circuit's output is bounded, so model monthly log-changes (stationary), not the trending level
r = np.diff(np.log(level))
r_scale = np.abs(r[:-24]).max()                       # scale with training data only
z = r / r_scale                                       # now within about [-1, 1]

n_lags = n_qubits = 4                                 # one qubit per lag
X = np.stack([z[i:i + n_lags] for i in range(len(z) - n_lags)])
t = z[n_lags:]                                        # next month's scaled log-change
X_tr, t_tr, X_te, t_te = X[:-24], t[:-24], X[-24:], t[-24:]

dev = qml.device("default.qubit", wires=n_qubits)

@qml.qnode(dev)
def circuit(x, weights):
    qml.AngleEmbedding(np.pi * x, wires=range(n_qubits))          # lag window -> rotation angles
    qml.StronglyEntanglingLayers(weights, wires=range(n_qubits))  # trainable entangling layers
    return qml.expval(qml.PauliZ(0))                              # read out a value in [-1, 1]

def predict(weights, scale, bias, X):
    return pnp.stack([scale * circuit(x, weights) + bias for x in X])

def cost(weights, scale, bias, X, t):
    return pnp.mean((predict(weights, scale, bias, X) - t) ** 2)

rng = np.random.default_rng(0)
shape = qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=n_qubits)
weights = pnp.array(rng.normal(0, 0.1, shape), requires_grad=True)
scale, bias = pnp.array(1.0, requires_grad=True), pnp.array(0.0, requires_grad=True)

opt = qml.AdamOptimizer(stepsize=0.05)
for step in range(120):                                # hybrid loop: quantum forward, classical update
    batch = rng.choice(len(X_tr), size=16, replace=False)
    Xb, tb = X_tr[batch], t_tr[batch]
    weights, scale, bias = opt.step(lambda w, s, b: cost(w, s, b, Xb, tb), weights, scale, bias)
    if step % 30 == 0:
        print(f"step {step:3d}  train MSE {cost(weights, scale, bias, X_tr, t_tr):.4f}")

prev = level[-25:-1]                                  # last observed month before each target
pred = prev * np.exp(np.array(predict(weights, scale, bias, X_te)) * r_scale)
actual = level[-24:]
print(f"one-step-ahead MAE, last 24 months: {np.mean(np.abs(pred - actual)):.1f} passengers")
print(f"naive (repeat last month) MAE:      {np.mean(np.abs(prev - actual)):.1f} passengers")

Tips & pitfalls

  • Deep random circuits suffer from barren plateaus (vanishing gradients): keep circuits shallow and initialise near zero.
  • Always compare with a classical model of similar size: a small MLP or ridge on the same lags.
  • Simulate with exact expectations first, then add shot noise to see how results hold up on hardware.

References

  1. Mitarai, K., Negoro, M., Kitagawa, M., & Fujii, K. (2018). Quantum circuit learning. Physical Review A, 98, 032309.
  2. Schuld, M., Bergholm, V., Gogolin, C., Izaac, J., & Killoran, N. (2019). Evaluating analytic gradients on quantum hardware. Physical Review A, 99, 032331.
  3. Chen, S. Y.-C., Yoo, S., & Fang, Y.-L. L. (2022). Quantum Long Short-Term Memory. Proceedings of ICASSP 2022.
  4. McClean, J. R., Boixo, S., Babbush, R., Smelyanskiy, V. N., & Neven, H. (2018). Barren plateaus in quantum neural network training landscapes. Nature Communications, 9, 4812.