Practical 9
Practical 9
building a time series forecasting model using a Recurrent Neural Network (RNN) with LSTM (Long
Short-Term Memory) layers. We will forecast future values of the Air Passenger dataset, a classic
time series dataset.
bash
Copy code
python
Copy code
import numpy as np
import pandas as pd
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
plt.plot(data)
plt.xlabel("Time")
plt.ylabel("Passengers")
plt.show()
scaled_data = scaler.fit_transform(data)
X, y = [], []
X, y = create_dataset(scaled_data, look_back)
model = Sequential([
Dense(1)
])
model.compile(optimizer="adam", loss="mean_squared_error")
# Step 7: Train the Model
y_pred = model.predict(X_test)
y_pred = scaler.inverse_transform(y_pred)
plt.figure(figsize=(10, 5))
plt.plot(y_test_actual, label="Actual")
plt.plot(y_pred, label="Predicted")
plt.xlabel("Time")
plt.ylabel("Passengers")
plt.legend()
plt.show()
model.save("lstm_time_series.h5")
Copy code
python time_series_forecasting.py
Code Explanation
1. Dataset:
o The Air Passenger dataset contains monthly totals of international airline passengers
from 1949 to 1960.
2. Preprocessing:
o Data is scaled to the range [0, 1] using MinMaxScaler for better performance with
LSTMs.
3. Model:
4. Training:
o 80% of the data is used for training, and 20% is reserved for testing.
5. Evaluation:
o Predictions are made on the test set, and results are inverse-transformed to their
original scale.
o The model's performance is visualized by plotting the actual vs. predicted values.
6. Saving:
Output
1. Visualization:
2. Model:
o Saved as lstm_time_series.h5.
3. Test Loss:
o The Mean Squared Error (MSE) on the test data.
Dataset