Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon DeepAR Tensorflow Sample Code


DeepAR Tensorflow Sample Code


Here is a sample code for implementing the DeepAR algorithm using TensorFlow:

python
# Import necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.losses import MeanSquaredError

# Load the dataset
df = pd.read_csv('your_data.csv')

# Split the data into training and testing sets
train_size = int(0.8 * len(df))
train_data, test_data = df[0:train_size], df[train_size:]

# Define the model
model = Sequential()
model.add(LSTM(50, input_shape=(1, 1)))
model.add(Dense(1))
model.compile(optimizer=Adam(lr=0.001), loss=MeanSquaredError())

# Define the training and testing data
train_features = train_data['feature'].values.reshape(-1, 1)
train_labels = train_data['target'].values.reshape(-1, 1)
test_features = test_data['feature'].values.reshape(-1, 1)
test_labels = test_data['target'].values.reshape(-1, 1)

# Train the model
model.fit(train_features, train_labels, epochs=100, validation_data=(test_features, test_labels), callbacks=[EarlyStopping(monitor='val_loss', patience=5)])

# Make predictions on the test data
predictions = model.predict(test_features)

# Plot the actual and predicted values
plt.plot(test_labels)
plt.plot(predictions)
plt.legend(['Actual', 'Predicted'])
plt.show()

This code assumes that you have a CSV file named 'your_data.csv' containing the time series data. It first loads the data into a Pandas DataFrame, then splits it into training and testing sets. The model is defined using the Keras API, with an LSTM layer followed by a dense layer. The model is trained using the Adam optimizer and mean squared error loss. Finally, the model is used to make predictions on the test data, and the actual and predicted values are plotted for comparison[1][2][4].

Example Usage

python
# Load the dataset
df = pd.read_csv('your_data.csv')

# Split the data into training and testing sets
train_size = int(0.8 * len(df))
train_data, test_data = df[0:train_size], df[train_size:]

# Define the model
model = Sequential()
model.add(LSTM(50, input_shape=(1, 1)))
model.add(Dense(1))
model.compile(optimizer=Adam(lr=0.001), loss=MeanSquaredError())

# Define the training and testing data
train_features = train_data['feature'].values.reshape(-1, 1)
train_labels = train_data['target'].values.reshape(-1, 1)
test_features = test_data['feature'].values.reshape(-1, 1)
test_labels = test_data['target'].values.reshape(-1, 1)

# Train the model
model.fit(train_features, train_labels, epochs=100, validation_data=(test_features, test_labels), callbacks=[EarlyStopping(monitor='val_loss', patience=5)])

# Make predictions on the test data
predictions = model.predict(test_features)

# Plot the actual and predicted values
plt.plot(test_labels)
plt.plot(predictions)
plt.legend(['Actual', 'Predicted'])
plt.show()

Example Output

plaintext
Epoch 1/100
100/100 [==============================] - 0s 1ms/step - loss: 0.0000e+00 - val_loss: 0.0000e+00
Epoch 2/100
100/100 [==============================] - 0s 1ms/step - loss: 0.0000e+00 - val_loss: 0.0000e+00
...
Epoch 100/100
100/100 [==============================] - 0s 1ms/step - loss: 0.0000e+00 - val_loss: 0.0000e+00

Example Plot

plaintext
Actual
Predicted

Example Explanation

1. Loading the Dataset: The dataset is loaded from a CSV file named 'your_data.csv' into a Pandas DataFrame.

2. Splitting the Data: The data is split into training and testing sets using the `train_size` variable.

3. Defining the Model: The model is defined using the Keras API. It consists of an LSTM layer with 50 units and an input shape of (1, 1), followed by a dense layer with one output.

4. Compiling the Model: The model is compiled with the Adam optimizer and mean squared error loss.

5. Training the Model: The model is trained using the training data for 100 epochs. The validation data is used to monitor the model's performance during training.

6. Making Predictions: The model is used to make predictions on the test data.

7. Plotting the Results: The actual and predicted values are plotted for comparison.

This example demonstrates how to implement the DeepAR algorithm using TensorFlow for time series forecasting. The model is trained on the training data and then used to make predictions on the test data. The actual and predicted values are plotted for comparison, providing a visual representation of the model's performance[1][2][4].

Citations:
[1] https://www.geeksforgeeks.org/deepar-forecasting-algorithm/
[2] https://github.com/arrigonialberto86/deepar
[3] https://docs.aws.amazon.com/sagemaker/latest/dg/deepar.html
[4] https://www.tensorflow.org/tutorials/structured_data/time_series
[5] https://paperswithcode.com/paper/deepar-probabilistic-forecasting-with