AutomaticTimeSeries

class hana_ml.algorithms.pal.auto_ml.AutomaticTimeSeries(scorings=None, generations=None, population_size=None, offspring_size=None, elite_number=None, min_layer=None, max_layer=None, mutation_rate=None, crossover_rate=None, random_seed=None, config_dict=None, progress_indicator_id=None, fold_num=None, resampling_method=None, max_eval_time_mins=None, early_stop=None, percentage=None, gap_num=None, connections=None, alpha=None, delta=None, top_k_connections=None, top_k_pipelines=None, search_method=None, fine_tune_pipeline=None, fine_tune_resource=None)

AutomaticTimeSeries offers an intelligent search amongst machine learning pipelines for time series tasks. Each machine learning pipeline contains several operators such as preprocessors, time series models and transformer that follows API of hana-ml algorithms.

For AutomaticTimeSeries parameter mappings of hana_ml and HANA PAL, please refer to the doc page: Parameter Mappings

In addition, in order to better demonstrate the process, we also provide a series of visualizers such as PipelineProgressStatusMonitor, SimplePipelineProgressStatusMonitor, and BestPipelineReport, as well as a set of log management methods.

Parameters:
scoringsdict, optional

AutomaticTimeSeries supports multi-objective optimization with specified weights of each target. The goal is to maximize the target. Therefore, if you want to minimize the target, the weight of target needs to be negative.

The available target options are as follows:

  • EVAR: Explained Variance. Higher values indicate better performance. It is recommended to assign a positive weight to this metric.

  • MAE: Mean Absolute Error. Lower values indicate better performance. It is recommended to assign a negative weight to this metric.

  • MAPE: Mean Absolute Percentage Error. Lower values indicate better performance. It is recommended to assign a negative weight to this metric.

  • MAX_ERROR: The maximum absolute difference between the observed value and the expected value. Lower values indicate better performance. It is recommended to assign a negative weight to this metric.

  • MSE: Mean Squared Error. Lower values indicate better performance. It is recommended to assign a negative weight to this metric.

  • R2: R-squared. Higher values indicate better performance. It is recommended to assign a positive weight to this metric.

  • RMSE: Root Mean Squared Error. Lower values indicate better performance. It is recommended to assign a negative weight to this metric.

  • WMAPE: Weighted Mean Absolute Percentage Error. Lower values indicate better performance. It is recommended to assign a negative weight to this metric.

  • LAYERS: The number of operators. Lower values indicate better performance. It is recommended to assign a negative weight to this metric.

  • SPEC: Stock keeping oriented Prediction Error Costs. Lower values indicate better performance. It is recommended to assign a negative weight to this metric.

  • LAYERS: The number of operators. Lower values indicate better performance. It is recommended to assign a negative weight to this metric.

  • TIME: Represents the computational time in seconds used. Lower values indicate better performance. It is recommended to assign a negative weight to this metric.

Defaults to {MAE":-1.0, "EVAR":1.0} (minimize MAE and maximize EVAR).

generationsint, optional

The number of iterations of the pipeline optimization.

Defaults to 5.

population_sizeint, optional
  • When search_method takes the value of 'GA', population_size is the number of individuals in each generation in genetic programming algorithm. Having too few individuals can limit the possibilities of crossover and exploration of the search space to only a small portion. Conversely, if there are too many individuals, the performance of the genetic algorithm may slow down.

  • When search_method takes the value of 'random', population_size is the number of pipelines randomly generated and evaluated in random search.

Defaults to 20.

offspring_sizeint, optional

The number of offsprings to produce in each generation.

It controls the number of new individuals generated in each iteration by genetic operations, from population.

Defaults to the number of population_size.

elite_numberint, optional

The number of elite to output into result table.

Defaults to 1/4 of population_size.

min_layerint, optional

The minimum number of operators in a pipeline.

Defaults to 1.

max_layerint, optional

The maximum number of operators in a pipeline.

Defaults to 5.

mutation_ratefloat, optional

The mutation rate for the genetic programming algorithm.

Represents the random search ability. A suitable value can prevent the GA from falling into a local optimum.

The sum of mutation_rate and crossover_rate cannot be greater than 1.0. When the sum is less than 1.0, the remaining probability will be used to regenerate.

Defaults to 0.9.

crossover_ratefloat, optional

The crossover rate for the genetic programming algorithm.

Represents the local search ability. A larger crossover rate will cause GA to converge to a local optimum faster.

The sum of mutation_rate and crossover_rate cannot be greater than 1.0. When the sum is less than 1.0, the remaining probability will be used to regenerate.

Defaults to 0.1.

random_seedint, optional

Specifies the seed for random number generator. Use system time if not provided.

No default value.

config_dictstr or dict, optional

The customized configuration for the searching space.

  • {'light', 'default'}: use provided config_dict templates.

  • JSON format config_dict. It could be JSON string or dict.

If it is None, the default config_dict will be used.

Defaults to None.

progress_indicator_idstr, optional

Set the ID used to output monitoring information of the optimization progress.

No default value.

fold_numint, optional

The number of fold in the cross validation process. If the value is 0, the function will automatically determine the fold number.

Defaults to 5.

resampling_method{'rocv', 'block'}, optional

Specifies the resampling method for pipeline evaluation.

Defaults to 'rocv'.

max_eval_time_minsfloat, optional

Time limit to evaluate a single pipeline. The unit is minute.

Defaults to 0.0 (there is no time limit).

early_stopint, optional

Stop optimization progress when best pipeline is not updated for the give consecutive generations. 0 means there is no early stop.

Defaults to 5.

percentagefloat, optional

Percentage between training data and test data. Only applicable when resampling_method is 'block'.

Defaults to 0.7.

gap_numint, optional

Number of samples to exclude from the end of each train set before the test set.

Defaults to 0.

connectionsstr or dict, optional

Specifies the connections in the Connection constrained Optimization. The options are:

  • 'default'

  • customized connections json string or a dict.

Defaults to None. If connections is not provided, connection constrained optimization is not applied.

alphafloat, optional

Adjusts rejection probability in connection optimization.

Valid only when connections is set.

Defaults to 0.1.

deltafloat, optional

Controls the increase rate of connection weights.

Valid only when connections is set.

Defaults to 1.0.

top_k_connectionsint, optional

The number of top connections used to generate optimal connections.

Valid only when connections is set.

Defaults to 1/2 of (connection size in connections).

top_k_pipelinesint, optional

The number of pipelines used to update connections in each iteration.

Valid only when connections is set.

search_methodstr, optional

Optimization algorithm used in AutoML.

  • 'GA': Genetic Algorithm

  • 'random': Random Search

Defaults to 'GA'.

Defaults to 1/2 of offspring_size.

fine_tune_pipelineint, optional

Specifies whether or not to fine-tune the pipelines generated by the genetic algorithm.

Valid only when search_method takes the value of 'GA'.

Defaults to False.

fine_tune_resourceint, optional

Specifies the resource limit to use for fine-tuning the pipelines generated by the genetic algorithm.

Valid only when fine_tune_pipeline is set as True.

Defaults to the value of population_size.

References

Under the given config_dict and scoring, AutomaticTimeSeries uses genetic programming to to search for the best valid pipeline. Please see Genetic Optimization in AutoML for more details.

Examples

Create an AutomaticTimeSeries instance:

>>> progress_id = "automl_{}".format(uuid.uuid1())
>>> auto_ts = AutomaticTimeSeries(generations=2,
                                  population_size=5,
                                  offspring_size=5,
                                  progress_indicator_id=progress_id)
>>> auto_ts.enable_workload_class("MY_WORKLOAD_CLASS")

Invoke a PipelineProgressStatusMonitor instance:

>>> progress_status_monitor = PipelineProgressStatusMonitor(connection_context=dataframe.ConnectionContext(url, port, user, pwd),
                                                            automatic_obj=auto_ts)
>>> progress_status_monitor.start()
>>> auto_ts.fit(data=df_ts, key='ID', endog="SERIES")

Output:

../../_images/progress_ts.png

Show the best pipeline:

>>> print(auto_ts.best_pipeline_.collect())
   ID                                           PIPELINE      0   0  {"SingleExpSm":{"args":{"ALPHA":0.6,"PHI":0.3}...

Plot the best pipeline:

>>> BestPipelineReport(auto_ts).generate_notebook_iframe()
../../_images/best_pipeline_ts.png

Make prediction:

>>> res = auto_ts.predict(data=df_predict)

If you want to use an existing pipeline to fit and predict:

>>> pipeline = auto_ts.best_pipeline_.collect().iat[0, 1]
>>> auto_ts.fit(data=df_ts, pipeline=pipeline)
>>> res = auto_ts.predict(data=df_predict)
Attributes:
best_pipeline_: DataFrame

Best pipelines selected, structured as follows:

  • 1st column: ID, type INTEGER, pipeline IDs.

  • 2nd column: PIPELINE, type NVARCHAR, pipeline contents.

  • 3rd column: SCORES, type NVARCHAR, scoring metrics for pipeline.

Available only when the pipeline parameter is not specified during the fitting process.

model_DataFrame or a list of DataFrames

If pipeline is not None, structured as follows

  • 1st column: ROW_INDEX

  • 2nd column: MODEL_CONTENT

If auto-ml is enabled, structured as follows

  • 1st DataFrame:

    • 1st column: ROW_INDEX

    • 2nd column: MODEL_CONTENT

  • 2nd DataFrame: best_pipeline_

info_DataFrame

Related info/statistics for AutomaticTimeSeries pipeline fitting, structured as follows:

  • 1st column: STAT_NAME

  • 2nd column: STAT_VALUE

Methods

cleanup_progress_log(connection_context)

Clean up the progress log.

delete_config_dict([operator_name, ...])

Deletes the content of the config dict.

disable_auto_sql_content([disable])

Disable auto SQL content logging.

disable_log_cleanup([disable])

Disable the log clean up.

disable_mlflow_autologging()

Disable the mlflow autologging.

disable_workload_class_check()

Disable the workload class check.

display_config_dict([operator_name, category])

Displays the config dict.

display_progress_table(connection_context)

Return the progress table.

enable_mlflow_autologging([schema, meta, ...])

Enable the mlflow autologging.

evaluate(data[, pipeline, key, endog, exog, ...])

This function is to evaluate the pipeline.

fit(data[, key, endog, exog, pipeline, ...])

The fit function for AutomaticTimeSeries.

get_best_pipeline()

Return the best pipeline.

get_config_dict()

Return the config_dict.

get_model_metrics()

Get the model metrics.

get_optimal_config_dict()

Return the optimal config_dict.

get_optimal_connections()

Return the optimal connections.

get_score_metrics()

Get the score metrics.

get_workload_classes(connection_context)

Return the available workload classes information.

make_future_dataframe([data, key, periods, ...])

Create a new dataframe for time series prediction.

persist_progress_log()

Persist the progress log.

pipeline_plot([name, iframe_height])

Pipeline plot.

predict(data[, key, exog, model, ...])

Predict function for AutomaticTimeSeries.

reset_config_dict([connection_context, ...])

Reset config dict.

score(data[, key, endog, exog, model, ...])

Pipeline model score function.

set_progress_log_level(log_level)

Set progress log level to output scorings.

update_category_map(connection_context)

Updates the list of operators.

update_config_dict(operator_name[, ...])

Updates the config dict.

fit(data, key=None, endog=None, exog=None, pipeline=None, categorical_variable=None, background_size=None, background_sampling_seed=None, model_table_name=None, lag=None, lag_features=None)

The fit function for AutomaticTimeSeries.

Parameters:
dataDataFrame

The input time-series data for training.

keystr, optional

Specifies the column that represents the ordering of time-series data.

If data is indexed by a single column, then key defaults to that index column; otherwise key must be specified(i.e. is mandatory).

endogstr, optional

Specifies the endogenous variable for time-series data.

Defaults to the 1st non-key column of data

exogstr, optional

Specifies the exogenous variables for time-series data.

Defaults to all non-key, non-endog columns in data.

pipelinestr or dict, optional

Directly use the input pipeline to fit.

Defaults to None.

categorical_variablestr or a list of str, optional

Specifies which INTEGER columns should be treated as categorical, with all other INTEGER columns treated as continuous.

No default value.

model_table_namestr, optional

Specifies the HANA model table name instead of the generated temporary table.

Defaults to None.

lagint, a list of int or dict, optional

The number of previous time stamp data used for generating features in current time stamp. Only valid when operator is HGBT_TimeSeries or MLR_TimeSeries.

If lag is a integer or a list of integer, both content of operators 'HGBT_TimeSeries' and 'MLR_TimeSeries' will be updated.

If lag is a dictionary, the key of this dictionary is the name of operator and value could be a integer, a list of integer or a dictionary of range (start, step, stop). Example : {"HGBT_TimeSeries" : 5}, or {"HGBT_TimeSeries" : [5, 7, 9]} or {"HGBT_TimeSeries" : {"range":[1,3,10]}}.

Defaults to minimum of 100 and (data size)/10.

lag_featuresstr, a list of strings or dict, optional

The name of features in time series data used for generating new data features. The name of target column should not be contained. Only valid when operator is HGBT_TimeSeries or MLR_TimeSeries.

If lag_features is a string or a list of strings, both content of operators 'HGBT_TimeSeries' and 'MLR_TimeSeries' will be updated.

If lag_features is a dictionary, the key of this dictionary is the name of operator and value could be a string or a list of strings. Example : {"MLR_TimeSeries" : "FEATURE_A"}, or {"MLR_TimeSeries" : ["FEATURE_A", "FEATURE_B", "FEATURE_C"]}.

Defaults to None.

Returns:
A fitted object of class "AutomaticTimeSeries".
predict(data, key=None, exog=None, model=None, show_explainer=False, predict_args=None)

Predict function for AutomaticTimeSeries.

Parameters:
dataDataFrame

The input time-series data to be predicted.

keystr, optional

Specifies the column that represents the ordering of the input time-series data.

If data is indexed by a single column, then key defaults to that index column; otherwise key must be specified(i.e. is mandatory).

exogstr or a list of str, optional

Names of the exogenous variables in data.

Defaults to all non-key columns if not provided.

modelDataFrame, optional

The model to be used for prediction.

Defaults to the fitted model(i.e. self.model_).

show_explainerbool, optional

Reserved paramter for future implementation of SHAP Explainer.

Currently ineffective.

predict_argsdict, optional

Specifies estimator-specific parameters passed to the predict method.

If not None, it must be specified as a dict with one of the following format:

  • key for estimator name, and value for estimator-specific parameter setting in a dict. For example {'RDT_Classifier':{'block_size': 5}, 'NB_Classifier':{'laplace':1.0}}.

Defaults to None(i.e. no estimator-specific predict parameter provided).

Returns:
DataFrame

Predicted result.

evaluate(data, pipeline=None, key=None, endog=None, exog=None, categorical_variable=None, resampling_method=None, fold_num=None, random_state=None, percentage=None, gap_num=None)

This function is to evaluate the pipeline.

Parameters:
dataDataFrame

Data for pipeline evaluation.

pipelinejson str or dict

Pipeline to be evaluated.

keystr, optional

Specifies the column that represents the ordering of the input time-series data.

If data is indexed by a single column, then key defaults to that index column; otherwise key must be specified(i.e. is mandatory).

endogstr, optional

Specifies the endogenous variable for time-series data.

Defaults to the 1st non-key column of data .

exogstr, optional

Specifies the exogenous variables for time-series data.

Defaults to all non-key, non-endog columns in data.

categorical_variablestr or a list of str, optional

Specifies which INTEGER columns should be treated as categorical, with all other INTEGER columns treated as continuous.

No default value.

resampling_method{'rocv', 'block'}, optional

The resampling method for pipeline model evaluation.

Defaults to 'rocv'.

fold_numint, optional

The fold number for cross validation. If the value is 0, the function will automatically determine the fold number.

Defaults to 5.

random_stateint, optional

Specifies the seed for random number generator.

  • 0: Uses the current time (in seconds) as the seed.

  • Others: Uses the specified value as the seed.

percentagefloat, optional

Percentage between training data and test data. Only applicable when resampling_method is 'block'.

Defaults to 0.7.

gap_numint, optional

Number of samples to exclude from the end of each train set before the test set.

Defaults to 0.

Returns:
DataFrame

Scores.

score(data, key=None, endog=None, exog=None, model=None, predict_args=None)

Pipeline model score function.

Parameters:
dataDataFrame

Data for pipeline model scoring.

keystr, optional

Specifies the column that represents the ordering of the input time-series data.

If data is indexed by a single column, then key defaults to that index column; otherwise key must be specified(i.e. is mandatory).

endogstr, optional

Specifies the endogenous variable for time-series data.

Defaults to the 1st non-key column of data .

exogstr, optional

Specifies the exogenous variables for time-series data.

Defaults to all non-key, non-endog columns in data.

modelDataFrame, optional

The pipeline model used to make predictions.

Defaults to the fitted pipeline model(i.e. self.model_).

predict_argsdict, optional

Specifies estimator-specific parameters passed to the predict phase of the score method.

If not None, it must be specified as a dict with one of the following format

  • key for estimator name, and value for estimator-specific parameter setting in a dict. For example {'RDT_Classifier':{'block_size': 5}, 'NB_Classifier':{'laplace':1.0}}.

Defaults to None(i.e. no estimator-specific predict parameter provided).

Returns:
DataFrames

DataFrame 1 : Prediction result for the input data, structured as follows: - 1st column, ID of input data. - 2nd column, SCORE, forecast value. - 3rd column, REASON CODE, feature attributions(currently All NULLs). - 4th & 5th column, placeholder columns for future implementations.

DataFrame 2 : Statistics.

reset_config_dict(connection_context=None, template_type='default')

Reset config dict.

Parameters:
connection_contextConnectionContext, optional

If it is set, the default config dict will use the one stored in a SAP HANA instance.

Defaults to None.

template_type{'default', 'light'}, optional

HANA config dict type.

Defaults to 'default'.

cleanup_progress_log(connection_context)

Clean up the progress log.

Parameters:
connection_contextConnectionContext

The connection object to a SAP HANA database.

delete_config_dict(operator_name=None, category=None, param_name=None)

Deletes the content of the config dict.

Parameters:
operator_namestr, optional

Deletes the operator based on the given name in the config dict.

Defaults to None.

categorystr, optional

Deletes the whole given category in the config dict.

Defaults to None.

param_namestr, optional

Deletes the parameter based on the given name once the operator name is provided.

Defaults to None.

disable_auto_sql_content(disable=True)

Disable auto SQL content logging. Use AFL's default progress logging.

disable_log_cleanup(disable=True)

Disable the log clean up.

disable_mlflow_autologging()

Disable the mlflow autologging.

disable_workload_class_check()

Disable the workload class check. Please note that the AutomaticClassification/AutomaticRegression/AutomaticTimeSeries may cause large resource. Without setting workload class, there's no resource restriction on the training process.

display_config_dict(operator_name=None, category=None)

Displays the config dict.

Parameters:
operator_namestr, optional

Only displays the information on the given operator name.

Defaults to None.

categorystr, optional

Only displays the information on the given category.

Defaults to None.

display_progress_table(connection_context)

Return the progress table.

Parameters:
connection_contextConnectionContext

The connection object to a SAP HANA database.

Returns:
DataFrame

Progress table.

enable_mlflow_autologging(schema=None, meta=None, is_exported=False, registered_model_name=None)

Enable the mlflow autologging.

Parameters:
schemastr, optional

Defines the model storage schema for mlflow autologging.

Defaults to the current schema.

metastr, optional

Defines the model storage meta table for mlflow autologging.

Defaults to 'HANAML_MLFLOW_MODEL_STORAGE'.

is_exportedbool, optional

Determines whether export a HANA model to mlflow.

Defaults to False.

registered_model_namestr, optional

MLFlow registered_model_name.

Defaults to None.

get_best_pipeline()

Return the best pipeline.

get_config_dict()

Return the config_dict.

get_model_metrics()

Get the model metrics.

Returns:
DataFrame

The model metrics.

get_optimal_config_dict()

Return the optimal config_dict. Only available when connections is used.

get_optimal_connections()

Return the optimal connections. Only available when connections is used.

get_score_metrics()

Get the score metrics.

Returns:
DataFrame

The score metrics.

get_workload_classes(connection_context)

Return the available workload classes information.

Parameters:
connection_contextstr, optional

The connection to a SAP HANA instance.

make_future_dataframe(data=None, key=None, periods=1, increment_type='seconds')

Create a new dataframe for time series prediction.

Parameters:
dataDataFrame, optional

The training data contains the index.

Defaults to the data used in the fit().

keystr, optional

The index defined in the training data.

Defaults to the specified key in fit function or the data.index or the first column of the data.

periodsint, optional

The number of rows created in the predict dataframe.

Defaults to 1.

increment_type{'seconds', 'days', 'months', 'years'}, optional

The increment type of the time series.

Defaults to 'seconds'.

Returns:
DataFrame
persist_progress_log()

Persist the progress log.

pipeline_plot(name='my_pipeline', iframe_height=450)

Pipeline plot.

Parameters:
namestr, optional

The name of the pipeline plot.

Defaults to 'my_pipeline'.

iframe_heightint, optional

The display height.

Defaults to 450.

set_progress_log_level(log_level)

Set progress log level to output scorings.

Parameters:
log_level: {'full', 'full_best', 'specified'}

'full' prints all scores. 'full_best' prints all scores only for the 'current_best' of each generation; other pipelines print only the scores specified by SCORINGS. 'Specified' means all pipelines print only the specified scores.

update_category_map(connection_context)

Updates the list of operators.

Parameters:
connection_contextstr, optional

The connection to a SAP HANA instance.

update_config_dict(operator_name, param_name=None, param_config=None)

Updates the config dict.

Parameters:
operator_namestr

The name of operator.

param_namestr, optional

The parameter name to be updated. If the parameter name doesn't exist in the config dict, it will create a new one.

Defaults to None.

param_configany, optional

The parameter config value.

Defaults to None.

Inherited Methods from PALBase

Besides those methods mentioned above, the AutomaticTimeSeries class also inherits methods from PALBase class, please refer to PAL Base for more details.