Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,77 +1,3 @@
|
|
| 1 |
-
# ============================================================================
|
| 2 |
-
# TIME SERIES FORECASTING TUTORIAL: Prophet, ARIMA, and SARIMA
|
| 3 |
-
# ============================================================================
|
| 4 |
-
#
|
| 5 |
-
# WHAT IS TIME SERIES DATA?
|
| 6 |
-
# -------------------------
|
| 7 |
-
# Time series data is a sequence of measurements taken at regular intervals
|
| 8 |
-
# over time. Examples include:
|
| 9 |
-
# - Daily temperature readings
|
| 10 |
-
# - Hourly stock prices
|
| 11 |
-
# - Monthly sales figures
|
| 12 |
-
# - Minute-by-minute sensor readings (like in this code!)
|
| 13 |
-
#
|
| 14 |
-
# The goal of time series forecasting is to predict FUTURE values based on
|
| 15 |
-
# PAST patterns in the data.
|
| 16 |
-
#
|
| 17 |
-
# KEY CONCEPTS IN TIME SERIES:
|
| 18 |
-
# ----------------------------
|
| 19 |
-
# 1. TREND: The long-term direction of the data (going up, down, or staying flat)
|
| 20 |
-
# Example: Global temperatures have an upward trend over decades
|
| 21 |
-
#
|
| 22 |
-
# 2. SEASONALITY: Patterns that repeat at regular intervals
|
| 23 |
-
# Example: Ice cream sales are higher in summer, lower in winter (yearly cycle)
|
| 24 |
-
# Example: Electricity usage is higher during day, lower at night (daily cycle)
|
| 25 |
-
#
|
| 26 |
-
# 3. NOISE: Random fluctuations that don't follow any pattern
|
| 27 |
-
# Example: Unexpected spikes or dips due to random events
|
| 28 |
-
#
|
| 29 |
-
# THE THREE MODELS WE'LL USE:
|
| 30 |
-
# ---------------------------
|
| 31 |
-
# 1. ARIMA (AutoRegressive Integrated Moving Average)
|
| 32 |
-
# - A classic statistical model
|
| 33 |
-
# - Good for data with trends but NO seasonality
|
| 34 |
-
# - Uses past values and past errors to predict future
|
| 35 |
-
#
|
| 36 |
-
# 2. SARIMA (Seasonal ARIMA)
|
| 37 |
-
# - ARIMA + ability to handle seasonal patterns
|
| 38 |
-
# - Good for data with BOTH trends AND seasonality
|
| 39 |
-
# - NOTE: Can be SLOW on large datasets! (see PERFORMANCE section below)
|
| 40 |
-
#
|
| 41 |
-
# 3. Prophet (by Meta/Facebook)
|
| 42 |
-
# - A modern, user-friendly model
|
| 43 |
-
# - Automatically detects trends and multiple seasonalities
|
| 44 |
-
# - Great for business forecasting with daily/weekly/yearly patterns
|
| 45 |
-
#
|
| 46 |
-
# ============================================================================
|
| 47 |
-
# PERFORMANCE CONSIDERATIONS (IMPORTANT!)
|
| 48 |
-
# ============================================================================
|
| 49 |
-
# SARIMA can be VERY SLOW on large datasets because:
|
| 50 |
-
# - It needs to compute seasonal lags (looking back 's' time steps)
|
| 51 |
-
# - Computational complexity grows with data size AND seasonal period
|
| 52 |
-
# - A dataset of 4500 points with s=60 could take 20-60 minutes!
|
| 53 |
-
#
|
| 54 |
-
# SOLUTION: DOWNSAMPLING
|
| 55 |
-
# ----------------------
|
| 56 |
-
# Instead of using every data point, we can use every Nth point.
|
| 57 |
-
# Example: Instead of 4500 minute-by-minute readings, use 75 hourly averages
|
| 58 |
-
#
|
| 59 |
-
# This is like looking at a photo:
|
| 60 |
-
# - Full resolution (4500 pixels): Very detailed, slow to process
|
| 61 |
-
# - Thumbnail (75 pixels): Less detail, but captures the main patterns quickly
|
| 62 |
-
#
|
| 63 |
-
# For SARIMA in this code, we downsample to make it run in ~30 seconds
|
| 64 |
-
# instead of 20+ minutes, while still capturing the important patterns.
|
| 65 |
-
#
|
| 66 |
-
# Prophet and ARIMA are faster, so they use the full resolution data.
|
| 67 |
-
# ============================================================================
|
| 68 |
-
|
| 69 |
-
# ============================================================================
|
| 70 |
-
# REQUIRED PACKAGES
|
| 71 |
-
# ============================================================================
|
| 72 |
-
# Before running this code, install these packages:
|
| 73 |
-
# pip install prophet statsmodels pandas numpy matplotlib gradio
|
| 74 |
-
|
| 75 |
import numpy as np
|
| 76 |
import pandas as pd
|
| 77 |
import matplotlib.pyplot as plt
|
|
@@ -176,7 +102,7 @@ PROPHET_N_CHANGEPOINTS = 25
|
|
| 176 |
# ============================================================================
|
| 177 |
# DATA GENERATION
|
| 178 |
# ============================================================================
|
| 179 |
-
# We'll create SYNTHETIC
|
| 180 |
# This simulates what you might see in a space station or submarine!
|
| 181 |
#
|
| 182 |
# We generate 4 types of measurements:
|
|
@@ -186,40 +112,6 @@ PROPHET_N_CHANGEPOINTS = 25
|
|
| 186 |
# 4. PM (Particulate Matter in μg/m³) - tiny particles in the air
|
| 187 |
|
| 188 |
def smooth_noise(n_points, low, high, window=30):
|
| 189 |
-
"""
|
| 190 |
-
Generate smooth random noise.
|
| 191 |
-
|
| 192 |
-
WHY SMOOTH NOISE?
|
| 193 |
-
-----------------
|
| 194 |
-
Pure random noise looks very jagged and unrealistic. Real sensor data
|
| 195 |
-
usually has smoother variations. We achieve this by:
|
| 196 |
-
1. Generating random numbers between 'low' and 'high'
|
| 197 |
-
2. Applying a "moving average" to smooth them out
|
| 198 |
-
|
| 199 |
-
WHAT IS A MOVING AVERAGE?
|
| 200 |
-
-------------------------
|
| 201 |
-
Instead of using each random number directly, we replace it with the
|
| 202 |
-
average of itself and its neighbors. This removes sharp spikes.
|
| 203 |
-
|
| 204 |
-
Example with window=3:
|
| 205 |
-
Original: [10, 2, 8, 4, 6]
|
| 206 |
-
Smoothed: [6, 6.67, 4.67, 6, 5] (each value = average of 3 neighbors)
|
| 207 |
-
|
| 208 |
-
Parameters:
|
| 209 |
-
-----------
|
| 210 |
-
n_points : int
|
| 211 |
-
How many data points to generate
|
| 212 |
-
low : float
|
| 213 |
-
Minimum value for random numbers
|
| 214 |
-
high : float
|
| 215 |
-
Maximum value for random numbers
|
| 216 |
-
window : int
|
| 217 |
-
How many neighbors to average (bigger = smoother)
|
| 218 |
-
|
| 219 |
-
Returns:
|
| 220 |
-
--------
|
| 221 |
-
numpy array of smoothed random values
|
| 222 |
-
"""
|
| 223 |
# Generate random numbers from a UNIFORM distribution
|
| 224 |
# Uniform means every number between low and high is equally likely
|
| 225 |
raw_noise = np.random.uniform(low, high, n_points)
|
|
@@ -233,31 +125,6 @@ def smooth_noise(n_points, low, high, window=30):
|
|
| 233 |
|
| 234 |
|
| 235 |
def generate_mission_data(seed=42, n_points=4500):
|
| 236 |
-
"""
|
| 237 |
-
Generate synthetic environmental sensor data.
|
| 238 |
-
|
| 239 |
-
This creates realistic-looking data with:
|
| 240 |
-
- A TREND (gradual increase or decrease over time)
|
| 241 |
-
- SEASONALITY (repeating daily and weekly patterns)
|
| 242 |
-
- NOISE (random small variations)
|
| 243 |
-
|
| 244 |
-
Parameters:
|
| 245 |
-
-----------
|
| 246 |
-
seed : int
|
| 247 |
-
Random seed for reproducibility (same seed = same data every time)
|
| 248 |
-
n_points : int
|
| 249 |
-
How many minutes of data to generate (4500 = ~3 days)
|
| 250 |
-
|
| 251 |
-
Returns:
|
| 252 |
-
--------
|
| 253 |
-
pandas DataFrame with columns:
|
| 254 |
-
- ds: datetime timestamp
|
| 255 |
-
- Time_min: minute number (0, 1, 2, ...)
|
| 256 |
-
- O2_percent: oxygen percentage
|
| 257 |
-
- CO2_ppm: carbon dioxide in parts per million
|
| 258 |
-
- VOCs_ppb: volatile organic compounds in parts per billion
|
| 259 |
-
- Particulates_ugm3: particulate matter in micrograms per cubic meter
|
| 260 |
-
"""
|
| 261 |
# Set random seed so we get the same "random" data each time
|
| 262 |
# This is important for reproducibility in science!
|
| 263 |
np.random.seed(seed)
|
|
@@ -357,33 +224,6 @@ def generate_mission_data(seed=42, n_points=4500):
|
|
| 357 |
# ============================================================================
|
| 358 |
|
| 359 |
def downsample_series(series, factor):
|
| 360 |
-
"""
|
| 361 |
-
Reduce the number of data points by averaging every 'factor' points.
|
| 362 |
-
|
| 363 |
-
WHY DOWNSAMPLE?
|
| 364 |
-
---------------
|
| 365 |
-
Some algorithms (like SARIMA) are very slow on large datasets.
|
| 366 |
-
Downsampling reduces the data size while preserving the overall pattern.
|
| 367 |
-
|
| 368 |
-
HOW IT WORKS:
|
| 369 |
-
-------------
|
| 370 |
-
Original (factor=3): [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
| 371 |
-
Downsampled: [2, 5, 8] (average of each group of 3)
|
| 372 |
-
|
| 373 |
-
This is similar to how video compression works - instead of storing
|
| 374 |
-
every frame, store key frames that capture the important information.
|
| 375 |
-
|
| 376 |
-
Parameters:
|
| 377 |
-
-----------
|
| 378 |
-
series : pandas Series or numpy array
|
| 379 |
-
The original data
|
| 380 |
-
factor : int
|
| 381 |
-
How many points to combine into one (e.g., 60 = hourly from minute data)
|
| 382 |
-
|
| 383 |
-
Returns:
|
| 384 |
-
--------
|
| 385 |
-
numpy array of downsampled values
|
| 386 |
-
"""
|
| 387 |
arr = np.array(series)
|
| 388 |
# Calculate how many complete groups we can make
|
| 389 |
n_groups = len(arr) // factor
|
|
@@ -396,36 +236,6 @@ def downsample_series(series, factor):
|
|
| 396 |
|
| 397 |
|
| 398 |
def upsample_predictions(predictions, factor, target_length):
|
| 399 |
-
"""
|
| 400 |
-
Expand predictions back to original resolution using interpolation.
|
| 401 |
-
|
| 402 |
-
WHY UPSAMPLE?
|
| 403 |
-
-------------
|
| 404 |
-
After SARIMA makes predictions on downsampled data, we need to
|
| 405 |
-
"stretch" those predictions back to match the original data length
|
| 406 |
-
for fair comparison.
|
| 407 |
-
|
| 408 |
-
HOW IT WORKS:
|
| 409 |
-
-------------
|
| 410 |
-
Downsampled predictions: [10, 20, 30] (3 points)
|
| 411 |
-
Upsampled (factor=3): [10, 13, 17, 20, 23, 27, 30, ...] (9 points)
|
| 412 |
-
|
| 413 |
-
We use LINEAR INTERPOLATION - drawing straight lines between points
|
| 414 |
-
and filling in the values along those lines.
|
| 415 |
-
|
| 416 |
-
Parameters:
|
| 417 |
-
-----------
|
| 418 |
-
predictions : numpy array
|
| 419 |
-
Predictions from the downsampled model
|
| 420 |
-
factor : int
|
| 421 |
-
The downsampling factor used
|
| 422 |
-
target_length : int
|
| 423 |
-
The desired output length (original test set size)
|
| 424 |
-
|
| 425 |
-
Returns:
|
| 426 |
-
--------
|
| 427 |
-
numpy array of upsampled predictions matching target_length
|
| 428 |
-
"""
|
| 429 |
# Create x-coordinates for original predictions
|
| 430 |
x_original = np.arange(len(predictions)) * factor
|
| 431 |
|
|
@@ -443,42 +253,6 @@ def upsample_predictions(predictions, factor, target_length):
|
|
| 443 |
# ============================================================================
|
| 444 |
|
| 445 |
def train_prophet(train_df, test_df):
|
| 446 |
-
"""
|
| 447 |
-
Train a Prophet model and make predictions.
|
| 448 |
-
|
| 449 |
-
HOW PROPHET WORKS (Simplified):
|
| 450 |
-
-------------------------------
|
| 451 |
-
Prophet breaks down the time series into components:
|
| 452 |
-
|
| 453 |
-
y(t) = trend(t) + seasonality(t) + holidays(t) + error(t)
|
| 454 |
-
|
| 455 |
-
1. TREND: Prophet fits a piecewise linear trend (like connecting dots
|
| 456 |
-
with straight lines, but allowing the slope to change at "changepoints")
|
| 457 |
-
|
| 458 |
-
2. SEASONALITY: Prophet uses Fourier series (fancy sine/cosine waves)
|
| 459 |
-
to capture daily, weekly, and yearly patterns
|
| 460 |
-
|
| 461 |
-
3. HOLIDAYS: Prophet can account for special events (we don't use this here)
|
| 462 |
-
|
| 463 |
-
4. ERROR: The random noise that can't be predicted
|
| 464 |
-
|
| 465 |
-
Prophet is great because:
|
| 466 |
-
- It handles missing data well
|
| 467 |
-
- It automatically detects seasonality
|
| 468 |
-
- It's robust to outliers
|
| 469 |
-
- It's easy to use!
|
| 470 |
-
|
| 471 |
-
Parameters:
|
| 472 |
-
-----------
|
| 473 |
-
train_df : DataFrame
|
| 474 |
-
Training data with 'ds' (datetime) and 'y' (value) columns
|
| 475 |
-
test_df : DataFrame
|
| 476 |
-
Test data with 'ds' column (we'll predict 'y' values)
|
| 477 |
-
|
| 478 |
-
Returns:
|
| 479 |
-
--------
|
| 480 |
-
numpy array of predictions for the test period
|
| 481 |
-
"""
|
| 482 |
# Create and configure the Prophet model
|
| 483 |
model = Prophet(
|
| 484 |
growth="linear", # Use linear trend (not logistic)
|
|
@@ -505,51 +279,6 @@ def train_prophet(train_df, test_df):
|
|
| 505 |
|
| 506 |
|
| 507 |
def train_arima(train_series, test_len):
|
| 508 |
-
"""
|
| 509 |
-
Train an ARIMA model and make predictions.
|
| 510 |
-
|
| 511 |
-
HOW ARIMA WORKS (Simplified):
|
| 512 |
-
-----------------------------
|
| 513 |
-
ARIMA stands for: AutoRegressive Integrated Moving Average
|
| 514 |
-
|
| 515 |
-
Let's break it down:
|
| 516 |
-
|
| 517 |
-
1. AR (AutoRegressive): Predict using past values
|
| 518 |
-
"Tomorrow's temperature depends on today's temperature"
|
| 519 |
-
|
| 520 |
-
Formula: y(t) = c + φ1*y(t-1) + φ2*y(t-2) + ... + error
|
| 521 |
-
|
| 522 |
-
Where φ (phi) are learned weights for each past value
|
| 523 |
-
|
| 524 |
-
2. I (Integrated): Differencing to remove trends
|
| 525 |
-
Instead of predicting y(t), we predict the CHANGE: y(t) - y(t-1)
|
| 526 |
-
|
| 527 |
-
This converts: [100, 102, 105, 109] (trending up)
|
| 528 |
-
Into: [2, 3, 4] (the differences - no trend!)
|
| 529 |
-
|
| 530 |
-
3. MA (Moving Average): Predict using past errors
|
| 531 |
-
"If I was wrong yesterday, adjust today's prediction"
|
| 532 |
-
|
| 533 |
-
Formula: y(t) = c + θ1*e(t-1) + θ2*e(t-2) + ... + error
|
| 534 |
-
|
| 535 |
-
Where e is the error (actual - predicted) from past forecasts
|
| 536 |
-
|
| 537 |
-
ARIMA combines all three: AR + I + MA
|
| 538 |
-
|
| 539 |
-
LIMITATION: Basic ARIMA doesn't handle seasonality well!
|
| 540 |
-
(That's why we have SARIMA)
|
| 541 |
-
|
| 542 |
-
Parameters:
|
| 543 |
-
-----------
|
| 544 |
-
train_series : pandas Series
|
| 545 |
-
Historical data to train on
|
| 546 |
-
test_len : int
|
| 547 |
-
How many future points to predict
|
| 548 |
-
|
| 549 |
-
Returns:
|
| 550 |
-
--------
|
| 551 |
-
numpy array of predictions
|
| 552 |
-
"""
|
| 553 |
try:
|
| 554 |
# Create and fit the ARIMA model
|
| 555 |
model = ARIMA(train_series, order=ARIMA_ORDER)
|
|
@@ -569,50 +298,6 @@ def train_arima(train_series, test_len):
|
|
| 569 |
|
| 570 |
|
| 571 |
def train_sarima(train_series, test_len, original_test_len):
|
| 572 |
-
"""
|
| 573 |
-
Train a SARIMA model on DOWNSAMPLED data for speed, then upsample predictions.
|
| 574 |
-
|
| 575 |
-
HOW SARIMA WORKS (Simplified):
|
| 576 |
-
------------------------------
|
| 577 |
-
SARIMA = Seasonal ARIMA = ARIMA + Seasonal components
|
| 578 |
-
|
| 579 |
-
It adds seasonal versions of AR, I, and MA:
|
| 580 |
-
|
| 581 |
-
Regular ARIMA(p,d,q) handles: trends and short-term patterns
|
| 582 |
-
Seasonal (P,D,Q,s) handles: repeating seasonal patterns
|
| 583 |
-
|
| 584 |
-
Example with daily temperature (s=365 for yearly seasonality):
|
| 585 |
-
- Regular AR: "Today's temp depends on yesterday's temp"
|
| 586 |
-
- Seasonal AR: "Today's temp also depends on this day LAST YEAR"
|
| 587 |
-
|
| 588 |
-
The seasonal differencing (D) removes seasonal trends:
|
| 589 |
-
Instead of: y(t) - y(t-1) [regular differencing]
|
| 590 |
-
We use: y(t) - y(t-s) [seasonal differencing]
|
| 591 |
-
|
| 592 |
-
This removes patterns like "summer is always hotter than winter"
|
| 593 |
-
|
| 594 |
-
SPEED OPTIMIZATION:
|
| 595 |
-
-------------------
|
| 596 |
-
SARIMA is slow on large datasets. To speed it up:
|
| 597 |
-
1. We DOWNSAMPLE the training data (e.g., minute → hourly)
|
| 598 |
-
2. Train on the smaller dataset (much faster!)
|
| 599 |
-
3. UPSAMPLE the predictions back to original resolution
|
| 600 |
-
|
| 601 |
-
This trades a small amount of accuracy for a HUGE speed improvement.
|
| 602 |
-
|
| 603 |
-
Parameters:
|
| 604 |
-
-----------
|
| 605 |
-
train_series : pandas Series
|
| 606 |
-
DOWNSAMPLED historical data to train on
|
| 607 |
-
test_len : int
|
| 608 |
-
How many DOWNSAMPLED points to predict
|
| 609 |
-
original_test_len : int
|
| 610 |
-
Original test length (for upsampling predictions)
|
| 611 |
-
|
| 612 |
-
Returns:
|
| 613 |
-
--------
|
| 614 |
-
numpy array of predictions (upsampled to original resolution)
|
| 615 |
-
"""
|
| 616 |
try:
|
| 617 |
# Create and fit the SARIMA model (called SARIMAX in statsmodels)
|
| 618 |
# The X in SARIMAX stands for "eXogenous variables" (external factors)
|
|
@@ -655,28 +340,6 @@ def train_sarima(train_series, test_len, original_test_len):
|
|
| 655 |
# ============================================================================
|
| 656 |
|
| 657 |
def run_prediction(seed, model_choice):
|
| 658 |
-
"""
|
| 659 |
-
Main function that orchestrates the entire prediction pipeline.
|
| 660 |
-
|
| 661 |
-
Steps:
|
| 662 |
-
1. Generate synthetic data
|
| 663 |
-
2. Split into training and test sets
|
| 664 |
-
3. Train selected model(s)
|
| 665 |
-
4. Make predictions
|
| 666 |
-
5. Calculate accuracy metrics
|
| 667 |
-
6. Create visualizations
|
| 668 |
-
|
| 669 |
-
Parameters:
|
| 670 |
-
-----------
|
| 671 |
-
seed : int
|
| 672 |
-
Random seed for data generation
|
| 673 |
-
model_choice : str
|
| 674 |
-
Which model to use: "Prophet", "ARIMA", "SARIMA", or "All"
|
| 675 |
-
|
| 676 |
-
Returns:
|
| 677 |
-
--------
|
| 678 |
-
tuple: (metrics_dataframe, seed_string, matplotlib_figure)
|
| 679 |
-
"""
|
| 680 |
# ========================================================================
|
| 681 |
# STEP 1: Generate Data
|
| 682 |
# ========================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import numpy as np
|
| 2 |
import pandas as pd
|
| 3 |
import matplotlib.pyplot as plt
|
|
|
|
| 102 |
# ============================================================================
|
| 103 |
# DATA GENERATION
|
| 104 |
# ============================================================================
|
| 105 |
+
# We'll create SYNTHETIC environmental sensor data
|
| 106 |
# This simulates what you might see in a space station or submarine!
|
| 107 |
#
|
| 108 |
# We generate 4 types of measurements:
|
|
|
|
| 112 |
# 4. PM (Particulate Matter in μg/m³) - tiny particles in the air
|
| 113 |
|
| 114 |
def smooth_noise(n_points, low, high, window=30):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
# Generate random numbers from a UNIFORM distribution
|
| 116 |
# Uniform means every number between low and high is equally likely
|
| 117 |
raw_noise = np.random.uniform(low, high, n_points)
|
|
|
|
| 125 |
|
| 126 |
|
| 127 |
def generate_mission_data(seed=42, n_points=4500):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
# Set random seed so we get the same "random" data each time
|
| 129 |
# This is important for reproducibility in science!
|
| 130 |
np.random.seed(seed)
|
|
|
|
| 224 |
# ============================================================================
|
| 225 |
|
| 226 |
def downsample_series(series, factor):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
arr = np.array(series)
|
| 228 |
# Calculate how many complete groups we can make
|
| 229 |
n_groups = len(arr) // factor
|
|
|
|
| 236 |
|
| 237 |
|
| 238 |
def upsample_predictions(predictions, factor, target_length):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
# Create x-coordinates for original predictions
|
| 240 |
x_original = np.arange(len(predictions)) * factor
|
| 241 |
|
|
|
|
| 253 |
# ============================================================================
|
| 254 |
|
| 255 |
def train_prophet(train_df, test_df):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
# Create and configure the Prophet model
|
| 257 |
model = Prophet(
|
| 258 |
growth="linear", # Use linear trend (not logistic)
|
|
|
|
| 279 |
|
| 280 |
|
| 281 |
def train_arima(train_series, test_len):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
try:
|
| 283 |
# Create and fit the ARIMA model
|
| 284 |
model = ARIMA(train_series, order=ARIMA_ORDER)
|
|
|
|
| 298 |
|
| 299 |
|
| 300 |
def train_sarima(train_series, test_len, original_test_len):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
try:
|
| 302 |
# Create and fit the SARIMA model (called SARIMAX in statsmodels)
|
| 303 |
# The X in SARIMAX stands for "eXogenous variables" (external factors)
|
|
|
|
| 340 |
# ============================================================================
|
| 341 |
|
| 342 |
def run_prediction(seed, model_choice):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
# ========================================================================
|
| 344 |
# STEP 1: Generate Data
|
| 345 |
# ========================================================================
|