GridSearchCV¶
yohou.model_selection.search.GridSearchCV
¶
Bases: BaseSearchCV
Exhaustive search over specified parameter values for a forecaster.
Important members are fit, predict, predict_interval, observe, and rewind.
GridSearchCV implements a "fit" method that evaluates all parameter combinations specified in param_grid using time series cross-validation. The parameters of the forecaster are optimized by cross-validated grid-search over a parameter grid.
It also implements "predict", "predict_interval", "observe", "rewind", "observe_predict", and "observe_predict_interval" if the underlying forecaster supports these methods and refit=True.
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
forecaster
|
BaseForecaster
|
A forecaster object implementing the yohou forecaster interface with fit and predict methods. |
required |
param_grid
|
dict or list of dict
|
Dictionary with parameter names ( Examples:: |
required |
scoring
|
BaseScorer or dict of {str: BaseScorer}
|
Strategy to evaluate the performance of the cross-validated model on the test set. If a single BaseScorer instance, the same scorer is used for all folds and stored in cv_results_ with key 'score'. If a dict, keys are scorer names and values are BaseScorer instances.
This enables multi-metric evaluation. The Unlike sklearn, string scorer names are not supported. You must use yohou.metrics BaseScorer instances (e.g., MeanAbsoluteError(), RootMeanSquaredError()). Examples:: Note: For multi-metric evaluation with dict, cv_results_ will contain keys like 'mean_test_mae', 'rank_test_mae', 'mean_test_rmse', etc. |
None
|
n_jobs
|
int
|
Number of jobs to run in parallel.
|
None
|
refit
|
bool, str, or callable
|
Refit a forecaster using the best found parameters on the whole dataset. For multiple metric evaluation, this needs to be a Where there are considerations other than maximum score in
choosing a best forecaster, The refitted forecaster is made available at the Also for multiple metric evaluation, the attributes See Examples:: |
True
|
cv
|
int, BaseSplitter, or None
|
Determines the cross-validation splitting strategy. Possible inputs for cv are:
For time series data, typical splitters are:
|
None
|
verbose
|
int
|
Controls the verbosity: the higher, the more messages.
|
0
|
pre_dispatch
|
int or str
|
Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be:
|
'2*n_jobs'
|
error_score
|
'raise' or numeric
|
Value to assign to the score if an error occurs in forecaster fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error. |
np.nan
|
return_train_score
|
bool
|
If Computing training scores is used to get insights on how different parameter settings impact the overfitting/underfitting trade-off. However computing the scores on the training set can be computationally expensive and is not strictly required to select the parameters that yield the best generalization performance. |
False
|
Attributes¶
| Name | Type | Description |
|---|---|---|
cv_results_ |
dict of numpy (masked) ndarrays
|
A dict with keys as column headers and values as columns, that can be
imported into a pandas For instance the below given table:: will be represented by a cv_results_ dict of:: NOTE: The key The For multi-metric evaluation, the scores for all the scorers are
available in the |
best_forecaster_ |
BaseForecaster
|
Forecaster that was chosen by the search, i.e. forecaster which gave
highest score (or smallest loss if specified) on the left out data.
Not available if See |
best_score_ |
float
|
Mean cross-validated score of the best_forecaster_. Follows sklearn's sign convention: for For multi-metric evaluation, this is present only if This attribute is not available if |
best_params_ |
dict
|
Parameter setting that gave the best results on the hold out data. For multi-metric evaluation, this is present only if |
best_index_ |
int
|
The index (of the The dict at For multi-metric evaluation, this is present only if |
scorer_ |
BaseScorer or dict
|
Scorer function(s) used on the held out data to choose the best parameters for the model. For multi-metric evaluation, this attribute holds the validated
|
n_splits_ |
int
|
The number of cross-validation splits (folds/iterations). |
refit_time_ |
float
|
Seconds used for refitting the best forecaster on the whole dataset. This is present only if |
multimetric_ |
bool
|
Whether or not the scorers compute several metrics. |
n_features_in_ |
int
|
Number of features seen during |
feature_names_in_ |
ndarray of shape (n_features_in_,)
|
Names of features seen during |
See Also¶
RandomizedSearchCV: Randomized search over parameter distributions.ExpandingWindowSplitter: Cross-validation with expanding training windows.SlidingWindowSplitter: Cross-validation with sliding fixed-size windows.MeanAbsoluteError: Mean absolute error scorer.RootMeanSquaredError: Root mean squared error scorer.
Notes¶
The parameters selected are those that maximize the score of the left out data, unless an explicit scorer is passed in which case it is used instead.
If n_jobs was set to a value higher than one, the data is copied for each
point in the grid (and not n_jobs times). This is done for efficiency
reasons if individual jobs take very little time, but may raise errors if
the dataset is large and not enough memory is available. A workaround in
this case is to set pre_dispatch. Then, the memory is copied only
pre_dispatch many times. A reasonable value for pre_dispatch is
2 * n_jobs.
Examples¶
>>> from yohou.point import PointReductionForecaster
>>> from yohou.model_selection import GridSearchCV
>>> from yohou.metrics import MeanAbsoluteError
>>> import polars as pl
>>> from datetime import datetime, timedelta
>>> # Create sample data
>>> dates = [datetime(2020, 1, 1) + timedelta(days=i) for i in range(100)]
>>> y = pl.DataFrame({"time": dates, "value": range(100)})
>>> # Define parameter grid
>>> param_grid = {
... "estimator__alpha": [0.1, 1.0, 10.0],
... "feature_transformer__lags": [[1], [1, 2]],
... }
>>> # Single-metric search
>>> search = GridSearchCV(
... forecaster=PointReductionForecaster(),
... param_grid=param_grid,
... scoring=MeanAbsoluteError(),
... cv=3,
... )
>>> search.fit(y, forecasting_horizon=5)
>>> search.best_params_
>>> y_pred = search.predict(forecasting_horizon=5)
>>>
>>> # Multi-metric search
>>> from yohou.metrics import RootMeanSquaredError
>>> scoring = {"mae": MeanAbsoluteError(), "rmse": RootMeanSquaredError()}
>>> search = GridSearchCV(
... forecaster=PointReductionForecaster(),
... param_grid=param_grid,
... scoring=scoring,
... refit="mae", # Use 'mae' to select best parameters
... cv=3,
... )
>>> search.fit(y, forecasting_horizon=5)
>>> search.best_params_
>>> # cv_results_ contains both 'mean_test_mae' and 'mean_test_rmse'
>>> search.cv_results_["mean_test_mae"]
>>> search.cv_results_["mean_test_rmse"]
Source Code¶
Show/Hide source
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 | |
Tutorials¶
The following example notebooks use this component:
-
How to Tune Fourier Seasonality Terms
Data-Features
Explore how Fourier harmonic count affects seasonal fit quality, compare Fourier vs Pattern seasonality, and tune harmonics jointly with GridSearchCV.
-
How to Create a Custom Scorer
Evaluation-Search
Implement a custom point scorer with aggregation, panel support, and systematic testing.
-
How to Run Hyperparameter Search
Evaluation-Search
Tune forecaster hyperparameters with GridSearchCV and RandomizedSearchCV using temporal cross-validation splitters and result scatter visualisation.
-
How to Search Interval Forecaster Hyperparameters
Evaluation-Search
Tune interval forecaster parameters directly with interval metrics in GridSearchCV, including mixed point+interval multimetric search.
-
Forecasting Workflow
Getting-Started
Evaluate forecasters with cross-validation, search hyperparameters with GridSearchCV, and inspect residuals to diagnose model weaknesses.
-
Reduction Forecasting Walkthrough
Getting-Started
Walk through the full fit/predict/evaluate cycle with PointReductionForecaster, cross-validation, and grid search on a real dataset.
-
How to Run Panel Cross-Validation
Panel-Data
Time series cross-validation on panel data with GridSearchCV, selective group observation, rewind operations, and groupwise performance comparison.
-
Quickstart
Quickstart
Comprehensive end-to-end tour of yohou beyond the Getting Started tutorials, covering data loading, baseline forecasting, preprocessing pipelines, decomposition, cross-validation search, and interval prediction.
-
How to Visualize Model Selection Results
Visualization
Visualise CV fold geometry with expanding and sliding window splitters and hyperparameter search results with plot_splits and plot_cv_results_scatter.