Capstone Project: Time Series Forecasting
Duration: 10 min
This module covers the application of TensorFlow and Keras to build a time series forecasting model. Time series forecasting is crucial for various applications such as stock market prediction, weather forecasting, and demand forecasting. Understanding and implementing these techniques will enable you to create robust predictive models.
Understanding Time Series Data
Time series data is a sequence of data points collected or recorded at regular intervals. It is essential to preprocess this data to remove trends, seasonality, and noise. Techniques such as differencing, rolling statistics, and decomposition are commonly used. In this module, we will explore how to preprocess time series data and build a forecasting model using TensorFlow and Keras.
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
# Sample time series data
data = {'date': pd.date_range(start='1/1/2020', periods=100),
'value': np.random.randint(1,100,100)}
df = pd.DataFrame(data)
df.set_index('date', inplace=True)
# Preprocessing
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df['value'].values.reshape(-1,1))
# Creating training and test sets
train_size = int(len(scaled_data) * 0.8)
test_size = len(scaled_data) - train_size
train, test = scaled_data[0:train_size,:], scaled_data[train_size:len(scaled_data),:]Shape of training data: (80, 1)
Shape of test data: (20, 1)Building a Time Series Forecasting Model
Once the data is preprocessed, we can build a time series forecasting model using TensorFlow and Keras. We will use a simple LSTM (Long Short-Term Memory) model for this purpose. LSTMs are a type of recurrent neural network (RNN) that can learn long-term dependencies, making them suitable for time series data.
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
# Define the LSTM model
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(train.shape[1], 1)))
model.add(LSTM(50))
model.add(Dense(1))
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# Reshape data for LSTM
train = np.reshape(train, (train.shape[0], train.shape[1], 1))
test = np.reshape(test, (test.shape[0], test.shape[1], 1))
# Fit the model
model.fit(train, epochs=50, batch_size=32)💡 Tip: Ensure your time series data is stationary before feeding it into the LSTM model. Non-stationary data can lead to poor model performance.
❓ What is the primary purpose of preprocessing time series data?
❓ Which type of neural network is commonly used for time series forecasting?