0Pricing
Learn AI with Python · Lesson

LSTM for Time Series Forecasting

Sequence preparation, stateless vs stateful LSTM, look-back window, multi-step forecasting.

LSTM for Time Series Forecasting is a free Learn AI with Python lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn AI with Python learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why LSTM for Time Series?

LSTM (Long Short-Term Memory) is a recurrent neural network that remembers patterns across long sequences using gated memory cells. It can model nonlinear dependencies that ARIMA cannot, making it powerful for complex series given enough data.

Sequence Windowing

LSTMs learn from windows: fixed-length slices of past steps used to predict the next value. With a window of 10, the model sees steps 1-10 to predict step 11, then 2-11 to predict 12, and so on.

Creating Windows in Code

A helper turns a 1D series into input/target pairs.

import numpy as np

def make_windows(series, window):
    X, y = [], []
    for i in range(len(series) - window):
        X.append(series[i:i+window])
        y.append(series[i+window])
    return np.array(X), np.array(y)

X, y = make_windows(values, window=10)

Scaling the Data

Neural networks train better on scaled inputs. Use MinMaxScaler to map values to [0, 1], and remember to inverse-transform predictions later.

from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()
scaled = scaler.fit_transform(values.reshape(-1, 1))

Reshaping for the LSTM

Keras LSTM layers expect input shaped (samples, timesteps, features). For a univariate series, features is 1.

# X is (samples, timesteps); add a feature axis
X = X.reshape((X.shape[0], X.shape[1], 1))
print(X.shape)  # (samples, timesteps, 1)

Building the Model

A simple architecture: one LSTM(50) layer feeding a Dense(1) output that predicts the next value.

from tensorflow.keras import Sequential
from tensorflow.keras.layers import LSTM, Dense

model = Sequential([
    LSTM(50, input_shape=(X.shape[1], 1)),
    Dense(1)
])

Why Dense(1)

Forecasting one step ahead is a regression with a single numeric output, so the final layer is Dense(1) with no activation. For multi-step forecasts you would use Dense(n_steps).

Compiling

Use the adam optimizer and mse (mean squared error) loss, the standard choice for regression on continuous targets.

model.compile(optimizer="adam", loss="mse")

Training

Fit on the windowed data. A validation split monitors generalization across epochs.

history = model.fit(
    X, y,
    epochs=50,
    batch_size=32,
    validation_split=0.2
)

Predicting

Predict on new windows, then inverse-transform to return to the original scale.

pred_scaled = model.predict(X_test)
pred = scaler.inverse_transform(pred_scaled)

Stacking and Tuning

For harder series, stack LSTMs (set return_sequences=True on all but the last) and add dropout. More layers capture deeper patterns but need more data and risk overfitting.

model = Sequential([
    LSTM(50, return_sequences=True, input_shape=(X.shape[1], 1)),
    LSTM(50),
    Dense(1)
])

Quick Check

Test your LSTM forecasting knowledge.

Recap

You prepared windows, scaled with MinMaxScaler, reshaped to (samples, timesteps, features), built LSTM(50) + Dense(1), compiled with adam/mse, trained, and predicted (inverse-transforming back). That ends the Time Series course. Next course: Recommendation Systems.

Frequently asked questions

Is the “LSTM for Time Series Forecasting” lesson free?

Yes — the full text of “LSTM for Time Series Forecasting” is free to read here on the web, and the Learn AI with Python course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn AI with Python course, upgrade to CoddyKit PRO.

What will I learn in “LSTM for Time Series Forecasting”?

Sequence preparation, stateless vs stateful LSTM, look-back window, multi-step forecasting. You practise Learn AI with Python with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Learn AI with Python?

No prior experience is required. Learn AI with Python on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “LSTM for Time Series Forecasting” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Learn AI with Python lesson?

Yes. Every Learn AI with Python lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Time Series Components and Stationarity
  2. ARIMA and SARIMA Models
  3. Prophet for Automated Forecasting
  4. LSTM for Time Series Forecasting
← Back to Learn AI with Python