forecasting_energy_demand.mdx 6.49 KB
Newer Older
bailuo's avatar
readme  
bailuo committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
---
title: "Forecasting Energy Demand"
description: "Energy demand forecasting tutorial using TimeGPT AI. Step-by-step Python guide for electricity consumption prediction with 90% faster predictions and superior accuracy."
icon: "bolt"
---

## Introduction

Energy demand forecasting is critical for grid operations, resource allocation, and infrastructure planning. Despite advances in methods, predicting consumption remains challenging due to weather, economic activity, and consumer behavior.

This tutorial demonstrates how TimeGPT simplifies in-zone electricity forecasting while delivering superior accuracy and speed. We will use the [PJM Hourly Energy Consumption dataset](https://www.pjm.com/) covering five regions from October 2023 to September 2024.

### What You'll Learn

- How to load and prepare energy consumption data
- How to generate 4-day ahead forecasts with TimeGPT
- How to evaluate forecast accuracy using MAE and sMAPE
- How TimeGPT compares to deep learning models like N-HiTS

The procedures in this tutorial apply to many time series forecasting scenarios beyond energy demand.

## How to Use TimeGPT to Forecast Energy Demand

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Nixtla/nixtla/blob/main/nbs/docs/use-cases/3_electricity_demand.ipynb)


### Step 1: Initial Setup

Install and import required packages, then create a NixtlaClient instance to interact with TimeGPT.

```python
import time
import requests
import pandas as pd
from nixtla import NixtlaClient
from utilsforecast.losses import mae, smape
from utilsforecast.evaluation import evaluate

nixtla_client = NixtlaClient(
    api_key='my_api_key_provided_by_nixtla'  # Defaults to os.environ.get("NIXTLA_API_KEY")
)
```

### Step 2: Load Energy Consumption Data
Load the energy consumption dataset and convert datetime strings to timestamps.

```python
df = pd.read_csv('https://raw.githubusercontent.com/Nixtla/transfer-learning-time-series/refs/heads/main/datasets/pjm_in_zone.csv')
df['ds'] = pd.to_datetime(df['ds'])

# Examine the dataset
df.groupby('unique_id').head(2)
```

|       | unique_id   | ds                          | y          |
| ----- | ----------- | --------------------------- | ---------- |
| 0     | AP-AP       | 2023-10-01 04:00:00+00:00   | 4042.513   |
| 1     | AP-AP       | 2023-10-01 05:00:00+00:00   | 3850.067   |



Plot the data series to visualize seasonal patterns.

```python
nixtla_client.plot(
    df,
    max_insample_length=365
)
```

<Frame caption="Seasonal patterns in energy consumption showing daily and weekly cycles in PJM electricity demand data">
  ![Seasonal patterns in energy consumption showing daily and weekly cycles in PJM electricity demand data](https://raw.githubusercontent.com/Nixtla/nixtla/readme_docs/nbs/_docs/docs/use-cases/3_electricity_demand_files/figure-markdown_strict/cell-12-output-1.png)
</Frame>

### Step 3: Generate Energy Demand Forecasts with TimeGPT
We'll split our dataset into:
- A training/input set for model calibration
- A testing set (last 4 days) to validate performance

```python
# Prepare test (last 4 days) and input data
test_df = df.groupby('unique_id').tail(96)
input_df = df.groupby('unique_id').apply(lambda group: group.iloc[-1104:-96]).reset_index(drop=True)

# Make forecasts
start = time.time()

fcst_df = nixtla_client.forecast(
    df=input_df,
    h=96,
    level=[90],
    finetune_steps=10,
    finetune_loss='mae',
    model='timegpt-1-long-horizon',
    time_col='ds',
    target_col='y',
    id_col='unique_id'
)

end = time.time()
timegpt_duration = end - start

print(f"Time (TimeGPT): {timegpt_duration}")

# Visualize forecasts against actual values
nixtla_client.plot(
    test_df,
    fcst_df,
    models=['TimeGPT'],
    level=[90],
    time_col='ds',
    target_col='y'
)
```

<Frame caption="TimeGPT energy demand forecast with 90% confidence intervals compared to actual electricity consumption">
  ![TimeGPT energy demand forecast with 90% confidence intervals compared to actual electricity consumption](https://raw.githubusercontent.com/Nixtla/nixtla/readme_docs/nbs/_docs/docs/use-cases/3_electricity_demand_files/figure-markdown_strict/cell-15-output-1.png)
</Frame>

### Step 4: Evaluate Forecast Accuracy
Compute accuracy metrics (MAE and sMAPE) for TimeGPT.

```python
fcst_df['ds'] = pd.to_datetime(fcst_df['ds'])
test_df = pd.merge(test_df, fcst_df, 'left', ['unique_id', 'ds'])

evaluation = evaluate(test_df, [mae, smape], ["TimeGPT"], "y", "unique_id")
average_metrics = evaluation.groupby('metric')['TimeGPT'].mean()
average_metrics
```

### Step 5: Forecast with N-HiTS
For comparison, we train and forecast using the deep-learning model N-HiTS.

```python
from neuralforecast.core import NeuralForecast
from neuralforecast.models import NHITS

# Prepare training dataset by excluding the last 4 days
train_df = df.groupby('unique_id').apply(lambda group: group.iloc[:-96]).reset_index(drop=True)

models = [
    NHITS(h=96, input_size=480, scaler_type='robust', batch_size=16, valid_batch_size=8)
]

nf = NeuralForecast(models=models, freq='H')

start = time.time()
nf.fit(df=train_df)
nhits_preds = nf.predict()

end = time.time()

print(f"Time (N-HiTS): {end - start}")
```

### Step 6: Evaluate N-HiTS

Compute accuracy metrics (MAE and sMAPE) for N-HiTS.

```python
preds_df = pd.merge(test_df, nhits_preds, 'left', ['unique_id', 'ds'])

evaluation = evaluate(preds_df, [mae, smape], ["NHITS"], "y", "unique_id")
average_metrics = evaluation.groupby('metric')['NHITS'].mean()
print(average_metrics)
```


## Conclusion

TimeGPT demonstrates substantial performance improvements over N-HiTS across key metrics:

- **Accuracy**: 18.6% lower MAE (882.6 vs 1084.7)
- **Error Rate**: 31.1% lower sMAPE
- **Speed**: 90% faster predictions (4.3 seconds vs 44 seconds)

These results make TimeGPT a powerful tool for forecasting energy consumption and other time-series tasks where both accuracy and speed are critical.

Experiment with the parameters to further optimize performance for your specific use case.

## Related Tutorials

Ready to explore more forecasting applications? Check out these guides:

- [Bitcoin Price Prediction with TimeGPT](/use_cases/bitcoin_price_prediction) - Financial time series forecasting
- [Exogenous Variables Guide](/forecasting/exogenous-variables/numeric_features) - Improve forecasts with external data
- [Long Horizon Forecasting](/forecasting/model-version/longhorizon_model) - Extended forecast periods

Learn more about [TimeGPT capabilities](/introduction/introduction) for time series prediction.