0% found this document useful (0 votes)
5 views5 pages

Practical 9

The document outlines a practical guide for building a time series forecasting model using a Recurrent Neural Network (RNN) with LSTM layers, specifically applied to the Air Passenger dataset. It includes steps for installing required libraries, loading and preprocessing the data, building and training the model, evaluating its performance, and saving the trained model. The final output includes visualizations of actual versus predicted values and the model's test loss.

Uploaded by

Tania Jamdar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views5 pages

Practical 9

The document outlines a practical guide for building a time series forecasting model using a Recurrent Neural Network (RNN) with LSTM layers, specifically applied to the Air Passenger dataset. It includes steps for installing required libraries, loading and preprocessing the data, building and training the model, evaluating its performance, and saving the trained model. The final output includes visualizations of actual versus predicted values and the model's test loss.

Uploaded by

Tania Jamdar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Practical 9 : Building a deep learning model for time series forecasting or anomaly detection

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.

Step 1: Install Required Libraries

Run the following command in the terminal to install necessary libraries:

bash

Copy code

pip install numpy pandas matplotlib scikit-learn tensorflow

Step 2: Python Code for Time Series Forecasting

Save the following code as time_series_forecasting.py.

python

Copy code

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

from sklearn.preprocessing import MinMaxScaler

from tensorflow.keras.models import Sequential

from tensorflow.keras.layers import LSTM, Dense

# Step 1: Load the Dataset

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"

data = pd.read_csv(url, usecols=[1], header=0)

data = data.values.astype("float32") # Ensure the data is float

# Step 2: Visualize the Data

plt.plot(data)

plt.title("Airline Passengers Over Time")

plt.xlabel("Time")
plt.ylabel("Passengers")

plt.show()

# Step 3: Normalize the Data

scaler = MinMaxScaler(feature_range=(0, 1))

scaled_data = scaler.fit_transform(data)

# Step 4: Prepare the Data for LSTM

def create_dataset(dataset, look_back=1):

X, y = [], []

for i in range(len(dataset) - look_back):

X.append(dataset[i:(i + look_back), 0])

y.append(dataset[i + look_back, 0])

return np.array(X), np.array(y)

look_back = 12 # Use 12 months (1 year) as input to predict the next value

X, y = create_dataset(scaled_data, look_back)

X = X.reshape((X.shape[0], X.shape[1], 1)) # Reshape for LSTM [samples, time_steps, features]

# Step 5: Split Data into Training and Testing Sets

train_size = int(len(X) * 0.8)

X_train, X_test = X[:train_size], X[train_size:]

y_train, y_test = y[:train_size], y[train_size:]

# Step 6: Build the LSTM Model

model = Sequential([

LSTM(50, activation="relu", input_shape=(look_back, 1)),

Dense(1)

])

model.compile(optimizer="adam", loss="mean_squared_error")
# Step 7: Train the Model

history = model.fit(X_train, y_train, epochs=50, batch_size=32, validation_data=(X_test, y_test),


verbose=1)

# Step 8: Evaluate the Model

loss = model.evaluate(X_test, y_test, verbose=0)

print(f"Test Loss: {loss:.4f}")

# Step 9: Predict and Inverse Transform

y_pred = model.predict(X_test)

y_pred = scaler.inverse_transform(y_pred)

y_test_actual = scaler.inverse_transform(y_test.reshape(-1, 1))

# Step 10: Plot Actual vs Predicted

plt.figure(figsize=(10, 5))

plt.plot(y_test_actual, label="Actual")

plt.plot(y_pred, label="Predicted")

plt.title("Actual vs Predicted Airline Passengers")

plt.xlabel("Time")

plt.ylabel("Passengers")

plt.legend()

plt.show()

# Step 11: Save the Model

model.save("lstm_time_series.h5")

print("Model saved as 'lstm_time_series.h5'.")

Step 3: Run the Code

1. Save the file as time_series_forecasting.py.

2. Open the terminal in VS Code.

3. Run the script:


bash

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.

o Link: Air Passenger Dataset.

2. Preprocessing:

o Data is scaled to the range [0, 1] using MinMaxScaler for better performance with
LSTMs.

o A sliding window (look_back) is used to create input-output pairs for training.

3. Model:

o LSTM Layer: Captures temporal dependencies in the time series data.

o Dense Layer: Outputs the next value in the sequence.

4. Training:

o 80% of the data is used for training, and 20% is reserved for testing.

o The model is trained for 50 epochs with a batch size of 32.

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:

o The trained model is saved as lstm_time_series.h5 for future use.

Output

1. Visualization:

o A line plot of the actual vs. predicted values.

2. Model:

o Saved as lstm_time_series.h5.

3. Test Loss:
o The Mean Squared Error (MSE) on the test data.

Dataset

 Air Passenger Dataset:

o URL: Air Passenger Dataset

o Automatically downloaded by the script.

You might also like