Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keras LSTM inputs must be 3D arrays shaped (samples, timesteps, features). Add or construct the axes so each training example contains an ordered sequence, with all feature values for each timestep on the last axis. In the model’s Input(shape=...), leave out the batch axis: use (timesteps, features).

What shape does a Keras LSTM expect?

The LSTM API expects a 3D tensor: (batch, timesteps, feature). In training data, those axes mean:

  • Samples: independent sequences in the batch or dataset.
  • Timesteps: ordered observations within each sequence.
  • Features: values recorded at each timestep.

For example, a batch of 100 sequences, each containing 12 observations with 3 values per observation, has shape (100, 12, 3). The corresponding model input shape omits the sample axis: (12, 3). See the Keras LSTM API and Input API.

Reshape data that is already windowed

First identify what one sample represents. For forecasting, it is commonly one contiguous window of past observations. Keep the sequence order intact and group each timestep’s feature values along the final axis.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Deep Learning (Adaptive Computation and Machine Learning series)
  • Language Published: English
  • Binding: hardcover
  • It ensures you get the best usage for a longer period

Single-feature windows

If X_raw already has one row per window and shape (samples, timesteps), add an explicit feature axis of size 1:

# X_raw: (number_of_windows, timesteps)
X = X_raw[..., None]

model = keras.Sequential([
    keras.Input(shape=(X.shape[1], X.shape[2])),
    keras.layers.LSTM(32),
    keras.layers.Dense(1),
])

After the expansion, X has shape (samples, timesteps, 1). Check X.shape before fitting. The array includes samples; keras.Input(shape=...) describes only the dimensions after samples.

Multiple-feature windows

For data with several measurements per observation, arrange each sample as (timesteps, features) and the batch as (samples, timesteps, features). Do not swap the time and feature axes: the second axis is time and the third is feature.

Build sliding windows from a continuous time series

When the source is one continuous stream rather than prebuilt windows, keras.utils.timeseries_dataset_from_array creates sliding sequences. Its input data uses axis 0 as time; for multivariate series, keep feature columns in the remaining axis. The utility lets you set sequence length, the distance between window starts, spacing between observations within a window, and batch size. Details are in the Keras time-series data loading API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
dataset = keras.utils.timeseries_dataset_from_array(
    data=values[:-12],
    targets=values[12:],
    sequence_length=12,
    batch_size=32,
)

This pairs each 12-step input window with a target offset from the corresponding start index. Adapt the offset to the forecast horizon you need, and verify that every target aligns with its input window. The utility can also expose sequence_stride to move window starts farther apart and sampling_rate to space observations within a window.

Choose between reshaping arrays and generating a dataset

Approach Use it when What to check
Expand or reshape an array Your samples and windows already exist in the intended order. Preserve temporal and feature ordering; the target shape must contain a compatible number of elements.
timeseries_dataset_from_array You have a continuous time series and need the utility to form windows and yield batches. Choose sequence length, stride, sampling rate, and target offsets that match the forecasting task.

Keras Reshape changes the dimensions of each sample, not the meaning or temporal order of the values. Its target_shape excludes the batch dimension, must be compatible with the input element count, and may contain one -1 dimension for inference. Consult the Reshape layer API. Use it only when the existing element order already matches the sequence you intend to feed the LSTM.

Handle variable-length sequences and padding

Use None for a variable timestep dimension in the model input, for example:

keras.Input(shape=(None, 3))

This describes sequences with a varying number of timesteps and 3 features per timestep. The input pipeline and downstream layers must also support the resulting variable-length inputs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Deep Learning: A Visual Approach
  • Deep Learning: A Visual Approach
  • No Starch Press
  • ABIS BOOK

If sequences are padded to a common length and those padded steps should be ignored, add a masking strategy. Keras Masking(mask_value=...) masks a timestep only when every feature value at that timestep equals the chosen value. Zero works only if a zero-valued feature vector cannot be meaningful data that should be processed. The Masking API describes the layer behavior; Keras notes that downstream layers must support masks they receive, or an exception is raised. The LSTM API describes masked timesteps as false and usable timesteps as true in its mask convention.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Input shape and output shape are different choices

Changing the input reshape does not control how many outputs the LSTM returns. By default, it returns the final output for each sample. Set return_sequences=True when the next layer needs an output at every timestep. In the LSTM API example, input shape (32, 10, 8) produces (32, 4) by default and (32, 10, 4) with return_sequences=True.

Check these common shape mistakes

  • Passing a 2D single-feature array: (samples, timesteps) is missing the feature axis. Expand it to (samples, timesteps, 1).
  • Reversing time and features: use (samples, timesteps, features), not (samples, features, timesteps).
  • Including samples in Input(shape=...): normally provide only (timesteps, features); the data supplies the sample axis.
  • Reshaping to an incompatible size: the per-sample element count must match the target dimensions.
  • Assuming reshape creates valid windows: it cannot determine which values are adjacent in time or align targets. Build and check those relationships explicitly.
  • Assuming padding is automatically ignored: use an accurate mask when padded timesteps should be skipped.

When stateful LSTMs need a different batching setup

Stateful recurrence carries the state at one sample position into the same position in the next batch. That setup requires consistent batch ordering; Keras’ FAQ example fixes the batch size at 32, feeds consecutive chunks, and uses shuffle=False. Most independent sliding-window examples do not require stateful behavior and use the default non-stateful configuration. See the Keras FAQ.

Quick Recap

SaleBestseller No. 1
Deep Learning (Adaptive Computation and Machine Learning series)
Deep Learning (Adaptive Computation and Machine Learning series)
Language Published: English; Binding: hardcover; It ensures you get the best usage for a longer period
$51.51
SaleBestseller No. 2
SaleBestseller No. 5
Deep Learning: A Visual Approach
Deep Learning: A Visual Approach
Deep Learning: A Visual Approach; No Starch Press; ABIS BOOK
$73.40

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.