Generate changepoints in time series¶
Goal¶
Insert abrupt level or slope changes at random or chosen positions of a time series.
In [1]:
Copied!
import badgers
badgers.__version__
import badgers
badgers.__version__
Out[1]:
'0.0.15'
In [2]:
Copied!
import numpy as np
import matplotlib.pyplot as plt
from badgers.generators.time_series.changepoints import RandomChangeInMeanGenerator
import numpy as np
import matplotlib.pyplot as plt
from badgers.generators.time_series.changepoints import RandomChangeInMeanGenerator
Setup random generator¶
In [3]:
Copied!
from numpy.random import default_rng
seed = 0
rng = default_rng(seed)
from numpy.random import default_rng
seed = 0
rng = default_rng(seed)
Generate data (gaussian white noise)¶
In [4]:
Copied!
X = rng.normal(size=(100, 2), scale=0.25)
X = rng.normal(size=(100, 2), scale=0.25)
In [5]:
Copied!
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6,4))
axes[0].plot(X[:, 0])
axes[1].plot(X[:, 1])
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6,4))
axes[0].plot(X[:, 0])
axes[1].plot(X[:, 1])
Out[5]:
[<matplotlib.lines.Line2D at 0x1b0379630e0>]
Randomly generate changepoints¶
In [6]:
Copied!
gen = RandomChangeInMeanGenerator(random_generator=rng)
gen = RandomChangeInMeanGenerator(random_generator=rng)
In [7]:
Copied!
Xt = gen.generate(X=X.copy(), max_change=2, min_change=-2, n_changepoints=5)
Xt = gen.generate(X=X.copy(), max_change=2, min_change=-2, n_changepoints=5)
In [8]:
Copied!
# verify: same shape, mean changes only after the changepoints
print('shape:', X.shape, '->', Xt.shape)
assert Xt.shape == X.shape
# gen.changepoints: list of (index, change) tuples
print('changepoints (index, change):', gen.changepoints)
# verify: same shape, mean changes only after the changepoints
print('shape:', X.shape, '->', Xt.shape)
assert Xt.shape == X.shape
# gen.changepoints: list of (index, change) tuples
print('changepoints (index, change):', gen.changepoints)
shape: (100, 2) -> (100, 2) changepoints (index, change): [(np.int64(57), np.float64(1.849692372497524)), (np.int64(22), np.float64(-1.710938937880493)), (np.int64(64), np.float64(-0.00010870536552598509)), (np.int64(56), np.float64(0.976389917130593)), (np.int64(87), np.float64(-1.2910930381013648))]
In [9]:
Copied!
fig, axes = plt.subplots(2, sharex=True, sharey=True, figsize=(6,6))
axes[0].plot(X)
axes[0].set_title('Original data')
axes[1].plot(Xt)
axes[1].set_title('Transformed data')
for cpt in gen.changepoints:
axes[1].vlines(cpt[0], ymin=Xt.min(), ymax=Xt.max(), ls='--', color='r')
plt.tight_layout();
fig, axes = plt.subplots(2, sharex=True, sharey=True, figsize=(6,6))
axes[0].plot(X)
axes[0].set_title('Original data')
axes[1].plot(Xt)
axes[1].set_title('Transformed data')
for cpt in gen.changepoints:
axes[1].vlines(cpt[0], ymin=Xt.min(), ymax=Xt.max(), ls='--', color='r')
plt.tight_layout();
Takeaways¶
- Changepoints are abrupt changes in level or slope at given positions.
gen.changepoints_records where the changes were inserted.