Evaluation
amltk.sklearn.evaluation
#
This module contains the cross-validation evaluation protocol.
This protocol will create a cross-validation task to be used in parallel and optimization. It represents a typical cross-validation evaluation for sklearn, handling some of the minor nuances of sklearn and it's interaction with optimization and parallelization.
Please see CVEvaluation
for more
information on usage.
PostSplitSignature
module-attribute
#
PostSplitSignature: TypeAlias = Callable[
[Trial, int, "CVEvaluation.PostSplitInfo"],
"CVEvaluation.PostSplitInfo",
]
A type alias for the post split callback signature.
Please see PostSplitInfo
for more information on the information available to this callback.
TaskTypeName
module-attribute
#
TaskTypeName: TypeAlias = Literal[
"binary",
"multiclass",
"multilabel-indicator",
"multiclass-multioutput",
"continuous",
"continuous-multioutput",
]
A type alias for the task type name as defined by sklearn.
XLike
module-attribute
#
A type alias for X input data type as defined by sklearn.
YLike
module-attribute
#
A type alias for y input data type as defined by sklearn.
CVEarlyStoppingProtocol
#
Bases: Protocol
Protocol for early stopping in cross-validation.
You class should implement the
update()
and should_stop()
methods. You can optionally inherit from this class but it is not required.
class MyStopper:
def update(self, report: Trial.Report) -> None:
if report.status is Trial.Status.SUCCESS:
# ... do some update logic
def should_stop(self, trial: Trial, split_infos: list[CVEvaluation.PostSplitInfo]) -> bool | Exception:
mean_scores_up_to_current_split = np.mean([i.val_scores["accuracy"] for i in split_infos])
if mean_scores_up_to_current_split > 0.9:
return False # Keep going
else:
return True # Stop evaluating
should_stop
#
should_stop(
trial: Trial, scores: SplitScores
) -> bool | Exception
Determines whether the cross-validation should stop early.
PARAMETER | DESCRIPTION |
---|---|
trial |
The trial that is currently being evaluated.
TYPE:
|
scores |
The scores from the evlauated splits.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
bool | Exception
|
|
Source code in src/amltk/sklearn/evaluation.py
update
#
update(report: Report) -> None
Update the protocol with a new report.
This will be called when a trial has been completed, either successfully
or failed. You can check for successful trials by using
report.status
.
PARAMETER | DESCRIPTION |
---|---|
report |
The report from the trial.
TYPE:
|
Source code in src/amltk/sklearn/evaluation.py
CVEvaluation
#
CVEvaluation(
X: XLike,
y: YLike,
*,
X_test: XLike | None = None,
y_test: YLike | None = None,
splitter: (
Literal["holdout", "cv"]
| BaseShuffleSplit
| BaseCrossValidator
) = "cv",
n_splits: int = 5,
holdout_size: float = 0.33,
train_score: bool = False,
store_models: bool = False,
rebalance_if_required_for_stratified_splitting: (
bool | None
) = None,
additional_scorers: Mapping[str, _Scorer] | None = None,
random_state: Seed | None = None,
params: Mapping[str, Any] | None = None,
task_hint: (
TaskTypeName
| Literal["classification", "regression", "auto"]
) = "auto",
working_dir: str | Path | PathBucket | None = None,
on_error: Literal["raise", "fail"] = "fail",
post_split: PostSplitSignature | None = None,
post_processing: (
Callable[[Report, Node, CompleteEvalInfo], Report]
| None
) = None,
post_processing_requires_models: bool = False
)
Bases: Emitter
Cross-validation evaluation protocol.
This protocol will create a cross-validation task to be used in parallel and optimization. It represents a typical cross-validation evaluation for sklearn.
Aside from the init parameters, it expects:
* The pipeline you are optimizing can be made into a sklearn.pipeline.Pipeline
calling .build("sklearn")
.
* The seed for the trial will be passed as a param to
.configure()
. If you have a component
that accepts a random_state
parameter, you can use a
request()
so that it will be seeded correctly.
from amltk.sklearn import CVEvaluation
from amltk.pipeline import Component, request
from amltk.optimization import Metric
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import get_scorer
from sklearn.datasets import load_iris
from pathlib import Path
pipeline = Component(
RandomForestClassifier,
config={"random_state": request("random_state")},
space={"n_estimators": (10, 100), "criterion": ["gini", "entropy"]},
)
working_dir = Path("./some-path")
X, y = load_iris(return_X_y=True)
evaluator = CVEvaluation(
X,
y,
n_splits=3,
splitter="cv",
additional_scorers={"roc_auc": get_scorer("roc_auc_ovr")},
store_models=False,
train_score=True,
working_dir=working_dir,
)
history = pipeline.optimize(
target=evaluator.fn,
metric=Metric("accuracy", minimize=False, bounds=(0, 1)),
working_dir=working_dir,
max_trials=1,
)
print(history.df())
evaluator.bucket.rmdir() # Cleanup
If you need to pass specific configuration items to your pipeline during
configuration, you can do so using a request()
in the config of your pipeline.
In the below example, we allow the pipeline to be configured with "n_jobs"
and pass it in to the CVEvalautor
using the params
argument.
from amltk.sklearn import CVEvaluation
from amltk.pipeline import Component, request
from amltk.optimization import Metric
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import get_scorer
from sklearn.datasets import load_iris
from pathlib import Path
working_dir = Path("./some-path")
X, y = load_iris(return_X_y=True)
pipeline = Component(
RandomForestClassifier,
config={
"random_state": request("random_state"),
# Allow it to be configured with n_jobs
"n_jobs": request("n_jobs", default=None)
},
space={"n_estimators": (10, 100), "criterion": ["gini", "entropy"]},
)
evaluator = CVEvaluation(
X,
y,
working_dir=working_dir,
# Use the `configure` keyword in params to pass to the `n_jobs`
# Anything in the pipeline requesting `n_jobs` will get the value
params={"configure": {"n_jobs": 2}}
)
history = pipeline.optimize(
target=evaluator.fn,
metric=Metric("accuracy"),
working_dir=working_dir,
max_trials=1,
)
print(history.df())
evaluator.bucket.rmdir() # Cleanup
CV Early Stopping
To see more about early stopping, please see
CVEvaluation.cv_early_stopping_plugin()
.
PARAMETER | DESCRIPTION |
---|---|
X |
The features to use for training.
TYPE:
|
y |
The target to use for training.
TYPE:
|
X_test |
The features to use for testing. If provided, all
scorers will be calculated on this data as well.
Must be provided with Scorer params for test scoring Due to nuances of sklearn's metadata routing, if you need to provide
parameters to the scorer for the test data, you can prefix these
with
TYPE:
|
y_test |
The target to use for testing. If provided, all
scorers will be calculated on this data as well.
Must be provided with
TYPE:
|
splitter |
The cross-validation splitter to use. This can be either
TYPE:
|
n_splits |
The number of cross-validation splits to use.
This argument will be ignored if
TYPE:
|
holdout_size |
The size of the holdout set to use. This argument
will be ignored if
TYPE:
|
train_score |
Whether to score on the training data as well. This will take extra time as predictions will be made on the training data as well.
TYPE:
|
store_models |
Whether to store the trained models in the trial.
TYPE:
|
rebalance_if_required_for_stratified_splitting |
Whether the CVEvaluator
should rebalance the training data to allow for stratified splitting.
* If
TYPE:
|
additional_scorers |
Additional scorers to use. |
random_state |
The random state to use for the cross-validation
TYPE:
|
params |
Parameters to pass to the estimator, splitter or scorers. See scikit-learn.org/stable/metadata_routing.html for more information. You may also additionally include the following as dictionarys:
Scorer params for test scoring Due to nuances of sklearn's metadata routing, if you need to provide
parameters to the scorer for the test data, you must prefix these
with |
task_hint |
A string indicating the task type matching those
use by sklearn's You can also provide If not provided, this will be inferred from the target data. If you know this value, it is recommended to provide it as sometimes the target is ambiguous and sklearn may infer incorrectly.
TYPE:
|
working_dir |
The directory to use for storing data. If not provided,
a temporary directory will be used. If provided as a string
or a
TYPE:
|
on_error |
What to do if an error occurs in the task. This can be
either
TYPE:
|
post_split |
If provided, this callable will be called with a
For example, this could be useful if you'd like to save out-of-fold predictions for later use.
Run in the worker This callable will be pickled and sent to the worker that is executing an evaluation. This means that you should mitigate relying on any large objects if your callalbe is an object, as the object will get pickled and sent to the worker. This also means you can not rely on information obtained from other trials as when sending the callable to a worker, it is no longer updatable from the main process. You should also avoid holding on to references to either the model
or large data that is passed in
This parameter should primarily be used for callables that rely solely on the output of the current trial and wish to store/add additional information to the trial itself.
TYPE:
|
post_processing |
If provided, this callable will be called with all of the
evaluated splits and the final report that will be returned.
This can be used to do things such as augment the final scores
if required, cleanup any resources or any other tasks that should be
run after the evaluation has completed. This will be handed a
This can be useful when you'd like to report the score of a bagged model, i.e. an ensemble of all validation models. Another example is if you'd like to add to the summary, the score of what the model would be if refit on all the data.
Run in the worker This callable will be pickled and sent to the worker that is executing an evaluation. This means that you should mitigate relying on any large objects if your callalbe is an object, as the object will get pickled and sent to the worker. This also means you can not rely on information obtained from other trials as when sending the callable to a worker, it is no longer updatable from the main process. This parameter should primarily be used for callables that will augment the report or what is stored with the trial. It should rely solely on the current trial to prevent unexpected issues.
TYPE:
|
post_processing_requires_models |
Whether the
TYPE:
|
Source code in src/amltk/sklearn/evaluation.py
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 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 |
|
LARGE_PARAM_HEURISTIC
class-attribute
#
LARGE_PARAM_HEURISTIC: int = 100
Any item in params=
which is greater will be stored to disk when sent to the
worker.
When launching tasks, pickling and streaming large data to tasks can be expensive.
This parameter checks if the object is large and if so, stores it to disk and
gives it to the task as a Stored
object instead.
Please feel free to overwrite this class variable as needed.
PARAM_EXTENSION_MAPPING
class-attribute
#
PARAM_EXTENSION_MAPPING: dict[type[Sized], str] = {
ndarray: "npy",
DataFrame: "pdpickle",
Series: "pdpickle",
}
The mapping from types to extensions in
params
.
If the parameter is an instance of one of these types, and is larger than
LARGE_PARAM_HEURISTIC
,
then it will be stored to disk and loaded back up in the task.
Please feel free to overwrite this class variable as needed.
SPLIT_EVALUATED
class-attribute
instance-attribute
#
Event that is emitted when a split has been evaluated.
Only emitted if the evaluator plugin is being used.
TMP_DIR_PREFIX
class-attribute
#
TMP_DIR_PREFIX: str = 'amltk-sklearn-cv-evaluation-data-'
Prefix for temporary directory names.
This is only used when working_dir
is not specified. If not specified
you can control the tmp dir location by setting the TMPDIR
environment variable. By default this is /tmp
.
When using a temporary directory, it will be deleted by default,
controlled by the delete_working_dir=
argument.
additional_scorers
instance-attribute
#
additional_scorers: Mapping[str, _Scorer] | None = (
additional_scorers
)
Additional scorers that will be used.
bucket
instance-attribute
#
bucket: PathBucket = bucket
The bucket to use for storing data.
For cleanup, you can call
bucket.rmdir()
.
params
instance-attribute
#
Parameters to pass to the estimator, splitter or scorers.
Please see scikit-learn.org/stable/metadata_routing.html for more.
splitter
instance-attribute
#
splitter: BaseShuffleSplit | BaseCrossValidator = splitter
The splitter that will be used.
store_models
instance-attribute
#
store_models: bool = store_models
Whether models will be stored in the trial.
train_score
instance-attribute
#
train_score: bool = train_score
Whether scores will be calculated on the training data as well.
CompleteEvalInfo
dataclass
#
CompleteEvalInfo(
X: XLike,
y: YLike,
X_test: XLike | None,
y_test: YLike | None,
splitter: BaseShuffleSplit | BaseCrossValidator,
max_splits: int,
scores: SplitScores,
scorers: dict[str, _Scorer],
models: list[BaseEstimator] | None,
splitter_params: Mapping[str, Any],
fit_params: Mapping[str, Any],
scorer_params: Mapping[str, Any],
test_scorer_params: Mapping[str, Any],
)
Information about the final evaluation of a cross-validation task.
This class contains information about the final evaluation of a cross-validation that will be passed to the post-processing function.
fit_params
instance-attribute
#
The parameters that were used for fitting the estimator.
Please use
select_params()
if you need to select the params specific to a split, i.e. for sample_weights
.
max_splits
instance-attribute
#
max_splits: int
The maximum number of splits that were (or could have been) evaluated.
models
instance-attribute
#
models: list[BaseEstimator] | None
The models that were trained in each split.
This will be None
if post_processing_requires_models=False
.
scorer_params
instance-attribute
#
The parameters that were used for scoring the estimator.
Please use
select_params()
if you need to select the params specific to a split, i.e. for sample_weights
.
splitter
instance-attribute
#
The splitter that was used.
splitter_params
instance-attribute
#
The parameters that were used for the splitter.
test_scorer_params
instance-attribute
#
The parameters that were used for scoring the test data.
Please use
select_params()
if you need to select the params specific to a split, i.e. for sample_weights
.
select_params
#
Convinience method to select parameters for a specific split.
Source code in src/amltk/sklearn/evaluation.py
PostSplitInfo
#
Bases: NamedTuple
Information about the evaluation of a split.
ATTRIBUTE | DESCRIPTION |
---|---|
X |
The features to used for training.
TYPE:
|
y |
The targets used for training.
TYPE:
|
X_test |
The features used for testing if it was passed in.
TYPE:
|
y_test |
The targets used for testing if it was passed in.
TYPE:
|
i_train |
The train indices for this split.
TYPE:
|
i_val |
The validation indices for this split.
TYPE:
|
model |
The model that was trained in this split.
TYPE:
|
train_scores |
The training scores for this split if requested. |
val_scores |
The validation scores for this split. |
test_scores |
The test scores for this split if requested. |
fitting_params |
Any additional fitting parameters that were used. |
train_scorer_params |
Any additional scorer parameters used for evaluating scorers on training set. |
val_scorer_params |
Any additional scorer parameters used for evaluating scorers on training set. |
test_scorer_params |
Any additional scorer parameters used for evaluating scorers on training set. |
SplitScores
#
Bases: NamedTuple
The scores for a split.
ATTRIBUTE | DESCRIPTION |
---|---|
val |
The validation scores for all evaluated split. |
train |
The training scores for all evaluated splits if requested. |
test |
The test scores for all evaluated splits if requested. |
cv_early_stopping_plugin
#
cv_early_stopping_plugin(
strategy: CVEarlyStoppingProtocol | None = None,
*,
create_comms: (
Callable[[], tuple[Comm, Comm]] | None
) = None
) -> _CVEarlyStoppingPlugin
Create a plugin for a task allow for early stopping.
from dataclasses import dataclass
from pathlib import Path
import sklearn.datasets
from sklearn.tree import DecisionTreeClassifier
from amltk.sklearn import CVEvaluation
from amltk.pipeline import Component
from amltk.optimization import Metric, Trial
working_dir = Path("./some-path")
pipeline = Component(DecisionTreeClassifier, space={"max_depth": (1, 10)})
x, y = sklearn.datasets.load_iris(return_X_y=True)
evaluator = CVEvaluation(x, y, n_splits=3, working_dir=working_dir)
# Our early stopping strategy, with an `update()` and `should_stop()`
# signature match what's expected.
@dataclass
class CVEarlyStopper:
def update(self, report: Trial.Report) -> None:
# Normally you would update w.r.t. a finished trial, such
# as updating a moving average of the scores.
pass
def should_stop(self, trial: Trial, scores: CVEvaluation.SplitScores) -> bool | Exception:
# Return True to stop, False to continue. Alternatively, return a
# specific exception to attach to the report instead
return True
history = pipeline.optimize(
target=evaluator.fn,
metric=Metric("accuracy", minimize=False, bounds=(0, 1)),
max_trials=1,
working_dir=working_dir,
# Here we insert the plugin to the task that will get created
plugins=[evaluator.cv_early_stopping_plugin(strategy=CVEarlyStopper())],
# Notably, we set `on_trial_exception="continue"` to not stop as
# we expect trials to fail given the early stopping strategy
on_trial_exception="continue",
)
╭──── Report(config_id=1_seed=1509460901_budget=None_instance=None) - fail ────╮
│ Status(fail) │
│ MetricCollection( │
│ metrics={ │
│ 'accuracy': Metric( │
│ name='accuracy', │
│ minimize=False, │
│ bounds=(0.0, 1.0), │
│ fn=None │
│ ) │
│ } │
│ ) │
│ ╭─ Metrics ────────────────────────────────────────────────────────────────╮ │
│ │ MetricCollection( │ │
│ │ metrics={ │ │
│ │ 'accuracy': Metric( │ │
│ │ name='accuracy', │ │
│ │ minimize=False, │ │
│ │ bounds=(0.0, 1.0), │ │
│ │ fn=None │ │
│ │ ) │ │
│ │ } │ │
│ │ ) │ │
│ ╰──────────────────────────────────────────────────────────────────────────╯ │
│ config {'DecisionTreeClassifier:max_depth': 7} │
│ seed 1509460901 │
│ bucket PathBucket(PosixPath('some-path/config_id=1_seed=1509460… │
│ summary {'split_0:val_accuracy': 0.94} │
│ storage {'exception.txt'} │
│ profile:cv Interval( │
│ memory=Interval( │
│ start_vms=1229381632.0, │
│ start_rss=244924416.0, │
│ end_vms=1229381632, │
│ end_rss=247676928, │
│ unit=bytes │
│ ), │
│ time=Interval( │
│ start=1723534477.633168, │
│ end=1723534477.6756542, │
│ kind=wall, │
│ unit=seconds │
│ ) │
│ ) │
│ profile:cv:fit Interval( │
│ memory=Interval( │
│ start_vms=1229381632.0, │
│ start_rss=245841920.0, │
│ end_vms=1229381632, │
│ end_rss=247545856, │
│ unit=bytes │
│ ), │
│ time=Interval( │
│ start=1723534477.645106, │
│ end=1723534477.649212, │
│ kind=wall, │
│ unit=seconds │
│ ) │
│ ) │
│ profile:cv:score Interval( │
│ memory=Interval( │
│ start_vms=1229381632.0, │
│ start_rss=247545856.0, │
│ end_vms=1229381632, │
│ end_rss=247676928, │
│ unit=bytes │
│ ), │
│ time=Interval( │
│ start=1723534477.6497915, │
│ end=1723534477.651904, │
│ kind=wall, │
│ unit=seconds │
│ ) │
│ ) │
│ profile:cv:split_0 Interval( │
│ memory=Interval( │
│ start_vms=1229381632.0, │
│ start_rss=247676928.0, │
│ end_vms=1229381632, │
│ end_rss=247676928, │
│ unit=bytes │
│ ), │
│ time=Interval( │
│ start=1723534477.6522815, │
│ end=1723534477.675374, │
│ kind=wall, │
│ unit=seconds │
│ ) │
│ ) │
╰──────────────────────────────────────────────────────────────────────────────╯
!!! warning "Recommended settings for CVEvaluation
When a trial is early stopped, it will be counted as a failed trial.
This can conflict with the behaviour of `pipeline.optimize` which
by default sets `on_trial_exception="raise"`, causing the optimization
to end. If using [`pipeline.optimize`][amltk.pipeline.Node.optimize],
to set `on_trial_exception="continue"` to continue optimization.
This will also add a new event to the task which you can subscribe to with
task.on("split-evaluated")
.
It will be passed a
CVEvaluation.PostSplitInfo
that you can use to make a decision on whether to continue or stop. The
passed in strategy=
simply sets up listening to these events for you.
You can also do this manually.
scores = []
evaluator = CVEvaluation(...)
task = scheduler.task(
evaluator.fn,
plugins=[evaluator.cv_early_stopping_plugin()]
)
@task.on("split-evaluated")
def should_stop(trial: Trial, scores: CVEvaluation.SplitScores) -> bool | Execption:
# Make a decision on whether to stop or continue
return info.scores["accuracy"] < np.mean(scores.val["accuracy"])
@task.on("result")
def update_scores(_, report: Trial.Report) -> bool | Execption:
if report.status is Trial.Status.SUCCESS:
return scores.append(report.values["accuracy"])
PARAMETER | DESCRIPTION |
---|---|
strategy |
The strategy to use for early stopping. Must implement the
By default, when no
TYPE:
|
create_comms |
A function that creates a pair of comms for the plugin to use. This is useful if you want to create a custom communication channel. If not provided, the default communication channel will be used. Default communication channel By default we use a simple |
RETURNS | DESCRIPTION |
---|---|
_CVEarlyStoppingPlugin
|
The plugin to use for the task. |
Source code in src/amltk/sklearn/evaluation.py
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 |
|
identify_task_type
#
identify_task_type(
y: YLike,
*,
task_hint: Literal[
"classification", "regression", "auto"
] = "auto"
) -> TaskTypeName
Identify the task type from the target data.
Source code in src/amltk/sklearn/evaluation.py
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 |
|
resample_if_minority_class_too_few_for_n_splits
#
resample_if_minority_class_too_few_for_n_splits(
X_train: DataFrame,
y_train: Series,
*,
n_splits: int,
seed: Seed | None = None,
_warning_if_occurs: str | None = None
) -> tuple[DataFrame, DataFrame | Series]
Rebalance the training data to allow stratification.
If your data only contains something such as 3 labels for a single class, and you wish to perform 5 fold cross-validation, you will need to rebalance the data to allow for stratification. This function will take the training data and labels and and resample the data to allow for stratification.
PARAMETER | DESCRIPTION |
---|---|
X_train |
The training data.
TYPE:
|
y_train |
The training labels.
TYPE:
|
n_splits |
The number of splits to perform.
TYPE:
|
seed |
Used for deciding which instances to resample.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
tuple[DataFrame, DataFrame | Series]
|
The rebalanced training data and labels. |