def test_handle_string(correct_problem_types): problem_types = [ 'regression', ProblemTypes.MULTICLASS, 'binary', ProblemTypes.TIME_SERIES_REGRESSION, 'time series binary', 'time series multiclass' ] for problem_type in zip(problem_types, correct_problem_types): assert handle_problem_types(problem_type[0]) == problem_type[1] problem_type = 'fake' error_msg = 'Problem type \'fake\' does not exist' with pytest.raises(KeyError, match=error_msg): handle_problem_types(problem_type) == ProblemTypes.REGRESSION
def test_estimators_feature_name_with_random_ascii(X_y_binary, X_y_multi, X_y_regression, helper_functions): for estimator_class in _all_estimators_used_in_search(): supported_problem_types = [ handle_problem_types(pt) for pt in estimator_class.supported_problem_types ] for problem_type in supported_problem_types: clf = helper_functions.safe_init_component_with_njobs_1( estimator_class) if problem_type == ProblemTypes.BINARY: X, y = X_y_binary elif problem_type == ProblemTypes.MULTICLASS: X, y = X_y_multi elif problem_type == ProblemTypes.REGRESSION: X, y = X_y_regression X = clf.random_state.random((X.shape[0], len(string.printable))) col_names = [ 'column_{}'.format(ascii_char) for ascii_char in string.printable ] X = pd.DataFrame(X, columns=col_names) clf.fit(X, y) assert len(clf.feature_importance) == len(X.columns) assert not np.isnan(clf.feature_importance).all().all() predictions = clf.predict(X) assert len(predictions) == len(y) assert not np.isnan(predictions).all()
def test_estimators_feature_name_with_random_ascii(X_y_binary, X_y_multi, X_y_regression, ts_data, helper_functions): for estimator_class in _all_estimators_used_in_search(): if estimator_class.__name__ == 'ARIMARegressor': continue supported_problem_types = [ handle_problem_types(pt) for pt in estimator_class.supported_problem_types ] for problem_type in supported_problem_types: clf = helper_functions.safe_init_component_with_njobs_1( estimator_class) if is_binary(problem_type): X, y = X_y_binary elif is_multiclass(problem_type): X, y = X_y_multi elif is_regression(problem_type): X, y = X_y_regression X = get_random_state(clf.random_seed).random( (X.shape[0], len(string.printable))) col_names = [ 'column_{}'.format(ascii_char) for ascii_char in string.printable ] X = pd.DataFrame(X, columns=col_names) assert clf.input_feature_names is None clf.fit(X, y) assert len(clf.feature_importance) == len(X.columns) assert not np.isnan(clf.feature_importance).all().all() predictions = clf.predict(X).to_series() assert len(predictions) == len(y) assert not np.isnan(predictions).all() assert (clf.input_feature_names == col_names)
def __init__(self, problem_type, objective, n_splits=3): """ A collection of basic data checks. Arguments: problem_type (str): The problem type that is being validated. Can be regression, binary, or multiclass. objective (str or ObjectiveBase): Name or instance of the objective class. n_splits (int): The number of splits as determined by the data splitter being used. """ if handle_problem_types(problem_type) in [ ProblemTypes.REGRESSION, ProblemTypes.TIME_SERIES_REGRESSION ]: super().__init__(self._DEFAULT_DATA_CHECK_CLASSES, data_check_params={ "InvalidTargetDataCheck": { "problem_type": problem_type, "objective": objective } }) else: super().__init__(self._DEFAULT_DATA_CHECK_CLASSES + [ClassImbalanceDataCheck], data_check_params={ "InvalidTargetDataCheck": { "problem_type": problem_type, "objective": objective }, "ClassImbalanceDataCheck": { "num_cv_folds": n_splits } })
def make_data_splitter(X, y, problem_type, problem_configuration=None, n_splits=3, shuffle=True, random_state=0): """Given the training data and ML problem parameters, compute a data splitting method to use during AutoML search. Arguments: X (pd.DataFrame, ww.DataTable): The input training data of shape [n_samples, n_features]. y (pd.Series, ww.DataColumn): The target training data of length [n_samples]. problem_type (ProblemType): the type of machine learning problem. problem_configuration (dict, None): Additional parameters needed to configure the search. For example, in time series problems, values should be passed in for the gap and max_delay variables. n_splits (int, None): the number of CV splits, if applicable. Default 3. shuffle (bool): whether or not to shuffle the data before splitting, if applicable. Default True. random_state (int, np.random.RandomState): The random seed/state. Defaults to 0. Returns: sklearn.model_selection.BaseCrossValidator: data splitting method. """ problem_type = handle_problem_types(problem_type) data_splitter = None if problem_type == ProblemTypes.REGRESSION: data_splitter = KFold(n_splits=n_splits, random_state=random_state, shuffle=shuffle) elif problem_type in [ProblemTypes.BINARY, ProblemTypes.MULTICLASS]: data_splitter = StratifiedKFold(n_splits=n_splits, random_state=random_state, shuffle=shuffle) elif is_time_series(problem_type): if not problem_configuration: raise ValueError("problem_configuration is required for time series problem types") data_splitter = TimeSeriesSplit(n_splits=n_splits, gap=problem_configuration.get('gap'), max_delay=problem_configuration.get('max_delay')) if X.shape[0] > _LARGE_DATA_ROW_THRESHOLD: data_splitter = TrainingValidationSplit(test_size=_LARGE_DATA_PERCENT_VALIDATION, shuffle=True) return data_splitter
def stackable_regressors(helper_functions): stackable_regressors = [] for estimator_class in _all_estimators(): supported_problem_types = [handle_problem_types(pt) for pt in estimator_class.supported_problem_types] if (set(supported_problem_types) == {ProblemTypes.REGRESSION, ProblemTypes.TIME_SERIES_REGRESSION} and estimator_class.model_family not in _nonstackable_model_families and estimator_class.model_family != ModelFamily.ENSEMBLE): stackable_regressors.append(helper_functions.safe_init_component_with_njobs_1(estimator_class)) return stackable_regressors
def allowed_model_families(problem_type): """List the model types allowed for a particular problem type. Arguments: problem_types (ProblemTypes or str): binary, multiclass, or regression Returns: list[ModelFamily]: a list of model families """ estimators = [] problem_type = handle_problem_types(problem_type) for estimator in _all_estimators_used_in_search(): if problem_type in set( handle_problem_types(problem) for problem in estimator.supported_problem_types): estimators.append(estimator) return list(set([e.model_family for e in estimators]))
def stackable_classifiers(helper_functions): stackable_classifiers = [] for estimator_class in _all_estimators(): supported_problem_types = [handle_problem_types(pt) for pt in estimator_class.supported_problem_types] if (set(supported_problem_types) == {ProblemTypes.BINARY, ProblemTypes.MULTICLASS, ProblemTypes.TIME_SERIES_BINARY, ProblemTypes.TIME_SERIES_MULTICLASS} and estimator_class.model_family not in _nonstackable_model_families and estimator_class.model_family != ModelFamily.ENSEMBLE): stackable_classifiers.append(estimator_class) return stackable_classifiers
def make_data_splitter(X, y, problem_type, problem_configuration=None, n_splits=3, shuffle=True, random_state=None, random_seed=0): """Given the training data and ML problem parameters, compute a data splitting method to use during AutoML search. Arguments: X (ww.DataTable, pd.DataFrame): The input training data of shape [n_samples, n_features]. y (ww.DataColumn, pd.Series): The target training data of length [n_samples]. problem_type (ProblemType): The type of machine learning problem. problem_configuration (dict, None): Additional parameters needed to configure the search. For example, in time series problems, values should be passed in for the gap and max_delay variables. Defaults to None. n_splits (int, None): The number of CV splits, if applicable. Defaults to 3. shuffle (bool): Whether or not to shuffle the data before splitting, if applicable. Defaults to True. random_state (None, int): Deprecated - use random_seed instead. random_seed (int): Seed for the random number generator. Defaults to 0. Returns: sklearn.model_selection.BaseCrossValidator: Data splitting method. """ random_seed = deprecate_arg("random_state", "random_seed", random_state, random_seed) problem_type = handle_problem_types(problem_type) if is_time_series(problem_type): if not problem_configuration: raise ValueError( "problem_configuration is required for time series problem types" ) return TimeSeriesSplit( n_splits=n_splits, gap=problem_configuration.get('gap'), max_delay=problem_configuration.get('max_delay')) if X.shape[0] > _LARGE_DATA_ROW_THRESHOLD: if problem_type == ProblemTypes.REGRESSION: return TrainingValidationSplit( test_size=_LARGE_DATA_PERCENT_VALIDATION, shuffle=shuffle) elif problem_type in [ProblemTypes.BINARY, ProblemTypes.MULTICLASS]: return BalancedClassificationDataTVSplit( test_size=_LARGE_DATA_PERCENT_VALIDATION, shuffle=shuffle, random_seed=random_seed) if problem_type == ProblemTypes.REGRESSION: return KFold(n_splits=n_splits, random_state=random_seed, shuffle=shuffle) elif problem_type in [ProblemTypes.BINARY, ProblemTypes.MULTICLASS]: return BalancedClassificationDataCVSplit(n_splits=n_splits, random_seed=random_seed, shuffle=shuffle)
def test_binary_classification_estimators_predict_proba_col_order(helper_functions): X = pd.DataFrame({'input': np.concatenate([np.array([-1] * 100), np.array([1] * 100)])}) data = np.concatenate([np.zeros(100), np.ones(100)]) y = pd.Series(data) for estimator_class in _all_estimators_used_in_search(): supported_problem_types = [handle_problem_types(pt) for pt in estimator_class.supported_problem_types] if ProblemTypes.BINARY in supported_problem_types: estimator = helper_functions.safe_init_component_with_njobs_1(estimator_class) estimator.fit(X, y) predicted_proba = estimator.predict_proba(X).to_dataframe() expected = np.concatenate([(1 - data).reshape(-1, 1), data.reshape(-1, 1)], axis=1) np.testing.assert_allclose(expected, np.round(predicted_proba).values)
def make_pipeline_from_components(component_instances, problem_type, custom_name=None, random_state=None, random_seed=0): """Given a list of component instances and the problem type, an pipeline instance is generated with the component instances. The pipeline will be a subclass of the appropriate pipeline base class for the specified problem_type. The pipeline will be untrained, even if the input components are already trained. A custom name for the pipeline can optionally be specified; otherwise the default pipeline name will be 'Templated Pipeline'. Arguments: component_instances (list): a list of all of the components to include in the pipeline problem_type (str or ProblemTypes): problem type for the pipeline to generate custom_name (string): a name for the new pipeline random_state(int): Deprecated. Use random_seed instead. random_seed (int): Random seed used to intialize the pipeline. Returns: Pipeline instance with component instances and specified estimator created from given random state. Example: >>> components = [Imputer(), StandardScaler(), RandomForestClassifier()] >>> pipeline = make_pipeline_from_components(components, problem_type="binary") >>> pipeline.describe() """ random_seed = deprecate_arg("random_state", "random_seed", random_state, random_seed) for i, component in enumerate(component_instances): if not isinstance(component, ComponentBase): raise TypeError( "Every element of `component_instances` must be an instance of ComponentBase" ) if i == len(component_instances) - 1 and not isinstance( component, Estimator): raise ValueError( "Pipeline needs to have an estimator at the last position of the component list" ) if custom_name and not isinstance(custom_name, str): raise TypeError("Custom pipeline name must be a string") pipeline_name = custom_name problem_type = handle_problem_types(problem_type) class TemplatedPipeline(_get_pipeline_base_class(problem_type)): custom_name = pipeline_name component_graph = [c.__class__ for c in component_instances] return TemplatedPipeline( {c.name: c.parameters for c in component_instances}, random_seed=random_seed)
def get_estimators(problem_type, model_families=None): """Returns the estimators allowed for a particular problem type. Can also optionally filter by a list of model types. Arguments: problem_type (ProblemTypes or str): problem type to filter for model_families (list[ModelFamily] or list[str]): model families to filter for Returns: list[class]: a list of estimator subclasses """ if model_families is not None and not isinstance(model_families, list): raise TypeError("model_families parameter is not a list.") problem_type = handle_problem_types(problem_type) if model_families is None: model_families = allowed_model_families(problem_type) model_families = [ handle_model_family(model_family) for model_family in model_families ] all_model_families = allowed_model_families(problem_type) for model_family in model_families: if model_family not in all_model_families: raise RuntimeError( "Unrecognized model type for problem type %s: %s" % (problem_type, model_family)) estimator_classes = [] for estimator_class in _all_estimators_used_in_search(): if problem_type not in [ handle_problem_types(supported_pt) for supported_pt in estimator_class.supported_problem_types ]: continue if estimator_class.model_family not in model_families: continue estimator_classes.append(estimator_class) return estimator_classes
def __init__(self, problem_type, threshold=0.50): """Checks each column in the input to determine the uniqueness of the values in those columns. Arguments: problem_type (str or ProblemTypes): The specific problem type to data check for. e.g. 'binary', 'multiclass', 'regression, 'time series regression' threshold(float): The threshold to set as an upper bound on uniqueness for classification type problems or lower bound on for regression type problems. Defaults to 0.50. """ self.problem_type = handle_problem_types(problem_type) if threshold < 0 or threshold > 1: raise ValueError("threshold must be a float between 0 and 1, inclusive.") self.threshold = threshold
def __init__(self, problem_type, objective, n_unique=100): """Check if the target is invalid for the specified problem type. Arguments: problem_type (str or ProblemTypes): The specific problem type to data check for. e.g. 'binary', 'multiclass', 'regression, 'time series regression' objective (str or ObjectiveBase): Name or instance of the objective class. n_unique (int): Number of unique target values to store when problem type is binary and target incorrectly has more than 2 unique values. Non-negative integer. Defaults to 100. If None, stores all unique values. """ self.problem_type = handle_problem_types(problem_type) self.objective = get_objective(objective) if n_unique is not None and n_unique <= 0: raise ValueError("`n_unique` must be a non-negative integer value.") self.n_unique = n_unique
def make_pipeline(X, y, estimator, problem_type, custom_hyperparameters=None, text_columns=None): """Given input data, target data, an estimator class and the problem type, generates a pipeline class with a preprocessing chain which was recommended based on the inputs. The pipeline will be a subclass of the appropriate pipeline base class for the specified problem_type. Arguments: X (pd.DataFrame, ww.DataTable): The input data of shape [n_samples, n_features] y (pd.Series, ww.DataColumn): The target data of length [n_samples] estimator (Estimator): Estimator for pipeline problem_type (ProblemTypes or str): Problem type for pipeline to generate custom_hyperparameters (dictionary): Dictionary of custom hyperparameters, with component name as key and dictionary of parameters as the value text_columns (list): feature names which should be treated as text features. Defaults to None. Returns: class: PipelineBase subclass with dynamically generated preprocessing components and specified estimator """ X = _convert_to_woodwork_structure(X) y = _convert_to_woodwork_structure(y) problem_type = handle_problem_types(problem_type) if estimator not in get_estimators(problem_type): raise ValueError( f"{estimator.name} is not a valid estimator for problem type") preprocessing_components = _get_preprocessing_components( X, y, problem_type, text_columns, estimator) complete_component_graph = preprocessing_components + [estimator] if custom_hyperparameters and not isinstance(custom_hyperparameters, dict): raise ValueError( f"if custom_hyperparameters provided, must be dictionary. Received {type(custom_hyperparameters)}" ) hyperparameters = custom_hyperparameters base_class = _get_pipeline_base_class(problem_type) class GeneratedPipeline(base_class): custom_name = f"{estimator.name} w/ {' + '.join([component.name for component in preprocessing_components])}" component_graph = complete_component_graph custom_hyperparameters = hyperparameters return GeneratedPipeline
def get_default_primary_search_objective(problem_type): """Get the default primary search objective for a problem type. Arguments: problem_type (str or ProblemType): problem type of interest. Returns: ObjectiveBase: primary objective instance for the problem type. """ problem_type = handle_problem_types(problem_type) objective_name = {'binary': 'Log Loss Binary', 'multiclass': 'Log Loss Multiclass', 'regression': 'R2', 'time series regression': 'R2', 'time series binary': 'Log Loss Binary', 'time series multiclass': 'Log Loss Multiclass'}[problem_type.value] return get_objective(objective_name, return_instance=True)
def get_core_objectives(problem_type): """Returns all core objective instances associated with the given problem type. Core objectives are designed to work out-of-the-box for any dataset. Arguments: problem_type (str/ProblemTypes): Type of problem Returns: List of ObjectiveBase instances """ problem_type = handle_problem_types(problem_type) all_objectives_dict = _all_objectives_dict() objectives = [ obj() for obj in all_objectives_dict.values() if obj.is_defined_for_problem_type(problem_type) and obj not in get_non_core_objectives() ] return objectives
def __init__(self, problem_type, threshold, unique_count_threshold=10): """Checks each column in the input to determine the sparsity of the values in those columns. Arguments: problem_type (str or ProblemTypes): The specific problem type to data check for. 'multiclass' or 'time series multiclass' is the only accepted problem type. threshold (float): The threshold value, or percentage of each column's unique values, below which, a column exhibits sparsity. Should be between 0 and 1. unique_count_threshold (int): The minimum number of times a unique value has to be present in a column to not be considered "sparse." Default is 10. """ self.problem_type = handle_problem_types(problem_type) if not is_multiclass(self.problem_type): raise ValueError("Sparsity is only defined for multiclass problem types.") self.threshold = threshold if threshold < 0 or threshold > 1: raise ValueError("Threshold must be a float between 0 and 1, inclusive.") self.unique_count_threshold = unique_count_threshold if unique_count_threshold < 0 or not isinstance(unique_count_threshold, int): raise ValueError("Unique count threshold must be positive integer.")
def make_pipeline(X, y, estimator, problem_type, parameters=None, custom_hyperparameters=None, sampler_name=None): """Given input data, target data, an estimator class and the problem type, generates a pipeline class with a preprocessing chain which was recommended based on the inputs. The pipeline will be a subclass of the appropriate pipeline base class for the specified problem_type. Arguments: X (pd.DataFrame, ww.DataTable): The input data of shape [n_samples, n_features] y (pd.Series, ww.DataColumn): The target data of length [n_samples] estimator (Estimator): Estimator for pipeline problem_type (ProblemTypes or str): Problem type for pipeline to generate parameters (dict): Dictionary with component names as keys and dictionary of that component's parameters as values. An empty dictionary or None implies using all default values for component parameters. custom_hyperparameters (dictionary): Dictionary of custom hyperparameters, with component name as key and dictionary of parameters as the value sampler_name (str): The name of the sampler component to add to the pipeline. Only used in classification problems. Defaults to None Returns: PipelineBase object: PipelineBase instance with dynamically generated preprocessing components and specified estimator """ X = infer_feature_types(X) y = infer_feature_types(y) problem_type = handle_problem_types(problem_type) if estimator not in get_estimators(problem_type): raise ValueError(f"{estimator.name} is not a valid estimator for problem type") if not is_classification(problem_type) and sampler_name is not None: raise ValueError(f"Sampling is unsupported for problem_type {str(problem_type)}") preprocessing_components = _get_preprocessing_components(X, y, problem_type, estimator, sampler_name) complete_component_graph = preprocessing_components + [estimator] if custom_hyperparameters and not isinstance(custom_hyperparameters, dict): raise ValueError(f"if custom_hyperparameters provided, must be dictionary. Received {type(custom_hyperparameters)}") base_class = _get_pipeline_base_class(problem_type) return base_class(complete_component_graph, parameters=parameters, custom_hyperparameters=custom_hyperparameters)
def test_handle_problem_types(correct_problem_types): for problem_type in correct_problem_types: assert handle_problem_types(problem_type) == problem_type
def is_defined_for_problem_type(cls, problem_type): return handle_problem_types(problem_type) in cls.problem_types
def __init__(self, X_train=None, y_train=None, problem_type=None, objective='auto', max_iterations=None, max_time=None, patience=None, tolerance=None, data_splitter=None, allowed_pipelines=None, allowed_model_families=None, start_iteration_callback=None, add_result_callback=None, error_callback=None, additional_objectives=None, random_state=None, random_seed=0, n_jobs=-1, tuner_class=None, optimize_thresholds=False, ensembling=False, max_batches=None, problem_configuration=None, train_best_pipeline=True, pipeline_parameters=None, _pipelines_per_batch=5): """Automated pipeline search Arguments: X_train (pd.DataFrame, ww.DataTable): The input training data of shape [n_samples, n_features]. Required. y_train (pd.Series, ww.DataColumn): The target training data of length [n_samples]. Required for supervised learning tasks. problem_type (str or ProblemTypes): type of supervised learning problem. See evalml.problem_types.ProblemType.all_problem_types for a full list. objective (str, ObjectiveBase): The objective to optimize for. Used to propose and rank pipelines, but not for optimizing each pipeline during fit-time. When set to 'auto', chooses: - LogLossBinary for binary classification problems, - LogLossMulticlass for multiclass classification problems, and - R2 for regression problems. max_iterations (int): Maximum number of iterations to search. If max_iterations and max_time is not set, then max_iterations will default to max_iterations of 5. max_time (int, str): Maximum time to search for pipelines. This will not start a new pipeline search after the duration has elapsed. If it is an integer, then the time will be in seconds. For strings, time can be specified as seconds, minutes, or hours. patience (int): Number of iterations without improvement to stop search early. Must be positive. If None, early stopping is disabled. Defaults to None. tolerance (float): Minimum percentage difference to qualify as score improvement for early stopping. Only applicable if patience is not None. Defaults to None. allowed_pipelines (list(class)): A list of PipelineBase subclasses indicating the pipelines allowed in the search. The default of None indicates all pipelines for this problem type are allowed. Setting this field will cause allowed_model_families to be ignored. allowed_model_families (list(str, ModelFamily)): The model families to search. The default of None searches over all model families. Run evalml.pipelines.components.utils.allowed_model_families("binary") to see options. Change `binary` to `multiclass` or `regression` depending on the problem type. Note that if allowed_pipelines is provided, this parameter will be ignored. data_splitter (sklearn.model_selection.BaseCrossValidator): Data splitting method to use. Defaults to StratifiedKFold. tuner_class: The tuner class to use. Defaults to SKOptTuner. start_iteration_callback (callable): Function called before each pipeline training iteration. Callback function takes three positional parameters: The pipeline class, the pipeline parameters, and the AutoMLSearch object. add_result_callback (callable): Function called after each pipeline training iteration. Callback function takes three positional parameters: A dictionary containing the training results for the new pipeline, an untrained_pipeline containing the parameters used during training, and the AutoMLSearch object. error_callback (callable): Function called when `search()` errors and raises an Exception. Callback function takes three positional parameters: the Exception raised, the traceback, and the AutoMLSearch object. Must also accepts kwargs, so AutoMLSearch is able to pass along other appropriate parameters by default. Defaults to None, which will call `log_error_callback`. additional_objectives (list): Custom set of objectives to score on. Will override default objectives for problem type if not empty. random_state (int): Deprecated - use random_seed instead. random_seed (int): Seed for the random number generator. Defaults to 0. n_jobs (int or None): Non-negative integer describing level of parallelism used for pipelines. None and 1 are equivalent. If set to -1, all CPUs are used. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. ensembling (boolean): If True, runs ensembling in a separate batch after every allowed pipeline class has been iterated over. If the number of unique pipelines to search over per batch is one, ensembling will not run. Defaults to False. max_batches (int): The maximum number of batches of pipelines to search. Parameters max_time, and max_iterations have precedence over stopping the search. problem_configuration (dict, None): Additional parameters needed to configure the search. For example, in time series problems, values should be passed in for the gap and max_delay variables. train_best_pipeline (boolean): Whether or not to train the best pipeline before returning it. Defaults to True _pipelines_per_batch (int): The number of pipelines to train for every batch after the first one. The first batch will train a baseline pipline + one of each pipeline family allowed in the search. """ if X_train is None: raise ValueError( 'Must specify training data as a 2d array using the X_train argument' ) if y_train is None: raise ValueError( 'Must specify training data target values as a 1d vector using the y_train argument' ) try: self.problem_type = handle_problem_types(problem_type) except ValueError: raise ValueError( 'choose one of (binary, multiclass, regression) as problem_type' ) self.tuner_class = tuner_class or SKOptTuner self.start_iteration_callback = start_iteration_callback self.add_result_callback = add_result_callback self.error_callback = error_callback or log_error_callback self.data_splitter = data_splitter self.optimize_thresholds = optimize_thresholds self.ensembling = ensembling if objective == 'auto': objective = get_default_primary_search_objective( self.problem_type.value) objective = get_objective(objective, return_instance=False) self.objective = self._validate_objective(objective) if self.data_splitter is not None and not issubclass( self.data_splitter.__class__, BaseCrossValidator): raise ValueError("Not a valid data splitter") if not objective.is_defined_for_problem_type(self.problem_type): raise ValueError( "Given objective {} is not compatible with a {} problem.". format(self.objective.name, self.problem_type.value)) if additional_objectives is None: additional_objectives = get_core_objectives(self.problem_type) # if our main objective is part of default set of objectives for problem_type, remove it existing_main_objective = next( (obj for obj in additional_objectives if obj.name == self.objective.name), None) if existing_main_objective is not None: additional_objectives.remove(existing_main_objective) else: additional_objectives = [ get_objective(o) for o in additional_objectives ] additional_objectives = [ self._validate_objective(obj) for obj in additional_objectives ] self.additional_objectives = additional_objectives self.objective_name_to_class = { o.name: o for o in [self.objective] + self.additional_objectives } if not isinstance(max_time, (int, float, str, type(None))): raise TypeError( f"Parameter max_time must be a float, int, string or None. Received {type(max_time)} with value {str(max_time)}.." ) if isinstance(max_time, (int, float)) and max_time < 0: raise ValueError( f"Parameter max_time must be None or non-negative. Received {max_time}." ) if max_batches is not None and max_batches < 0: raise ValueError( f"Parameter max_batches must be None or non-negative. Received {max_batches}." ) if max_iterations is not None and max_iterations < 0: raise ValueError( f"Parameter max_iterations must be None or non-negative. Received {max_iterations}." ) self.max_time = convert_to_seconds(max_time) if isinstance( max_time, str) else max_time self.max_iterations = max_iterations self.max_batches = max_batches self._pipelines_per_batch = _pipelines_per_batch if not self.max_iterations and not self.max_time and not self.max_batches: self.max_batches = 1 logger.info("Using default limit of max_batches=1.\n") if patience and (not isinstance(patience, int) or patience < 0): raise ValueError( "patience value must be a positive integer. Received {} instead" .format(patience)) if tolerance and (tolerance > 1.0 or tolerance < 0.0): raise ValueError( "tolerance value must be a float between 0.0 and 1.0 inclusive. Received {} instead" .format(tolerance)) self.patience = patience self.tolerance = tolerance or 0.0 self._results = { 'pipeline_results': {}, 'search_order': [], 'errors': [] } self.random_seed = deprecate_arg("random_state", "random_seed", random_state, random_seed) self.n_jobs = n_jobs self.plot = None try: self.plot = PipelineSearchPlots(self) except ImportError: logger.warning( "Unable to import plotly; skipping pipeline search plotting\n") self._data_check_results = None self.allowed_pipelines = allowed_pipelines self.allowed_model_families = allowed_model_families self._automl_algorithm = None self._start = 0.0 self._baseline_cv_scores = {} self.show_batch_output = False self._validate_problem_type() self.problem_configuration = self._validate_problem_configuration( problem_configuration) self._train_best_pipeline = train_best_pipeline self._best_pipeline = None self._searched = False self.X_train = infer_feature_types(X_train) self.y_train = infer_feature_types(y_train) default_data_splitter = make_data_splitter( self.X_train, self.y_train, self.problem_type, self.problem_configuration, n_splits=3, shuffle=True, random_seed=self.random_seed) self.data_splitter = self.data_splitter or default_data_splitter self.pipeline_parameters = pipeline_parameters if pipeline_parameters is not None else {} self.search_iteration_plot = None self._interrupted = False self._engine = SequentialEngine( self.X_train, self.y_train, self, should_continue_callback=self._should_continue, pre_evaluation_callback=self._pre_evaluation_callback, post_evaluation_callback=self._post_evaluation_callback) if self.allowed_pipelines is None: logger.info("Generating pipelines to search over...") allowed_estimators = get_estimators(self.problem_type, self.allowed_model_families) logger.debug( f"allowed_estimators set to {[estimator.name for estimator in allowed_estimators]}" ) self.allowed_pipelines = [ make_pipeline(self.X_train, self.y_train, estimator, self.problem_type, custom_hyperparameters=self.pipeline_parameters) for estimator in allowed_estimators ] if self.allowed_pipelines == []: raise ValueError("No allowed pipelines to search") run_ensembling = self.ensembling if run_ensembling and len(self.allowed_pipelines) == 1: logger.warning( "Ensembling is set to True, but the number of unique pipelines is one, so ensembling will not run." ) run_ensembling = False if run_ensembling and self.max_iterations is not None: # Baseline + first batch + each pipeline iteration + 1 first_ensembling_iteration = ( 1 + len(self.allowed_pipelines) + len(self.allowed_pipelines) * self._pipelines_per_batch + 1) if self.max_iterations < first_ensembling_iteration: run_ensembling = False logger.warning( f"Ensembling is set to True, but max_iterations is too small, so ensembling will not run. Set max_iterations >= {first_ensembling_iteration} to run ensembling." ) else: logger.info( f"Ensembling will run at the {first_ensembling_iteration} iteration and every {len(self.allowed_pipelines) * self._pipelines_per_batch} iterations after that." ) if self.max_batches and self.max_iterations is None: self.show_batch_output = True if run_ensembling: ensemble_nth_batch = len(self.allowed_pipelines) + 1 num_ensemble_batches = (self.max_batches - 1) // ensemble_nth_batch if num_ensemble_batches == 0: logger.warning( f"Ensembling is set to True, but max_batches is too small, so ensembling will not run. Set max_batches >= {ensemble_nth_batch + 1} to run ensembling." ) else: logger.info( f"Ensembling will run every {ensemble_nth_batch} batches." ) self.max_iterations = ( 1 + len(self.allowed_pipelines) + self._pipelines_per_batch * (self.max_batches - 1 - num_ensemble_batches) + num_ensemble_batches) else: self.max_iterations = 1 + len( self.allowed_pipelines) + (self._pipelines_per_batch * (self.max_batches - 1)) self.allowed_model_families = list( set([p.model_family for p in (self.allowed_pipelines)])) logger.debug( f"allowed_pipelines set to {[pipeline.name for pipeline in self.allowed_pipelines]}" ) logger.debug( f"allowed_model_families set to {self.allowed_model_families}") if len(self.problem_configuration): pipeline_params = { **{ 'pipeline': self.problem_configuration }, **self.pipeline_parameters } else: pipeline_params = self.pipeline_parameters self._automl_algorithm = IterativeAlgorithm( max_iterations=self.max_iterations, allowed_pipelines=self.allowed_pipelines, tuner_class=self.tuner_class, random_seed=self.random_seed, n_jobs=self.n_jobs, number_features=self.X_train.shape[1], pipelines_per_batch=self._pipelines_per_batch, ensembling=run_ensembling, pipeline_params=pipeline_params)
def test_handle_incorrect_type(): error_msg = '`handle_problem_types` was not passed a str or ProblemTypes object' with pytest.raises(ValueError, match=error_msg): handle_problem_types(5)