code
stringlengths
17
6.64M
class RepeatedContinuousStratifiedGroupKFold(_RepeatedSplits): 'Repeated Stratified-Groups K-Fold cross validator.\n\n Repeats :class:`julearn.model_selection.ContinuousStratifiedGroupKFold`\n n times with different randomization in each repetition.\n\n Parameters\n ----------\n n_bins : int\n ...
class StratifiedBootstrap(BaseShuffleSplit): 'Stratified Bootstrap cross-validation iterator.\n\n Provides train/test indices using resampling with replacement, respecting\n the distribution of samples for each class.\n\n Parameters\n ----------\n n_splits : int, default=5\n Number of re-shu...
def test_register_searcher() -> None: 'Test registering a searcher.' with pytest.raises(ValueError, match='The specified searcher '): get_searcher('custom_grid') register_searcher('custom_grid', GridSearchCV) assert (get_searcher('custom_grid') == GridSearchCV) with pytest.warns(RuntimeWar...
def test_reset_searcher() -> None: 'Test resetting the searcher registry.' register_searcher('custom_grid', GridSearchCV) get_searcher('custom_grid') reset_searcher_register() with pytest.raises(ValueError, match='The specified searcher '): get_searcher('custom_grid')
def test_continuous_stratified_kfold_binning() -> None: 'Test continuous stratified K-fold generator using binning.' (n_samples, n_features) = (200, 20) X = np.random.rand(n_samples, n_features) y = np.random.rand(n_samples) n_bins = 5 edges = np.histogram_bin_edges(y, bins=n_bins) bins = ...
def test_continuous_stratified_kfold_quantile() -> None: 'Test continuous stratified K-fold generator using binning.' (n_samples, n_features) = (200, 20) X = np.random.rand(n_samples, n_features) y = np.random.normal(size=n_samples) n_bins = 5 edges = np.quantile(y, np.linspace(0, 1, (n_bins +...
def test_continuous_stratified_group_kfold_binning() -> None: 'Test continuous stratified group K-fold generator using binning.' (n_samples, n_features) = (200, 20) X = np.random.rand(n_samples, n_features) y = np.random.rand(n_samples) n_bins = 5 edges = np.histogram_bin_edges(y, bins=n_bins)...
def test_continuous_stratified_group_kfold_quantile() -> None: 'Test continuous stratified group K-fold generator using binning.' (n_samples, n_features) = (200, 20) X = np.random.rand(n_samples, n_features) y = np.random.normal(size=n_samples) n_bins = 5 edges = np.quantile(y, np.linspace(0, ...
@pytest.mark.parametrize('n_classes, test_size', [(3, 0.2), (2, 0.5), (4, 0.8)]) def test_stratified_bootstrap(n_classes: int, test_size: float) -> None: 'Test stratified bootstrap CV generator.\n\n Parameters\n ----------\n n_classes : int\n Number of classes.\n test_size : float\n Test...
def list_models() -> List[str]: 'List all the available model names.\n\n Returns\n -------\n list of str\n A list will all the available model names.\n\n ' out = list(_available_models.keys()) return out
def get_model(name: str, problem_type: str, **kwargs: Any) -> ModelLike: 'Get a model.\n\n Parameters\n ----------\n name : str\n The model name\n problem_type : str\n The type of problem. See :func:`.run_cross_validation`.\n **kwargs : dict\n Extra keyword arguments.\n\n Re...
def register_model(model_name: str, classification_cls: Optional[Type[ModelLike]]=None, regression_cls: Optional[Type[ModelLike]]=None, overwrite: Optional[bool]=None): 'Register a model to julearn.\n\n This function allows you to add a model or models for different problem\n types to julearn. Afterwards, i...
def reset_model_register() -> None: 'Reset the model register to the default state.' global _available_models _available_models = deepcopy(_available_models_reset)
def test_register_model() -> None: 'Test the register model function.' register_model('dt', classification_cls=DecisionTreeClassifier, regression_cls=DecisionTreeRegressor) classification = get_model('dt', 'classification') regression = get_model('dt', 'regression') assert isinstance(classificatio...
def test_register_warning() -> None: 'Test the register model function warnings.' with pytest.warns(RuntimeWarning, match='Model name'): register_model('rf', regression_cls=RandomForestRegressor) reset_model_register() with pytest.raises(ValueError, match='Model name'): register_model(...
@fixture(params=['METADES', 'SingleBest', 'StaticSelection', 'StackedClassifier', 'KNORAU', 'KNORAE', 'DESP', 'OLA', 'MCB', 'KNOP'], scope='module') def all_deslib_algorithms(request: FixtureRequest) -> str: 'Return different algorithms for the iris dataset features.\n\n Parameters\n ----------\n request...
@pytest.mark.parametrize('algo_name', [lazy_fixture('all_deslib_algorithms')]) @pytest.mark.skip('Deslib is not compatible with new python. Waiting for PR.') def test_algorithms(df_iris: pd.DataFrame, algo_name: str) -> None: 'Test all the algorithms from deslib.\n\n Parameters\n ----------\n df_iris : p...
def test_wrong_algo(df_iris: pd.DataFrame) -> None: 'Test wrong algorithm.\n\n Parameters\n ----------\n df_iris : pd.DataFrame\n Iris dataset.\n ' df_iris = df_iris[df_iris['species'].isin(['versicolor', 'virginica'])] X = ['sepal_length', 'sepal_width', 'petal_length'] y = 'specie...
@pytest.mark.parametrize('ds_split', [0.2, 0.3, [train_test_split(np.arange(20), test_size=0.4, shuffle=True)], ShuffleSplit(n_splits=1)]) @pytest.mark.skip('Deslib is not compatible with new python. Waiting for PR.') def test_ds_split_parameter(ds_split: Any, df_iris: pd.DataFrame) -> None: 'Test ds_split parame...
@pytest.mark.parametrize('ds_split', [4, ShuffleSplit(n_splits=2)]) @pytest.mark.skip('Deslib is not compatible with new python. Waiting for PR.') def test_ds_split_error(ds_split: Any, df_iris: pd.DataFrame) -> None: 'Test ds_split errors.\n\n Parameters\n ----------\n ds_split : float or tuple or sklea...
@pytest.mark.parametrize('model_name, model_class, model_params', [('nb_bernoulli', BernoulliNB, {}), ('nb_categorical', CategoricalNB, {}), ('nb_complement', ComplementNB, {}), ('nb_gaussian', GaussianNB, {}), ('nb_multinomial', MultinomialNB, {})]) def test_naive_bayes_estimators(df_iris: pd.DataFrame, model_name: ...
@pytest.mark.parametrize('model_name, model_class, model_params', [('svm', SVC, {}), ('rf', RandomForestClassifier, {'n_estimators': 10, 'random_state': 42}), ('et', ExtraTreesClassifier, {'n_estimators': 10, 'random_state': 42}), ('dummy', DummyClassifier, {'strategy': 'prior'}), ('gauss', GaussianProcessClassifier,...
@pytest.mark.parametrize('model_name, model_class, model_params', [('svm', SVR, {}), ('rf', RandomForestRegressor, {'n_estimators': 10, 'random_state': 42}), ('et', ExtraTreesRegressor, {'n_estimators': 10, 'random_state': 42}), ('dummy', DummyRegressor, {'strategy': 'mean'}), ('gauss', GaussianProcessRegressor, {'ra...
def test_wrong_problem_types() -> None: 'Test models with wrong problem types.' with pytest.raises(ValueError, match='is not suitable for'): get_model('linreg', 'classification') with pytest.raises(ValueError, match='is not available'): get_model('wrong', 'classification')
def merge_pipelines(*pipelines: EstimatorLike, search_params: Dict) -> Pipeline: 'Merge multiple pipelines into a single one.\n\n Parameters\n ----------\n pipelines : List[EstimatorLike]\n List of estimators that will be merged.\n search_params : Dict\n Dictionary with the search parame...
def _params_to_pipeline(param: Any, X_types: Dict[(str, List)], search_params: Optional[Dict]): 'Recursively convert params to pipelines.\n\n Parameters\n ----------\n param : Any\n The parameter to convert.\n X_types : Dict[str, List]\n The types of the columns in the data.\n search_...
@dataclass class Step(): 'Step class.\n\n This class represents a step in a pipeline.\n\n\n Parameters\n ----------\n name : str\n The name of the step.\n estimator : Any\n The estimator to use.\n apply_to : ColumnTypesLike\n The types to apply this step to, by default "cont...
class PipelineCreator(): 'PipelineCreator class.\n\n This class is used to create pipelines. As the creation of a pipeline\n is a bit more complicated than just adding steps to a pipeline, this\n helper class is provided so the user can easily create complex\n :class:`sklearn.pipeline.Pipeline` object...
def _prepare_hyperparameter_tuning(params_to_tune: Union[(Dict[(str, Any)], List[Dict[(str, Any)]])], search_params: Optional[Dict[(str, Any)]], pipeline: Pipeline): "Prepare hyperparameter tuning in the pipeline.\n\n Parameters\n ----------\n params_to_tune : dict\n A dictionary with the paramete...
class TargetPipelineCreator(): 'TargetPipelineCreator class.\n\n Analogous to the PipelineCreator class, this class allows to create\n :class:`julearn.pipeline.target_pipeline.JuTargetPipeline` objects in an\n easy way.\n ' def __init__(self) -> None: self._steps = [] def add(self, s...
def test_merger_pipelines() -> None: 'Test the pipeline merger.' creator1 = PipelineCreator(problem_type='classification') creator1.add('zscore', name='scaler', apply_to='continuous') creator1.add('rf') creator2 = PipelineCreator(problem_type='classification') creator2.add('scaler_robust', nam...
def test_merger_errors() -> None: 'Test that the merger raises errors when it should.' creator1 = PipelineCreator(problem_type='classification') creator1.add('zscore', name='scaler', apply_to='continuous') creator1.add('rf') creator2 = PipelineCreator(problem_type='classification') creator2.ad...
@pytest.mark.parametrize('model,preprocess,problem_type', [lazy_fixture(['models_all_problem_types', 'preprocessing', 'all_problem_types'])]) def test_construction_working(model: str, preprocess: List[str], problem_type: str) -> None: 'Test that the pipeline constructions works as expected.\n\n Parameters\n ...
@pytest.mark.parametrize('model,preprocess,problem_type', [lazy_fixture(['models_all_problem_types', 'preprocessing', 'all_problem_types'])]) def test_fit_and_transform_no_error(X_iris: pd.DataFrame, y_iris: pd.Series, model: str, preprocess: List[str], problem_type: str) -> None: 'Test that the pipeline fit and ...
@pytest.mark.parametrize('model,preprocess,problem_type', [lazy_fixture(['models_all_problem_types', 'preprocessing', 'all_problem_types'])]) def test_hyperparameter_tuning(X_types_iris: Dict[(str, List[str])], model: str, preprocess: List[str], problem_type: str, get_tuning_params: Callable, search_params: Dict[(str...
@pytest.mark.parametrize('X_types,apply_to,warns', [({'duck': 'B'}, ['duck', 'chicken'], True), ({'duck': 'B'}, ['duck'], False), ({}, ['continuous'], False), (None, ['continuous'], False), ({'continuous': 'A', 'cat': 'B'}, ['continuous', 'cat'], False), ({'continuous': 'A'}, ['continuous', 'target'], False), ({'cont...
@pytest.mark.parametrize('X_types,apply_to,error', [({}, ['duck'], True), ({'duck': 'B'}, ['duck'], False), ({}, ['continuous'], False), (None, ['continuous'], False), ({'continuous': 'A', 'cat': 'B'}, ['continuous', 'cat'], False), ({'continuous': 'A', 'cat': 'B'}, ['continuous'], True), ({'continuous': 'A', 'cat': ...
def test_pipelinecreator_default_apply_to() -> None: 'Test pipeline creator using the default apply_to.' pipeline_creator = PipelineCreator(problem_type='classification').add('rf', apply_to='chicken') with pytest.raises(ValueError, match='Extra X_types were provided'): pipeline_creator._check_X_ty...
def test_pipelinecreator_default_constructor_apply_to() -> None: 'Test pipeline creator using a default apply_to in the constructor.' pipeline_creator = PipelineCreator(problem_type='classification', apply_to='duck').add('rf') pipeline_creator._check_X_types({'duck': 'teriyaki'}) pipeline_creator = Pi...
def test_added_model_target_transform() -> None: 'Test that the added model and target transformer are set correctly.' pipeline_creator = PipelineCreator(problem_type='classification').add('zscore', apply_to='continuous') assert (pipeline_creator._added_target_transformer is False) pipeline_creator.ad...
def test_stacking(X_iris: pd.DataFrame, y_iris: pd.Series) -> None: 'Test that the stacking model works correctly.' X_types = {'sepal': ['sepal_length', 'sepal_width'], 'petal': ['petal_length', 'petal_width']} model_sepal = PipelineCreator(problem_type='classification', apply_to='*') model_sepal.add(...
def test_added_repeated_transformers() -> None: 'Test that the repeated transformers names are set correctly.' pipeline_creator = PipelineCreator(problem_type='classification') pipeline_creator.add('zscore', apply_to='continuous') pipeline_creator.add('zscore', apply_to='duck') pipeline_creator.ad...
def test_target_pipe(X_iris, y_iris) -> None: 'Test that the target pipeline works correctly.' X_types = {'continuous': ['sepal_length', 'sepal_width', 'petal_length'], 'confounds': ['petal_width']} target_pipeline = TargetPipelineCreator().add('confound_removal', confounds=['confounds', 'continuous']) ...
def test_raise_wrong_problem_type() -> None: 'Test that the correct error is raised when the problem type is wrong.' with pytest.raises(ValueError, match='`problem_type` should'): PipelineCreator(problem_type='binary')
def test_raise_wrong_problem_type_added_to_step() -> None: 'Test error when problem type is passed to a step.' with pytest.raises(ValueError, match='Please provide the problem_type'): PipelineCreator(problem_type='classification').add('svm', problem_type='classification')
def test_raise_error_not_target_pipe() -> None: 'Test error when target pipeline is not applied to target.' with pytest.raises(ValueError, match='TargetPipelineCreator can'): target_pipeline = TargetPipelineCreator().add('confound_removal', confounds=['confounds', 'continuous']) PipelineCreato...
def test_raise_pipe_no_model() -> None: 'Test error when no model is added to the pipeline.' X_types = {'continuous': ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']} pipeline_creator = PipelineCreator(problem_type='regression').add('zscore') with pytest.raises(ValueError, match='Cannot...
def test_raise_pipe_wrong_searcher() -> None: 'Test error when the searcher is not a valid julearn searcher.' X_types = {'continuous': ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']} pipeline_creator = PipelineCreator(problem_type='regression').add('svm', C=[1, 2]) with pytest.raises(V...
def test_PipelineCreator_repeated_steps() -> None: 'Test the pipeline creator with repeated steps.' creator = PipelineCreator(problem_type='classification') creator.add('zscore', apply_to='continuous') creator.add('zscore', apply_to='continuous') creator.add('rf') assert (len(creator._steps) =...
def test_PipelineCreator_repeated_steps_error() -> None: 'Test error with repeated steps.' creator = PipelineCreator(problem_type='classification') creator.add('zscore', name='scale', apply_to='continuous') creator.add('pca', name='pca', apply_to='continuous') with pytest.raises(ValueError, match=...
def test_PipelineCreator_split() -> None: 'Test the pipeline creator split.' creator1 = PipelineCreator(problem_type='classification') creator1.add('zscore', apply_to='continuous') creator1.add('zscore', apply_to='continuous') creator1.add('rf') assert (len(creator1._steps) == 3) assert (c...
def test_TargetPipelineCreator() -> None: 'Test the target pipeline creator.' creator = TargetPipelineCreator() creator.add('zscore') creator.add('scaler_minmax') creator.add('confound_removal', confounds='confounds') pipeline = creator.to_pipeline() assert isinstance(pipeline, JuTargetPip...
def test_TargetPipelineCreator_repeated_names() -> None: 'Test the target pipeline creator.' creator = TargetPipelineCreator() creator.add('zscore') creator.add('zscore') pipeline = creator.to_pipeline() assert isinstance(pipeline, JuTargetPipeline) assert (len(pipeline.steps) == 2) as...
def get_scorer(name: str) -> ScorerLike: 'Get available scorer by name.\n\n Parameters\n ----------\n name : str\n name of an available scorer\n\n Returns\n -------\n scorer : ScorerLike\n Callable object that returns a scalar score; greater is better.\n Will be called using...
def list_scorers() -> List[str]: 'List all available scorers.\n\n Returns\n -------\n list of str\n a list containing all available scorers.\n ' scorers = list(get_scorer_names()) scorers.extend(list(_extra_available_scorers.keys())) return scorers
def register_scorer(scorer_name: str, scorer: ScorerLike, overwrite: Optional[bool]=None) -> None: 'Register a scorer, so that it can be accessed by name.\n\n Parameters\n ----------\n scorer_name : str\n name of the scorer you want to register\n scorer : ScorerLike\n Callable object tha...
def reset_scorer_register(): 'Reset the scorer register to the default state.' global _extra_available_scorers _extra_available_scorers = deepcopy(_extra_available_scorers_reset)
def check_scoring(estimator: EstimatorLike, scoring: Union[(ScorerLike, str, Callable, List[str], None)], wrap_score: bool) -> Union[(None, ScorerLike, Callable, Dict[(str, ScorerLike)])]: 'Check the scoring.\n\n Parameters\n ----------\n estimator : EstimatorLike\n estimator to check the scoring ...
def _extend_scorer(scorer, extend): if extend: return _ExtendedScorer(scorer) return scorer
class _ExtendedScorer(): def __init__(self, scorer): self.scorer = scorer def __call__(self, estimator, X, y): if hasattr(estimator, 'best_estimator_'): estimator = estimator.best_estimator_ X_trans = X for (_, transform) in estimator.steps[:(- 1)]: X_...
def ensure_1d(y: ArrayLike) -> np.ndarray: 'Ensure that y is 1d.\n\n Parameters\n ----------\n y : ArrayLike\n The array to be checked.\n\n Returns\n -------\n np.ndarray\n The array as a 1d numpy array.\n\n Raises\n ------\n ValueError\n If y cannot be converted to...
def r2_corr(y_true: ArrayLike, y_pred: ArrayLike) -> float: 'Compute squared Pearson product-moment correlation coefficient.\n\n Parameters\n ----------\n y_true : ArrayLike\n The true values.\n y_pred : ArrayLike\n The predicted values.\n\n Returns\n -------\n float\n Th...
def r_corr(y_true: ArrayLike, y_pred: ArrayLike) -> float: 'Compute Pearson product-moment correlation coefficient.\n\n Parameters\n ----------\n y_true : ArrayLike\n The true values.\n y_pred : ArrayLike\n The predicted values.\n\n Returns\n -------\n float\n Pearson pro...
def _return_1(estimator: EstimatorLike, X: DataLike, y: DataLike) -> float: 'Return 1.' return 1
def test_register_scorer() -> None: 'Test registering scorers.' with pytest.raises(ValueError, match='useless is not a valid scorer'): get_scorer('useless') register_scorer('useless', make_scorer(_return_1)) _ = get_scorer('useless') register_scorer('useless', make_scorer(_return_1), True)...
def test_reset_scorer() -> None: 'Test resetting the scorers registry.' with pytest.raises(ValueError, match='useless is not a valid scorer '): get_scorer('useless') register_scorer('useless', make_scorer(_return_1)) get_scorer('useless') reset_scorer_register() with pytest.raises(Valu...
def test_ensure_1d() -> None: 'Test ensure_1d.' y = [1, 2, 3, 4] assert np.all((ensure_1d(y) == y)) y = [[1, 2, 3, 4]] assert np.all((ensure_1d(y) == y[0])) with pytest.raises(ValueError, match='cannot be converted to 1d'): ensure_1d([[1, 2, 3, 4], [2, 3, 4, 5]])
def test_r2_corr() -> None: 'Test r2_corr.' assert (r2_corr([1, 2, 3, 4], [1, 2, 3, 4]) == 1) assert (r2_corr([1, 2, 3, 4], [2, 3, 4, 5]) == 1)
def test_r_corr() -> None: 'Test r_corr.' assert (r_corr([1, 2, 3, 4], [1, 2, 3, 4]) == 1) assert (r_corr([1, 2, 3, 4], [2, 3, 4, 5]) == 1)
def _corrected_std(differences: np.ndarray, n_train: int, n_test: int) -> float: "Corrects standard deviation using Nadeau and Bengio's approach.\n\n Parameters\n ----------\n differences : ndarray of shape (n_samples,)\n Vector containing the differences in the score metrics of two models.\n n...
def _compute_corrected_ttest(differences: np.ndarray, n_train: int, n_test: int, df: Optional[int]=None, alternative: str='two-sided') -> Tuple[(float, float)]: "Compute paired t-test with corrected variance.\n\n Parameters\n ----------\n differences : array-like of shape (n_samples,)\n Vector con...
def corrected_ttest(*scores: pd.DataFrame, df: Optional[int]=None, method: str='bonferroni', alternative: str='two-sided') -> pd.DataFrame: "Perform corrected t-test on the scores of two or more models.\n\n Parameters\n ----------\n *scores : pd.DataFrame\n DataFrames containing the scores of the ...
def test__compute_corrected_ttest_alternatives(): 'Test the _compute_corrected_ttest function.' rvs1 = stats.norm.rvs(loc=0.5, scale=0.2, size=20, random_state=42) rvs2 = stats.norm.rvs(loc=0.51, scale=0.2, size=20, random_state=45) rvs3 = stats.norm.rvs(loc=0.9, scale=0.2, size=20, random_state=50) ...
def test_corrected_ttest() -> None: 'Test the corrected_ttest function.' data1 = np.random.rand(10) data2 = (np.random.rand(10) + 0.05) data3 = (np.random.rand(10) + 0.1) cv_mdsum = 'maradona' scores1 = pd.DataFrame({'fold': (np.arange(10) % 5), 'repeat': (np.arange(10) // 5), 'test_score': da...
def test_corrected_ttest_errors() -> None: 'Test the corrected_ttest function.' data1 = np.random.rand(10) data2 = (np.random.rand(10) + 0.05) scores1 = pd.DataFrame({'test_score': data1}) scores2 = pd.DataFrame({'test_score': data2}) with pytest.raises(ValueError, match='cv_mdsum'): c...
def test_run_cv_simple_binary(df_binary: pd.DataFrame, df_iris: pd.DataFrame) -> None: 'Test a simple binary classification problem.\n\n Parameters\n ----------\n df_binary : pd.DataFrame\n The iris dataset as a binary classification problem.\n df_iris : pd.DataFrame\n The iris dataset a...
def test_run_cv_simple_binary_groups(df_iris: pd.DataFrame) -> None: 'Test a simple binary classification problem with groups in the CV.\n\n Parameters\n ----------\n df_iris : pd.DataFrame\n The iris dataset as a multiclass classification problem.\n ' df_iris = df_iris[df_iris['species'].i...
def test_run_cv_simple_binary_errors(df_binary: pd.DataFrame, df_iris: pd.DataFrame) -> None: 'Test a simple classification problem errors.\n\n Parameters\n ----------\n df_binary : pd.DataFrame\n The iris dataset as a binary classification problem.\n df_iris : pd.DataFrame\n The iris da...
def test_run_cv_errors(df_iris: pd.DataFrame) -> None: 'Test a run_cross_validation errors and warnings.\n\n Parameters\n ----------\n df_iris : pd.DataFrame\n The iris dataset as a multiclass classification problem.\n ' X = ['sepal_length', 'sepal_width', 'petal_length'] y = 'species' ...
def test_run_cv_multiple_pipeline_errors(df_iris: pd.DataFrame) -> None: 'Test run_cross_validation with multiple pipelines errors.' X = ['sepal_length', 'sepal_width', 'petal_length'] y = 'species' X_types = {'continuous': X} model1 = PipelineCreator(problem_type='classification') model1.add(...
def test_tune_hyperparam_gridsearch(df_iris: pd.DataFrame) -> None: 'Test a run_cross_validation with hyperparameter tuning (gridsearch).\n\n Parameters\n ----------\n df_iris : pd.DataFrame\n The iris dataset as a multiclass classification problem.\n ' df_iris = df_iris[df_iris['species']....
def test_tune_hyperparam_gridsearch_groups(df_iris: pd.DataFrame) -> None: 'Test a run_cross_validation with hyperparameter tuning (gridsearch).\n\n Parameters\n ----------\n df_iris : pd.DataFrame\n The iris dataset as a multiclass classification problem.\n ' df_iris = df_iris[df_iris['spe...
def test_tune_hyperparam_randomsearch(df_iris: pd.DataFrame) -> None: 'Test a run_cross_validation with hyperparameter tuning (randomsearch).\n\n Parameters\n ----------\n df_iris : pd.DataFrame\n The iris dataset as a multiclass classification problem.\n ' df_iris = df_iris[df_iris['specie...
def test_tune_hyperparams_multiple_grid(df_iris: pd.DataFrame) -> None: 'Test a run_cross_validation hyperparameter tuning (multiple grid).' df_iris = df_iris[df_iris['species'].isin(['versicolor', 'virginica'])] X = ['sepal_length', 'sepal_width', 'petal_length'] y = 'species' X_types = {'continu...
def test_return_estimators(df_iris: pd.DataFrame) -> None: 'Test returning estimators.\n\n Parameters\n ----------\n df_iris : pd.DataFrame\n The iris dataset as a multiclass classification problem.\n ' df_iris = df_iris[df_iris['species'].isin(['versicolor', 'virginica'])] X = ['sepal_...
def test_return_train_scores(df_iris: pd.DataFrame) -> None: 'Test returning estimators.\n\n Parameters\n ----------\n df_iris : pd.DataFrame\n The iris dataset as a multiclass classification problem.\n ' df_iris = df_iris[df_iris['species'].isin(['versicolor', 'virginica'])] X = ['sepa...
@pytest.mark.parametrize('cv1, cv2, expected', [(GroupKFold(2), KFold(3), False), (GroupKFold(2), GroupKFold(3), False), (GroupKFold(3), GroupKFold(3), True), (GroupShuffleSplit(2), GroupShuffleSplit(3), 'non-reproducible'), (GroupShuffleSplit(2, random_state=32), GroupShuffleSplit(3, random_state=32), False), (Group...
def test_api_stacking_models() -> None: 'Test API of stacking models.' (X, y) = make_regression(n_features=6, n_samples=50) X_types = {'type1': [f'type1_{x}' for x in range(1, 4)], 'type2': [f'type2_{x}' for x in range(1, 4)]} X_names = (X_types['type1'] + X_types['type2']) data = pd.DataFrame(X) ...
def test_inspection_error(df_iris: pd.DataFrame) -> None: 'Test error for inspector.\n\n Parameters\n ----------\n df_iris : pd.DataFrame\n The iris dataset.\n\n ' X = ['sepal_length', 'sepal_width', 'petal_length'] y = 'species' with pytest.raises(ValueError, match='return_inspecto...
def test_final_estimator_picklable(tmp_path: Path, df_iris: pd.DataFrame) -> None: 'Test if final estimator is picklable.\n\n Parameters\n ----------\n tmp_path : pathlib.Path\n The path to the test directory.\n df_iris : pd.DataFrame\n The iris dataset.\n\n ' X = ['sepal_length',...
def test_inspector_picklable(tmp_path: Path, df_iris: pd.DataFrame) -> None: 'Test if inspector is picklable.\n\n Parameters\n ----------\n tmp_path : pathlib.Path\n The path to the test directory.\n df_iris : pd.DataFrame\n The iris dataset.\n\n ' X = ['sepal_length', 'sepal_widt...
def test_set_config_wrong_keys() -> None: 'Test that set_config raises an error when the key does not exist.' with pytest.raises(ValueError, match='does not exist'): set_config('wrong_key', 1)
def test_set_get_config() -> None: 'Test setting and getting config values.' old_value = get_config('MAX_X_WARNS') new_value = (old_value + 1) set_config('MAX_X_WARNS', new_value) assert (get_config('MAX_X_WARNS') == new_value)
def _check_df_input(prepared, X, y, groups, df): (df_X, df_y, df_groups, _) = prepared assert_array_equal(df[X].values, df_X[X].values) assert_array_equal(df_y.values, df[y].values) if (groups is not None): assert_array_equal(df[groups].values, df_groups)
def test_prepare_input_data() -> None: 'Test prepare input data (dataframe).' data = np.random.rand(4, 10) columns = [f'f_{x}' for x in range(data.shape[1])] X = columns[:(- 2)] y = columns[(- 1)] df = pd.DataFrame(data=data, columns=columns) X_types = {'continuous': X} prepared = prep...
def test_prepare_input_data_erors() -> None: 'Test prepare input data (dataframe) errors.' data = np.random.rand(4, 10) columns = [f'f_{x}' for x in range(data.shape[1])] df = pd.DataFrame(data=data, columns=columns) with pytest.raises(ValueError, match='DataFrame columns must be strings'): ...
def test_prepare_input_data_pos_labels() -> None: 'Test prepare input data (dataframe) pos_labels.' data = np.random.rand(20, 10) columns = [f'f_{x}' for x in range(data.shape[1])] df = pd.DataFrame(data=data, columns=columns) X = columns[:(- 1)] y = columns[(- 1)] X_types = {'continuous':...
def test_pick_columns_using_column_name() -> None: 'Test pick columns using column names as regexes.' columns = ['conf_1', 'conf_2', 'feat_1', 'feat_2', 'Feat_3'] regexes = ['conf_2', 'Feat_3'] assert (regexes == _pick_columns(regexes, columns)) columns = ['Feat_3', 'conf_1', 'conf_2', 'feat_1', '...
def test_pick_columns_using_regex_match() -> None: 'Test pick columns using regexes.' columns = ['conf_1', 'conf_2', 'feat_1', 'feat_2', 'Feat_3'] regexes = ['.*conf.*', '.*feat.*'] picked = _pick_columns(regexes, columns) assert (columns[:(- 1)] == picked) columns = ['conf_1', 'conf_2', '_fea...
def test_pick_columns_using_regex_and_column_name_match() -> None: 'Test pick columns using regexes and column names.' columns = ['conf_1', 'conf_2', 'feat_1', 'feat_2', 'Feat_3'] regexes = ['.*conf.*', '.*feat.*', 'Feat_3'] assert (columns == _pick_columns(regexes, columns))