Angad Sandhu
Search
Browse
On this page

S+P_Week_1_Lesson_2

#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Lesson 2

In the screencast for this lesson I go through a few scenarios for time series. This notebook contains the code for that with a few little extras! :)

Setup

!pip install -U tf-nightly-2.0-preview
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
def plot_series(time, series, format="-", start=0, end=None, label=None):
    plt.plot(time[start:end], series[start:end], format, label=label)
    plt.xlabel("Time")
    plt.ylabel("Value")
    if label:
        plt.legend(fontsize=14)
    plt.grid(True)

Trend and Seasonality

def trend(time, slope=0):
    return slope * time

Let's create a time series that just trends upward:

time = np.arange(4 * 365 + 1)
baseline = 10
series = trend(time, 0.1)

plt.figure(figsize=(10, 6))
plot_series(time, series)
plt.show()

Now let's generate a time series with a seasonal pattern:

def seasonal_pattern(season_time):
    """Just an arbitrary pattern, you can change it if you wish"""
    return np.where(season_time < 0.4,
                    np.cos(season_time * 2 * np.pi),
                    1 / np.exp(3 * season_time))

def seasonality(time, period, amplitude=1, phase=0):
    """Repeats the same pattern at each period"""
    season_time = ((time + phase) % period) / period
    return amplitude * seasonal_pattern(season_time)
baseline = 10
amplitude = 40
series = seasonality(time, period=365, amplitude=amplitude)

plt.figure(figsize=(10, 6))
plot_series(time, series)
plt.show()

Now let's create a time series with both trend and seasonality:

slope = 0.05
series = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)

plt.figure(figsize=(10, 6))
plot_series(time, series)
plt.show()

Noise

In practice few real-life time series have such a smooth signal. They usually have some noise, and the signal-to-noise ratio can sometimes be very low. Let's generate some white noise:

def white_noise(time, noise_level=1, seed=None):
    rnd = np.random.RandomState(seed)
    return rnd.randn(len(time)) * noise_level
noise_level = 5
noise = white_noise(time, noise_level, seed=42)

plt.figure(figsize=(10, 6))
plot_series(time, noise)
plt.show()

Now let's add this white noise to the time series:

series += noise

plt.figure(figsize=(10, 6))
plot_series(time, series)
plt.show()

All right, this looks realistic enough for now. Let's try to forecast it. We will split it into two periods: the training period and the validation period (in many cases, you would also want to have a test period). The split will be at time step 1000.

split_time = 1000
time_train = time[:split_time]
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
def autocorrelation(time, amplitude, seed=None):
    rnd = np.random.RandomState(seed)
    φ1 = 0.5
    φ2 = -0.1
    ar = rnd.randn(len(time) + 50)
    ar[:50] = 100
    for step in range(50, len(time) + 50):
        ar[step] += φ1 * ar[step - 50]
        ar[step] += φ2 * ar[step - 33]
    return ar[50:] * amplitude
def autocorrelation(time, amplitude, seed=None):
    rnd = np.random.RandomState(seed)
    φ = 0.8
    ar = rnd.randn(len(time) + 1)
    for step in range(1, len(time) + 1):
        ar[step] += φ * ar[step - 1]
    return ar[1:] * amplitude
series = autocorrelation(time, 10, seed=42)
plot_series(time[:200], series[:200])
plt.show()
Stored notebook output
series = autocorrelation(time, 10, seed=42) + trend(time, 2)
plot_series(time[:200], series[:200])
plt.show()
Stored notebook output
series = autocorrelation(time, 10, seed=42) + seasonality(time, period=50, amplitude=150) + trend(time, 2)
plot_series(time[:200], series[:200])
plt.show()
Stored notebook output
series = autocorrelation(time, 10, seed=42) + seasonality(time, period=50, amplitude=150) + trend(time, 2)
series2 = autocorrelation(time, 5, seed=42) + seasonality(time, period=50, amplitude=2) + trend(time, -1) + 550
series[200:] = series2[200:]
#series += noise(time, 30)
plot_series(time[:300], series[:300])
plt.show()
Stored notebook output
def impulses(time, num_impulses, amplitude=1, seed=None):
    rnd = np.random.RandomState(seed)
    impulse_indices = rnd.randint(len(time), size=10)
    series = np.zeros(len(time))
    for index in impulse_indices:
        series[index] += rnd.rand() * amplitude
    return series    
series = impulses(time, 10, seed=42)
plot_series(time, series)
plt.show()
Stored notebook output
def autocorrelation(source, φs):
    ar = source.copy()
    max_lag = len(φs)
    for step, value in enumerate(source):
        for lag, φ in φs.items():
            if step - lag > 0:
              ar[step] += φ * ar[step - lag]
    return ar
signal = impulses(time, 10, seed=42)
series = autocorrelation(signal, {1: 0.99})
plot_series(time, series)
plt.plot(time, signal, "k-")
plt.show()
Stored notebook output
signal = impulses(time, 10, seed=42)
series = autocorrelation(signal, {1: 0.70, 50: 0.2})
plot_series(time, series)
plt.plot(time, signal, "k-")
plt.show()
Stored notebook output
series_diff1 = series[1:] - series[:-1]
plot_series(time[1:], series_diff1)
Stored notebook output
import polars as pl


def overlap_autocorr(values, lag):
    # Pairwise Pearson: remove null/NaN after shifting, retaining infinities.
    pairs = pl.DataFrame({"value": values, "lagged": values.shift(lag)})
    return pairs.select(pl.corr(pl.col("value").fill_nan(None),
                                pl.col("lagged").fill_nan(None))).item()


def autocorrelation_plot(series, ax=None, **kwds):
    # Global centering uses every original position; missing values propagate.
    n = len(series)
    data = np.asarray(series, dtype=float)
    if ax is None:
        ax = plt.gca()
        ax.set_xlim(1, n)
        ax.set_ylim(-1.0, 1.0)
    mean = np.mean(data)
    c0 = np.sum((data - mean) ** 2) / n

    def r(h):
        return ((data[:n - h] - mean) * (data[h:] - mean)).sum() / n / c0

    x = np.arange(n) + 1
    y = [r(lag) for lag in x]
    z95 = 1.959963984540054
    z99 = 2.5758293035489004
    ax.axhline(y=z99 / np.sqrt(n), linestyle="--", color="grey")
    ax.axhline(y=z95 / np.sqrt(n), color="grey")
    ax.axhline(y=0.0, color="black")
    ax.axhline(y=-z95 / np.sqrt(n), color="grey")
    ax.axhline(y=-z99 / np.sqrt(n), linestyle="--", color="grey")
    ax.set_xlabel("Lag")
    ax.set_ylabel("Autocorrelation")
    ax.plot(x, y, **kwds)
    if "label" in kwds:
        ax.legend()
    ax.grid()
    return ax


autocorrelation_plot(series)
from statsmodels.tsa.arima_model import ARIMA

model = ARIMA(series, order=(5, 1, 0))
model_fit = model.fit(disp=0)
print(model_fit.summary())
                             ARIMA Model Results                              
==============================================================================
Dep. Variable:                    D.y   No. Observations:                 1460
Model:                 ARIMA(5, 1, 0)   Log Likelihood                2223.428
Method:                       css-mle   S.D. of innovations              0.053
Date:                Tue, 30 Jul 2019   AIC                          -4432.855
Time:                        17:40:55   BIC                          -4395.852
Sample:                             1   HQIC                         -4419.052
                                                                              
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const          0.0003      0.001      0.384      0.701      -0.001       0.002
ar.L1.D.y     -0.1235      0.026     -4.714      0.000      -0.175      -0.072
ar.L2.D.y     -0.1254      0.029     -4.333      0.000      -0.182      -0.069
ar.L3.D.y     -0.1089      0.029     -3.759      0.000      -0.166      -0.052
ar.L4.D.y     -0.0914      0.029     -3.162      0.002      -0.148      -0.035
ar.L5.D.y     -0.0774      0.029     -2.675      0.008      -0.134      -0.021
                                    Roots                                    
=============================================================================
                  Real          Imaginary           Modulus         Frequency
-----------------------------------------------------------------------------
AR.1            1.0145           -1.1311j            1.5194           -0.1336
AR.2            1.0145           +1.1311j            1.5194            0.1336
AR.3           -1.8173           -0.0000j            1.8173           -0.5000
AR.4           -0.6967           -1.6113j            1.7554           -0.3150
AR.5           -0.6967           +1.6113j            1.7554            0.3150
-----------------------------------------------------------------------------
def monthly_series(df):
    values = df.select("Date", "Monthly Mean Total Sunspot Number")
    if values["Date"].n_unique() != len(values):
        raise ValueError("cannot reindex duplicate Date labels")
    if values.is_empty():
        return values
    first, last = values["Date"].min(), values["Date"].max()
    # Roll only the generated calendar; original labels remain untouched.
    dates = pl.date_range(first.replace(day=1), last, interval="1mo", eager=True).dt.month_end()
    calendar = pl.DataFrame({"Date": dates}).filter(
        (pl.col("Date") >= first) & (pl.col("Date") <= last))
    return calendar.join(values, on="Date", how="left", validate="1:1", maintain_order="left")


df = pl.read_csv("sunspots.csv", try_parse_dates=True)
series = monthly_series(df)
series.head()
plt.figure(figsize=(12, 5))
plt.plot(series["Date"].to_numpy(), series["Monthly Mean Total Sunspot Number"].to_numpy())
plt.gca().set_xlabel("Date")
recent = series.filter(pl.col("Date") >= pl.date(1995, 1, 1))
plt.plot(recent["Date"].to_numpy(), recent["Monthly Mean Total Sunspot Number"].to_numpy())
plt.gca().set_xlabel("Date")
series_diff = series.with_columns(pl.col("Monthly Mean Total Sunspot Number").diff(1))
plt.plot(series_diff["Date"].to_numpy(), series_diff["Monthly Mean Total Sunspot Number"].to_numpy())
plt.gca().set_xlabel("Date")
plt.axis([0, 100, -50, 50])
autocorrelation_plot(series["Monthly Mean Total Sunspot Number"])
series_diff1 = series.with_columns(pl.col("Monthly Mean Total Sunspot Number").diff(1)).slice(1)
autocorrelation_plot(series_diff1["Monthly Mean Total Sunspot Number"])
double_diff = series_diff1.with_columns(pl.col("Monthly Mean Total Sunspot Number").diff(11 * 12)).slice(11 * 12 + 1)
autocorrelation_plot(double_diff["Monthly Mean Total Sunspot Number"])
plt.axis([0, 500, -0.1, 0.1])
autocorrelation_plot(series_diff1["Monthly Mean Total Sunspot Number"])
plt.axis([0, 50, -0.1, 0.1])
116.7 - 104.3
[overlap_autocorr(series["Monthly Mean Total Sunspot Number"], lag) for lag in range(1, 50)]

Polars CSV reader reference

pl.read_csv("sunspots.csv", try_parse_dates=True) reads CSV columns with an explicit Date column. Monthly calendar alignment joins generated month ends against unchanged original Date labels; duplicate labels are rejected. Install Polars for the tabular examples; NumPy and Matplotlib remain the existing plotting dependencies.

# Intentional correction: positional differences replace indexed subtraction,
# which aligned shared Date labels to zeros and left missing endpoints.
series_diff = series
for lag in range(50):
    series_diff = series_diff.with_columns(pl.col("Monthly Mean Total Sunspot Number").diff(1)).slice(1)

autocorrelation_plot(series_diff["Monthly Mean Total Sunspot Number"])
# Intentional correction: one positional difference, rather than aligned zeros.
series_diff1 = series.with_columns(pl.col("Monthly Mean Total Sunspot Number").diff(1)).slice(1)
autocorrs = [overlap_autocorr(series_diff1["Monthly Mean Total Sunspot Number"], lag) for lag in range(1, 60)]
plt.plot(autocorrs)
plt.show()

Browse the library