timebasedcv
¶
Here are the top-level classes available in timebasedcv.
timebasedcv.core.TimeBasedSplit
¶
Bases: _CoreTimeBasedSplit
TimeBasedSplit
generates splits based on time periods, independently from the number of samples in each split.
It inherits from _CoreTimeBasedSplit
and it only implements the .split()
method and logic.
Differences with scikit-learn
TimeBasedSplit
is not compatible with
scikit-learn CV Splitters.
In fact, we have made the (opinioned) choice to:
- Return the sliced arrays from
.split(...)
, while scikit-learn CV Splitters return train and test indices of the split. - Require to pass the time series as input to
.split(...)
method, while scikit-learn CV Splitters require to provide onlyX, y, groups
to.split(...)
. - Such time series is used to generate the boolean masks with which we slice the original arrays into train and test for each split.
If you are looking for a class compatible with scikit-learn, check out our
TimeBasedCVSplitter
in the timebasedcv.sklearn
module.
A few examples on how splits are generated given the parameters. Let:
=
: train period unit*
: forecast period unit/
: gap period unit>
: stride period unit (absorbed in=
ifwindow="expanding"
)
Recall also that if stride
is not provided, it is set to forecast_horizon
:
train_size, forecast_horizon, gap, stride, window = (4, 3, 0, None, "rolling")
| ======= ***** |
| >>>>> ======= ***** |
| >>>>> ======= ***** |
| >>>>> ======= * |
train_size, forecast_horizon, gap, stride, window = (4, 3, 2, 2, "rolling")
| ======= /// ***** |
| >>> ======= /// ***** |
| >>> ======= /// ***** |
| >>> ======= /// *** |
train_size, forecast_horizon, gap, stride, window = (4, 3, 2, 2, "expanding")
| ======= /// ***** |
| =========== /// ***** |
| =============== /// ***** |
| =================== /// *** |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
frequency |
FrequencyUnit
|
The frequency (or time unit) of the time series. Must be one of "days", "seconds", "microseconds",
"milliseconds", "minutes", "hours", "weeks". These are the only valid values for the |
required |
train_size |
int
|
Defines the minimum number of time units required to be in the train set. |
required |
forecast_horizon |
int
|
Specifies the number of time units to forecast. |
required |
gap |
int
|
Sets the number of time units to skip between the end of the train set and the start of the forecast set. |
0
|
stride |
Union[int, None]
|
How many time unit to move forward after each split. If |
None
|
window |
WindowType
|
The type of window to use, either "rolling" or "expanding". |
'rolling'
|
mode |
ModeType
|
Determines in which orders the splits are generated, either "forward" (start to end) or "backward" (end to start). |
'forward'
|
Raises:
Type | Description |
---|---|
ValueError
|
|
TypeError
|
If |
Examples:
# Let's first generate some data
import pandas as pd
import numpy as np
RNG = np.random.default_rng(seed=42)
dates = pd.Series(pd.date_range("2023-01-01", "2023-01-31", freq="D"))
size = len(dates)
df = (
pd.concat(
[
pd.DataFrame(
{
"time": pd.date_range(start, end, periods=_size, inclusive="left"),
"a": RNG.normal(size=_size - 1),
"b": RNG.normal(size=_size - 1),
}
)
for start, end, _size in zip(dates[:-1], dates[1:], RNG.integers(2, 24, size - 1))
]
)
.reset_index(drop=True)
.assign(y=lambda t: t[["a", "b"]].sum(axis=1) + RNG.normal(size=t.shape[0]) / 25)
)
df.set_index("time").resample("D").agg(count=("y", np.size)).head(5)
Now let's run split the data with the provided TimeBasedSplit
instance:
from timebasedcv import TimeBasedSplit
tbs = TimeBasedSplit(
frequency="days",
train_size=10,
forecast_horizon=5,
gap=1,
stride=3
)
X, y, time_series = df.loc[:, ["a", "b"]], df["y"], df["time"]
for X_train, X_forecast, y_train, y_forecast in tbs.split(X, y, time_series=time_series):
print(f"Train: {X_train.shape}, Forecast: {X_forecast.shape}")
Train: (100, 2), Forecast: (51, 2)
Train: (114, 2), Forecast: (50, 2)
...
Train: (124, 2), Forecast: (40, 2)
Train: (137, 2), Forecast: (22, 2)
Source code in timebasedcv/core.py
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 |
|
split(*arrays, time_series, start_dt=None, end_dt=None, return_splitstate=False)
¶
Returns a generator of split arrays based on the time_series
.
The time_series
argument is split on split state values to create boolean masks for training - from train_
start (included) to train_end (excluded) - and forecast - from forecast_start (included) to forecast_end
(excluded). These masks are then used to index the arrays passed as arguments.
The start_dt
and end_dt
arguments can be used to specify the start and end of the time period. If provided,
they are used in place of the time_series.min()
and time_series.max()
respectively.
This is useful because the series does not necessarely starts from the first date and/or terminates in the last date of the time period of interest.
The return_splitstate
argument can be used to return the SplitState
instance for each split. This can be
useful if a particular logic has to be applied only on specific cases (e.g. if first day of the week, then
retrain a model).
By returning the split state, the user has the freedom and flexibility to apply any logic.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*arrays |
TensorLikeT
|
The arrays to split. Must have the same length as |
()
|
time_series |
SeriesLike[DateTimeLike]
|
The time series used to create boolean mask for splits. It is not required to be sorted, but it must support:
|
required |
start_dt |
NullableDatetime
|
The start of the time period. If provided, it is used in place of the |
None
|
end_dt |
NullableDatetime
|
The end of the time period. If provided,it is used in place of the |
None
|
return_splitstate |
bool
|
Whether to return the
|
False
|
Returns:
Type | Description |
---|---|
Generator[Union[Tuple[TensorLikeT, ...], Tuple[Tuple[TensorLikeT, ...], SplitState]], None, None]
|
A generator of tuples of arrays containing the training and forecast data.
Each tuple corresponds to a split generated by the |
Raises:
Type | Description |
---|---|
ValueError
|
|
Source code in timebasedcv/core.py
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 |
|
timebasedcv.core.ExpandingTimeSplit
¶
Bases: TimeBasedSplit
Alias for TimeBasedSplit(..., window="expanding")
.
Source code in timebasedcv/core.py
timebasedcv.core.RollingTimeSplit
¶
Bases: TimeBasedSplit
Alias for TimeBasedSplit(..., window="rolling")
.