What is a Time Series?
A time series is a list of values recorded over time, such as daily temperature, sales per month or stock prices. Forecasting means predicting the next values from the past ones.
Step 1: Create Sample Data
python
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0, 1000)
series = np.sin(0.05 * t) + 0.1 * np.random.randn(1000) # wave with noise
plt.plot(series[:200])
plt.show()
For real data, load your CSV with pandas and use a column such as df["temperature"].values.
Step 2: Split by Time, Not Randomly
Very important: Never shuffle time series before splitting. The model must be tested on the future, so the test set is always the last part.
python
split = int(len(series) * 0.8)
train, test = series[:split], series[split:]
Step 3: Scale
python
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
train_s = scaler.fit_transform(train.reshape(-1, 1)) # fit on train only
test_s = scaler.transform(test.reshape(-1, 1))
Step 4: Make Windows
The model gets a window of the last 30 values and has to predict the next one.
python
import keras
window = 30
def make_ds(data, shuffle):
return keras.utils.timeseries_dataset_from_array(
data=data[:-window], # inputs
targets=data[window:], # value right after each window
sequence_length=window,
batch_size=32,
shuffle=shuffle, # shuffling windows is fine for training
)
train_ds = make_ds(train_s, shuffle=True)
test_ds = make_ds(test_s, shuffle=False)
for x, y in train_ds.take(1):
print(x.shape, y.shape) # (32, 30, 1) (32, 1)
Step 5: Build and Train
python
from keras import layers
model = keras.Sequential([
keras.Input(shape=(window, 1)),
layers.LSTM(32),
layers.Dense(1),
])
model.compile(optimizer="adam", loss="mse")
model.fit(train_ds, validation_data=test_ds, epochs=15)
Step 6: Predict and Compare
python
preds = model.predict(test_ds)
y_true = np.concatenate([y for _, y in test_ds])
preds = scaler.inverse_transform(preds)
y_true = scaler.inverse_transform(y_true)
plt.plot(y_true[:150], label="real")
plt.plot(preds[:150], label="predicted")
plt.legend()
plt.show()
Forecasting Several Steps Ahead
python
last = test_s[-window:].reshape(1, window, 1)
future = []
for _ in range(20):
nxt = model.predict(last, verbose=0)[0, 0]
future.append(nxt)
last = np.append(last[:, 1:, :], [[[nxt]]], axis=1) # slide the window
future = scaler.inverse_transform(np.array(future).reshape(-1, 1))
Reality check: Always compare with a naive baseline, such as predicting that tomorrow equals today. If your LSTM cannot beat it, the model is not adding value.
Conclusion
Time series forecasting needs time-ordered splits, scaling on training data only and windowed samples. Then an LSTM can learn the pattern.
Quick Summary: Split by time, scale, create windows, train an LSTM with a Dense(1) output and invert the scaling.