Skip to content

getml.pipeline.Pipeline

A Pipeline is the main class for feature learning and prediction.

PARAMETER DESCRIPTION
data_model

Abstract representation of the data_model, which defines the abstract relationships between the tables. Required for the feature learners.

TYPE: Optional[DataModel] DEFAULT: None

peripheral

Abstract representations of the additional tables used to augment the information provided in population. These have to be the same objects that were join ed onto the population Placeholder. Their order determines the order of the peripheral DataFrame passed to the 'peripheral_tables' argument in check, fit, predict, score, and transform, if you pass the data frames as a list. If you omit the peripheral placeholders, they will be inferred from the data model and ordered alphabetically.

TYPE: Optional[List[Placeholder]] DEFAULT: None

preprocessors

The preprocessor(s) to be used. Must be from preprocessors. A single preprocessor does not have to be wrapped in a list.

TYPE: Optional[Union[CategoryTrimmer, EmailDomain, Imputation, Mapping, Seasonal, Substring, TextFieldSplitter, List[Union[CategoryTrimmer, EmailDomain, Imputation, Mapping, Seasonal, Substring, TextFieldSplitter]]]] DEFAULT: None

feature_learners

The feature learner(s) to be used. Must be from feature_learning. A single feature learner does not have to be wrapped in a list.

TYPE: Optional[Union[Union[Fastboost, FastProp, Multirel, Relboost, RelMT], List[Union[Fastboost, FastProp, Multirel, Relboost, RelMT]]]] DEFAULT: None

feature_selectors

Predictor(s) used to select the best features. Must be from predictors. A single feature selector does not have to be wrapped in a list. Make sure to also set share_selected_features.

TYPE: Optional[Union[Union[LinearRegression, LogisticRegression, XGBoostClassifier, XGBoostRegressor, ScaleGBMClassifier, ScaleGBMRegressor], List[Union[LinearRegression, LogisticRegression, XGBoostClassifier, XGBoostRegressor, ScaleGBMClassifier, ScaleGBMRegressor]]]] DEFAULT: None

predictors

Predictor(s) used to generate the predictions. If more than one predictor is passed, the predictions generated will be averaged. Must be from predictors. A single predictor does not have to be wrapped in a list.

TYPE: Optional[Union[LinearRegression, LogisticRegression, XGBoostClassifier, XGBoostRegressor, ScaleGBMClassifier, ScaleGBMRegressor, List[Union[LinearRegression, LogisticRegression, XGBoostClassifier, XGBoostRegressor, ScaleGBMClassifier, ScaleGBMRegressor]]]] DEFAULT: None

loss_function

The loss function to use for the feature learners.

TYPE: Optional[str] DEFAULT: None

tags

Tags exist to help you organize your pipelines. You can add any tags that help you remember what you were trying to do.

TYPE: Optional[List[str]] DEFAULT: None

include_categorical

Whether you want to pass categorical columns in the population table to the predictor.

TYPE: bool DEFAULT: False

share_selected_features

The share of features you want the feature selection to keep. When set to 0.0, then all features will be kept.

TYPE: float DEFAULT: 0.5

Example

We assume that you have already set up your preprocessors (refer to preprocessors), your feature learners (refer to feature_learning) as well as your feature selectors and predictors (refer to predictors, which can be used for prediction and feature selection).

You might also want to refer to DataFrame, View, DataModel, Container, Placeholder and StarSchema.

If you want to create features for a time series problem, the easiest way to do so is to use the TimeSeries abstraction.

Note that this example is taken from the robot notebook .

# All rows before row 10500 will be used for training.
split = getml.data.split.time(data_all, "rowid", test=10500)

time_series = getml.data.TimeSeries(
    population=data_all,
    time_stamps="rowid",
    split=split,
    lagged_targets=False,
    memory=30,
)

pipe = getml.Pipeline(
    data_model=time_series.data_model,
    feature_learners=[...],
    predictors=...
)

pipe.check(time_series.train)

pipe.fit(time_series.train)

pipe.score(time_series.test)

# To generate predictions on new data,
# it is sufficient to use a Container.
# You don't have to recreate the entire
# TimeSeries, because the abstract data model
# is stored in the pipeline.
container = getml.data.Container(
    population=population_new,
)

# Add the data as a peripheral table, for the
# self-join.
container.add(population=population_new)

predictions = pipe.predict(container.full)
Example

If your data can be organized in a simple star schema, you can use StarSchema. StarSchema unifies Container and DataModel:

Note that this example is taken from the loans notebook .

# First, we insert our data into a StarSchema.
# population_train and population_test are either
# DataFrames or Views. The population table
# defines the statistical population of your
# machine learning problem and contains the
# target variables.
star_schema = getml.data.StarSchema(
    train=population_train,
    test=population_test
)

# meta, order and trans are either
# DataFrames or Views.
# Because this is a star schema,
# all joins take place on the population
# table.
star_schema.join(
    trans,
    on="account_id",
    time_stamps=("date_loan", "date")
)

star_schema.join(
    order,
    on="account_id",
)

star_schema.join(
    meta,
    on="account_id",
)

# Now you can insert your data model,
# your preprocessors, feature learners,
# feature selectors and predictors
# into the pipeline.
# Note that the pipeline only knows
# the abstract data model, but hasn't
# seen the actual data yet.
pipe = getml.Pipeline(
    data_model=star_schema.data_model,
    preprocessors=[mapping],
    feature_learners=[fast_prop],
    feature_selectors=[feature_selector],
    predictors=predictor,
)

# Now, we pass the actual data.
# This passes 'population_train' and the
# peripheral tables (meta, order and trans)
# to the pipeline.
pipe.check(star_schema.train)

pipe.fit(star_schema.train)

pipe.score(star_schema.test)
Example

StarSchema is simpler, but cannot be used for more complex data models. The general approach is to use Container and DataModel:

# First, we insert our data into a Container.
# population_train and population_test are either
# DataFrames or Views.
container = getml.data.Container(
    train=population_train,
    test=population_test
)

# meta, order and trans are either
# DataFrames or Views. They are given
# aliases, so we can refer to them in the
# DataModel.
container.add(
    meta=meta,
    order=order,
    trans=trans
)

# Freezing makes the container immutable.
# This is not required, but often a good idea.
container.freeze()

# The abstract data model is constructed
# using the DataModel class. A data model
# does not contain any actual data. It just
# defines the abstract relational structure.
dm = getml.data.DataModel(
    population_train.to_placeholder("population")
)

dm.add(getml.data.to_placeholder(
    meta=meta,
    order=order,
    trans=trans)
)

dm.population.join(
    dm.trans,
    on="account_id",
    time_stamps=("date_loan", "date")
)

dm.population.join(
    dm.order,
    on="account_id",
)

dm.population.join(
    dm.meta,
    on="account_id",
)

# Now you can insert your data model,
# your preprocessors, feature learners,
# feature selectors and predictors
# into the pipeline.
# Note that the pipeline only knows
# the abstract data model, but hasn't
# seen the actual data yet.
pipe = getml.Pipeline(
    data_model=dm,
    preprocessors=[mapping],
    feature_learners=[fast_prop],
    feature_selectors=[feature_selector],
    predictors=predictor,
)

# This passes 'population_train' and the
# peripheral tables (meta, order and trans)
# to the pipeline.
pipe.check(container.train)

pipe.fit(container.train)

pipe.score(container.test)

Technically, you don't actually have to use a Container. You might as well do this (in fact, a Container is just syntactic sugar for this approach):

pipe.check(
    population_train,
    {"meta": meta, "order": order, "trans": trans},
)

pipe.fit(
    population_train,
    {"meta": meta, "order": order, "trans": trans},
)

pipe.score(
    population_test,
    {"meta": meta, "order": order, "trans": trans},
)
Or you could even do this. The order of the peripheral tables can be inferred from the __repr__ method of the pipeline, and it is usually in alphabetical order.

pipe.check(
    population_train,
    [meta, order, trans],
)

pipe.fit(
    population_train,
    [meta, order, trans],
)

pipe.score(
    population_test,
    [meta, order, trans],
)
Source code in getml/pipeline/pipeline.py
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
def __init__(
    self,
    data_model: Optional[DataModel] = None,
    peripheral: Optional[List[Placeholder]] = None,
    preprocessors: Optional[
        Union[
            CategoryTrimmer,
            EmailDomain,
            Imputation,
            Mapping,
            Seasonal,
            Substring,
            TextFieldSplitter,
            List[
                Union[
                    CategoryTrimmer,
                    EmailDomain,
                    Imputation,
                    Mapping,
                    Seasonal,
                    Substring,
                    TextFieldSplitter,
                ]
            ],
        ],
    ] = None,
    feature_learners: Optional[
        Union[
            Union[Fastboost, FastProp, Multirel, Relboost, RelMT],
            List[Union[Fastboost, FastProp, Multirel, Relboost, RelMT]],
        ]
    ] = None,
    feature_selectors: Optional[
        Union[
            Union[
                LinearRegression,
                LogisticRegression,
                XGBoostClassifier,
                XGBoostRegressor,
                ScaleGBMClassifier,
                ScaleGBMRegressor,
            ],
            List[
                Union[
                    LinearRegression,
                    LogisticRegression,
                    XGBoostClassifier,
                    XGBoostRegressor,
                    ScaleGBMClassifier,
                    ScaleGBMRegressor,
                ]
            ],
        ],
    ] = None,
    predictors: Optional[
        Union[
            LinearRegression,
            LogisticRegression,
            XGBoostClassifier,
            XGBoostRegressor,
            ScaleGBMClassifier,
            ScaleGBMRegressor,
            List[
                Union[
                    LinearRegression,
                    LogisticRegression,
                    XGBoostClassifier,
                    XGBoostRegressor,
                    ScaleGBMClassifier,
                    ScaleGBMRegressor,
                ]
            ],
        ]
    ] = None,
    loss_function: Optional[str] = None,
    tags: Optional[List[str]] = None,
    include_categorical: bool = False,
    share_selected_features: float = 0.5,
) -> None:
    data_model = data_model or DataModel("population")

    if not isinstance(data_model, DataModel):
        raise TypeError("'data_model' must be a getml.data.DataModel.")

    peripheral = peripheral or _infer_peripheral(data_model.population)

    preprocessors = preprocessors or []

    feature_learners = feature_learners or []

    feature_selectors = feature_selectors or []

    predictors = predictors or []

    tags = tags or []

    if not isinstance(preprocessors, list):
        preprocessors = [preprocessors]

    if not isinstance(feature_learners, list):
        feature_learners = [feature_learners]

    if not isinstance(feature_selectors, list):
        feature_selectors = [feature_selectors]

    if not isinstance(predictors, list):
        predictors = [predictors]

    if not isinstance(peripheral, list):
        peripheral = [peripheral]

    if not isinstance(tags, list):
        tags = [tags]

    self._id: str = NOT_FITTED

    self.type = "Pipeline"

    loss_function = (
        loss_function
        or (
            [fl.loss_function for fl in feature_learners if fl.loss_function]
            or ["SquareLoss"]
        )[0]
    )

    feature_learners = [
        _handle_loss_function(fl, loss_function) for fl in feature_learners
    ]

    self.data_model = data_model
    self.feature_learners = feature_learners
    self.feature_selectors = feature_selectors
    self.include_categorical = include_categorical
    self.loss_function = loss_function
    self.peripheral = peripheral
    self.predictors = predictors
    self.preprocessors = preprocessors
    self.share_selected_features = share_selected_features
    self.tags = Tags(tags)

    self._metadata: Optional[AllMetadata] = None

    self._scores: Dict[str, Any] = {}

    self._targets: List[str] = []

    setattr(type(self), "_supported_params", list(self.__dict__.keys()))

    self._validate()

accuracy property

accuracy: Union[float, List[float]]

A convenience wrapper to retrieve the accuracy of the latest scoring run (the last time .score() was called) on the pipeline.

For programmatic access use metrics.

RETURNS DESCRIPTION
Union[float, List[float]]

The accuracy of the pipeline.

auc property

A convenience wrapper to retrieve the auc of the latest scoring run (the last time .score() was called) on the pipeline.

For programmatic access use metrics.

RETURNS DESCRIPTION
Union[float, List[float]]

The auc of the pipeline.

columns property

columns: Columns

Columns object that can be used to handle information about the original columns utilized by the feature learners.

RETURNS DESCRIPTION
Columns

The columns object.

cross_entropy property

cross_entropy: Union[float, List[float]]

A convenience wrapper to retrieve the cross entropy of the latest scoring run (the last time .score() was called) on the pipeline.

For programmatic access use metrics.

RETURNS DESCRIPTION
Union[float, List[float]]

The cross entropy of the pipeline.

features property

features: Features

Features object that can be used to handle the features generated by the feature learners.

RETURNS DESCRIPTION
Features

The features object.

fitted property

fitted: bool

Whether the pipeline has already been fitted.

RETURNS DESCRIPTION
bool

Whether the pipeline has already been fitted.

mae property

A convenience wrapper to retrieve the mae of the latest scoring run (the last time .score() was called) on the pipeline.

For programmatic access use metrics.

RETURNS DESCRIPTION
Union[float, List[float]]

The mae of the pipeline.

plots property

plots: Plots

Plots object that can be used to generate plots like an ROC curve or a lift curve.

RETURNS DESCRIPTION
Plots

The plots object.

id property

id: str

ID of the pipeline. This is used to uniquely identify the pipeline on the Engine.

RETURNS DESCRIPTION
str

The ID of the pipeline.

is_classification property

is_classification: bool

Whether the pipeline can be used for classification problems.

RETURNS DESCRIPTION
bool

Whether the pipeline can be used for classification problems.

is_regression property

is_regression: bool

Whether the pipeline can be used for regression problems.

RETURNS DESCRIPTION
bool

Whether the pipeline can be used for regression problems.

metadata property

metadata: Optional[AllMetadata]

Contains information on the data frames that were passed to .fit(...). The roles contained therein can be directly passed to existing data frames to correctly reassign the roles of existing columns. If the pipeline has not been fitted, this is None.

RETURNS DESCRIPTION
Optional[AllMetadata]

The metadata of the pipeline.

name property

name: str

Returns the ID of the pipeline. The name property is kept for backward compatibility.

RETURNS DESCRIPTION
str

The ID of the pipeline.

rmse property

rmse: Union[float, List[float]]

A convenience wrapper to retrieve the rmse of the latest scoring run (the last time .score() was called) on the pipeline.

For programmatic access use metrics.

RETURNS DESCRIPTION
Union[float, List[float]]

The rmse of the pipeline.

rsquared property

rsquared: Union[float, List[float]]

A convenience wrapper to retrieve the rsquared of the latest scoring run (the last time .score() was called) on the pipeline.

For programmatic access use metrics.

RETURNS DESCRIPTION
Union[float, List[float]]

The rsquared of the pipeline.

scores property

scores: Scores

Contains all scores generated by score

RETURNS DESCRIPTION
Scores

A container that holds the scores for the pipeline.

scored property

scored: bool

Whether the pipeline has been scored.

RETURNS DESCRIPTION
bool

Whether the pipeline has been scored.

tables property

tables: Tables

Tables object that can be used to handle information about the original tables utilized by the feature learners.

RETURNS DESCRIPTION
Tables

The tables object.

targets property

targets: List[str]

Contains the names of the targets used for this pipeline.

RETURNS DESCRIPTION
List[str]

The names of the targets.

check

check(
    population_table: Union[DataFrame, View, Subset],
    peripheral_tables: Optional[
        Union[
            Dict[str, Union[DataFrame, View]],
            Sequence[Union[DataFrame, View]],
        ]
    ] = None,
) -> Optional[Issues]

Checks the validity of the data model.

PARAMETER DESCRIPTION
population_table

Main table containing the target variable(s) and corresponding to the population Placeholder instance variable.

TYPE: Union[DataFrame, View, Subset]

peripheral_tables

Additional tables corresponding to the peripheral Placeholder instance variable. If passed as a list, the order needs to match the order of the corresponding placeholders passed to peripheral.

If you pass a Subset to population_table, the peripheral tables from that subset will be used. If you use a Container, StarSchema or TimeSeries, that means you are passing a Subset.

TYPE: Optional[Union[Dict[str, Union[DataFrame, View]], Sequence[Union[DataFrame, View]]]] DEFAULT: None

Source code in getml/pipeline/pipeline.py
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
def check(
    self,
    population_table: Union[DataFrame, View, data.Subset],
    peripheral_tables: Optional[
        Union[
            Dict[str, Union[DataFrame, View]],
            Sequence[Union[DataFrame, View]],
        ]
    ] = None,
) -> Optional[Issues]:
    """
    Checks the validity of the data model.

    Args:
        population_table:
            Main table containing the target variable(s) and
            corresponding to the ``population``
            [`Placeholder`][getml.data.Placeholder] instance
            variable.

        peripheral_tables:
            Additional tables corresponding to the ``peripheral``
            [`Placeholder`][getml.data.Placeholder] instance
            variable. If passed as a list, the order needs to
            match the order of the corresponding placeholders passed
            to ``peripheral``.

            If you pass a [`Subset`][getml.data.Subset] to `population_table`,
            the peripheral tables from that subset will be used. If you use
            a [`Container`][getml.data.Container], [`StarSchema`][getml.data.StarSchema]
            or [`TimeSeries`][getml.data.TimeSeries], that means you are passing
            a [`Subset`][getml.data.Subset].

    """

    if isinstance(population_table, data.Subset):
        peripheral_tables = population_table.peripheral
        population_table = population_table.population

    peripheral_tables = _transform_peripheral(peripheral_tables, self.peripheral)

    _check_df_types(population_table, peripheral_tables)

    temp = copy.deepcopy(self)

    temp._send()

    cmd: Dict[str, Any] = {}

    cmd["type_"] = temp.type + ".check"
    cmd["name_"] = temp.id

    cmd["peripheral_dfs_"] = [df._getml_deserialize() for df in peripheral_tables]
    cmd["population_df_"] = population_table._getml_deserialize()

    with comm.send_and_get_socket(cmd) as sock:
        msg = comm.recv_string(sock)
        if msg != "Found!":
            comm.handle_engine_exception(msg)
        print("Checking data model...")
        msg = comm.log(sock)
        if msg != "Success!":
            comm.handle_engine_exception(msg)
        issues = Issues(comm.recv_issues(sock))
        if len(issues) == 0:
            print("OK.")
        else:
            print(
                f"The pipeline check generated {len(issues.info)} "
                + f"issues labeled INFO and {len(issues.warnings)} "
                + "issues labeled WARNING."
            )

    temp.delete()

    return None if len(issues) == 0 else issues

delete

delete() -> None

Deletes the pipeline from the Engine.

Warning

You can not undo this action!

Source code in getml/pipeline/pipeline.py
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
def delete(self) -> None:
    """
    Deletes the pipeline from the Engine.

    Warning:
        You can not undo this action!
    """
    self._check_whether_fitted()

    cmd: Dict[str, Any] = {}
    cmd["type_"] = self.type + ".delete"
    cmd["name_"] = self.id
    cmd["mem_only_"] = False

    comm.send(cmd)

    self._id = NOT_FITTED

deploy

deploy(deploy: bool) -> None

Allows a fitted pipeline to be addressable via an HTTP request. See deployment for details.

PARAMETER DESCRIPTION
deploy

If True, the deployment of the pipeline will be triggered.

TYPE: bool

Source code in getml/pipeline/pipeline.py
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
def deploy(self, deploy: bool) -> None:
    """Allows a fitted pipeline to be addressable via an HTTP request.
    See [deployment][deployment] for details.

    Args:
        deploy: If `True`, the deployment of the pipeline
            will be triggered.
    """
    self._check_whether_fitted()

    if not isinstance(deploy, bool):
        raise TypeError("'deploy' must be of type bool")

    self._validate()

    cmd: Dict[str, Any] = {}
    cmd["type_"] = self.type + ".deploy"
    cmd["name_"] = self.id
    cmd["deploy_"] = deploy

    comm.send(cmd)

    self._save()

fit

fit(
    population_table: Union[DataFrame, View, Subset],
    peripheral_tables: Optional[
        Union[
            Sequence[Union[DataFrame, View]],
            Dict[str, Union[DataFrame, View]],
        ]
    ] = None,
    validation_table: Optional[
        Union[DataFrame, View, Subset]
    ] = None,
    check: bool = True,
) -> Pipeline

Trains the feature learning algorithms, feature selectors and predictors.

PARAMETER DESCRIPTION
population_table

Main table containing the target variable(s) and corresponding to the population Placeholder instance variable.

TYPE: Union[DataFrame, View, Subset]

peripheral_tables

Additional tables corresponding to the peripheral Placeholder instance variable. If passed as a list, the order needs to match the order of the corresponding placeholders passed to peripheral.

If you pass a Subset to population_table, the peripheral tables from that subset will be used. If you use a Container, StarSchema or TimeSeries, that means you are passing a Subset.

TYPE: Optional[Union[Sequence[Union[DataFrame, View]], Dict[str, Union[DataFrame, View]]]] DEFAULT: None

validation_table

Main table containing the target variable(s) and corresponding to the population Placeholder instance variable. If you are passing a subset, that subset must be derived from the same container as population_table.

Only used for early stopping in XGBoostClassifier and XGBoostRegressor.

TYPE: Optional[Union[DataFrame, View, Subset]] DEFAULT: None

check

Whether you want to check the data model before fitting. The checks are equivalent to the checks run by check.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Pipeline

The fitted pipeline.

Source code in getml/pipeline/pipeline.py
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
def fit(
    self,
    population_table: Union[DataFrame, View, data.Subset],
    peripheral_tables: Optional[
        Union[
            Sequence[Union[DataFrame, View]],
            Dict[str, Union[DataFrame, View]],
        ]
    ] = None,
    validation_table: Optional[Union[DataFrame, View, data.Subset]] = None,
    check: bool = True,
) -> Pipeline:
    """Trains the feature learning algorithms, feature selectors
    and predictors.

    Args:
        population_table:
            Main table containing the target variable(s) and
            corresponding to the ``population``
            [`Placeholder`][getml.data.Placeholder] instance
            variable.

        peripheral_tables:
            Additional tables corresponding to the ``peripheral``
            [`Placeholder`][getml.data.Placeholder] instance
            variable. If passed as a list, the order needs to
            match the order of the corresponding placeholders passed
            to ``peripheral``.

            If you pass a [`Subset`][getml.data.Subset] to `population_table`,
            the peripheral tables from that subset will be used. If you use
            a [`Container`][getml.data.Container], [`StarSchema`][getml.data.StarSchema]
            or [`TimeSeries`][getml.data.TimeSeries], that means you are passing
            a [`Subset`][getml.data.Subset].

        validation_table:
            Main table containing the target variable(s) and
            corresponding to the ``population``
            [`Placeholder`][getml.data.Placeholder] instance
            variable. If you are passing a subset, that subset
            must be derived from the same container as *population_table*.

            Only used for early stopping in [`XGBoostClassifier`][getml.predictors.XGBoostClassifier]
            and [`XGBoostRegressor`][getml.predictors.XGBoostRegressor].

        check:
            Whether you want to check the data model before fitting. The checks are
            equivalent to the checks run by [`check`][getml.Pipeline.check].

    Returns:
        The fitted pipeline.
    """

    additional_tags = (
        ["container-" + population_table.container_id]
        if isinstance(population_table, data.Subset)
        else []
    )

    if (
        isinstance(population_table, data.Subset)
        and isinstance(validation_table, data.Subset)
        and validation_table.container_id != population_table.container_id
    ):
        raise ValueError(
            "The subset used for validation must be from the same container "
            + "as the subset used for training."
        )

    if isinstance(population_table, data.Subset):
        peripheral_tables = population_table.peripheral
        population_table = population_table.population

    if isinstance(validation_table, data.Subset):
        validation_table = validation_table.population

    peripheral_tables = _transform_peripheral(peripheral_tables, self.peripheral)

    _check_df_types(population_table, peripheral_tables)

    if check:
        warnings = self.check(population_table, peripheral_tables)
        if warnings:
            print("To see the issues in full, run .check() on the pipeline.")

    self._send(additional_tags)

    cmd: Dict[str, Any] = {}

    cmd["type_"] = self.type + ".fit"
    cmd["name_"] = self.id

    cmd["peripheral_dfs_"] = [df._getml_deserialize() for df in peripheral_tables]
    cmd["population_df_"] = population_table._getml_deserialize()

    if validation_table is not None:
        cmd["validation_df_"] = validation_table._getml_deserialize()

    with comm.send_and_get_socket(cmd) as sock:
        msg = comm.recv_string(sock)

        if msg != "Found!":
            comm.handle_engine_exception(msg)

        begin = time.monotonic()

        msg = comm.log(sock)

        end = time.monotonic()

        if "Trained" in msg:
            print(msg)
            _print_time_taken(begin, end, "Time taken: ")
        else:
            comm.handle_engine_exception(msg)

    self._save()

    return self.refresh()

predict

predict(
    population_table: Union[DataFrame, View, Subset],
    peripheral_tables: Optional[
        Union[
            Sequence[Union[DataFrame, View]],
            Dict[str, Union[DataFrame, View]],
        ]
    ] = None,
    table_name: str = "",
) -> Union[NDArray[float_], None]

Forecasts on new, unseen data using the trained predictor.

Returns the predictions generated by the pipeline based on population_table and peripheral_tables or writes them into a database named table_name.

PARAMETER DESCRIPTION
population_table

Main table containing the target variable(s) and corresponding to the population Placeholder instance variable.

TYPE: Union[DataFrame, View, Subset]

peripheral_tables

Additional tables corresponding to the peripheral Placeholder instance variable. If passed as a list, the order needs to match the order of the corresponding placeholders passed to peripheral.

If you pass a Subset to population_table, the peripheral tables from that subset will be used. If you use a Container, StarSchema or TimeSeries, that means you are passing a Subset.

TYPE: Optional[Union[Sequence[Union[DataFrame, View]], Dict[str, Union[DataFrame, View]]]] DEFAULT: None

table_name

If not an empty string, the resulting predictions will be written into a table in a database. Refer to Unified import interface for further information.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION
Union[NDArray[float_], None]

Resulting predictions provided in an array of the (number of rows in population_table, number of targets in population_table).

Note

Only fitted pipelines (fit) can be used for prediction.

Source code in getml/pipeline/pipeline.py
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
def predict(
    self,
    population_table: Union[DataFrame, View, data.Subset],
    peripheral_tables: Optional[
        Union[
            Sequence[Union[DataFrame, View]],
            Dict[str, Union[DataFrame, View]],
        ]
    ] = None,
    table_name: str = "",
) -> Union[NDArray[np.float_], None]:
    """Forecasts on new, unseen data using the trained ``predictor``.

    Returns the predictions generated by the pipeline based on
    `population_table` and `peripheral_tables` or writes them into
    a database named `table_name`.

    Args:
        population_table:
            Main table containing the target variable(s) and
            corresponding to the ``population``
            [`Placeholder`][getml.data.Placeholder] instance
            variable.

        peripheral_tables:
            Additional tables corresponding to the ``peripheral``
            [`Placeholder`][getml.data.Placeholder] instance
            variable. If passed as a list, the order needs to
            match the order of the corresponding placeholders passed
            to ``peripheral``.

            If you pass a [`Subset`][getml.data.Subset] to `population_table`,
            the peripheral tables from that subset will be used. If you use
            a [`Container`][getml.data.Container], [`StarSchema`][getml.data.StarSchema]
            or [`TimeSeries`][getml.data.TimeSeries], that means you are passing
            a [`Subset`][getml.data.Subset].

        table_name:
            If not an empty string, the resulting predictions will
            be written into a table in a [`database`][getml.database].
            Refer to [Unified import interface][importing-data-unified-interface] for further information.

    Returns:
        Resulting predictions provided in an array of the (number of rows in `population_table`, number of targets in `population_table`).

    Note:
        Only fitted pipelines
        ([`fit`][getml.Pipeline.fit]) can be used for
        prediction.


    """

    self._check_whether_fitted()

    if isinstance(population_table, data.Subset):
        peripheral_tables = population_table.peripheral
        population_table = population_table.population

    peripheral_tables = _transform_peripheral(peripheral_tables, self.peripheral)

    _check_df_types(population_table, peripheral_tables)

    if not isinstance(table_name, str):
        raise TypeError("'table_name' must be of type str")

    self._validate()

    cmd: Dict[str, Any] = {}
    cmd["type_"] = self.type + ".transform"
    cmd["name_"] = self.id
    cmd["http_request_"] = False

    with comm.send_and_get_socket(cmd) as sock:
        msg = comm.recv_string(sock)
        if msg != "Found!":
            comm.handle_engine_exception(msg)
        y_hat = self._transform(
            peripheral_tables,
            population_table,
            sock,
            predict=True,
            table_name=table_name,
        )

    return y_hat

refresh

refresh() -> Pipeline

Reloads the pipeline from the Engine.

This discards all local changes you have made since the last time you called fit.

RETURNS DESCRIPTION
Pipeline

Current instance

Source code in getml/pipeline/pipeline.py
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
def refresh(self) -> Pipeline:
    """Reloads the pipeline from the Engine.

    This discards all local changes you have made since the
    last time you called [`fit`][getml.Pipeline.fit].

    Returns:
            Current instance
    """

    cmd: Dict[str, Any] = {}
    cmd["type_"] = self.type + ".refresh"
    cmd["name_"] = self.id

    with comm.send_and_get_socket(cmd) as sock:
        msg = comm.recv_string(sock)

    if msg[0] != "{":
        comm.handle_engine_exception(msg)

    json_obj = json.loads(msg)

    self._parse_json_obj(json_obj)

    return self

score

score(
    population_table: Union[DataFrame, View, Subset],
    peripheral_tables: Optional[
        Union[
            Sequence[Union[DataFrame, View]],
            Dict[str, Union[DataFrame, View]],
        ]
    ] = None,
) -> Scores

Calculates the performance of the predictor.

Returns different scores calculated on population_table and peripheral_tables.

PARAMETER DESCRIPTION
population_table

Main table containing the target variable(s) and corresponding to the population Placeholder instance variable.

TYPE: Union[DataFrame, View, Subset]

peripheral_tables

Additional tables corresponding to the peripheral Placeholder instance variable. If passed as a list, the order needs to match the order of the corresponding placeholders passed to peripheral.

If you pass a Subset to population_table, the peripheral tables from that subset will be used. If you use a Container, StarSchema or TimeSeries, that means you are passing a Subset.

TYPE: Optional[Union[Sequence[Union[DataFrame, View]], Dict[str, Union[DataFrame, View]]]] DEFAULT: None

RETURNS DESCRIPTION
Scores

The scores of the pipeline.

Note

Only fitted pipelines (fit) can be scored.

Source code in getml/pipeline/pipeline.py
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
def score(
    self,
    population_table: Union[DataFrame, View, data.Subset],
    peripheral_tables: Optional[
        Union[
            Sequence[Union[DataFrame, View]],
            Dict[str, Union[DataFrame, View]],
        ]
    ] = None,
) -> Scores:
    """Calculates the performance of the ``predictor``.

    Returns different scores calculated on `population_table` and
    `peripheral_tables`.

    Args:
        population_table:
            Main table containing the target variable(s) and
            corresponding to the ``population``
            [`Placeholder`][getml.data.Placeholder] instance
            variable.

        peripheral_tables:
            Additional tables corresponding to the ``peripheral``
            [`Placeholder`][getml.data.Placeholder] instance
            variable. If passed as a list, the order needs to
            match the order of the corresponding placeholders passed
            to ``peripheral``.

            If you pass a [`Subset`][getml.data.Subset] to `population_table`,
            the peripheral tables from that subset will be used. If you use
            a [`Container`][getml.data.Container], [`StarSchema`][getml.data.StarSchema]
            or [`TimeSeries`][getml.data.TimeSeries], that means you are passing
            a [`Subset`][getml.data.Subset].

    Returns:
        The scores of the pipeline.

    Note:
        Only fitted pipelines
        ([`fit`][getml.Pipeline.fit]) can be
        scored.

    """

    self._check_whether_fitted()

    if isinstance(population_table, data.Subset):
        peripheral_tables = population_table.peripheral
        population_table = population_table.population

    peripheral_tables = _transform_peripheral(peripheral_tables, self.peripheral)

    _check_df_types(population_table, peripheral_tables)

    cmd: Dict[str, Any] = {}
    cmd["type_"] = self.type + ".transform"
    cmd["name_"] = self.id
    cmd["http_request_"] = False

    with comm.send_and_get_socket(cmd) as sock:
        msg = comm.recv_string(sock)

        if msg != "Found!":
            comm.handle_engine_exception(msg)

        self._transform(
            peripheral_tables, population_table, sock, predict=True, score=True
        )

        msg = comm.recv_string(sock)

        if msg != "Success!":
            comm.handle_engine_exception(msg)

        scores = comm.recv_string(sock)

        scores = json.loads(scores)

    self.refresh()

    self._save()

    return self.scores

transform

transform(
    population_table: Union[DataFrame, View, Subset],
    peripheral_tables: Optional[
        Union[
            Sequence[Union[DataFrame, View]],
            Dict[str, Union[DataFrame, View]],
        ]
    ] = None,
    df_name: str = "",
    table_name: str = "",
) -> Union[DataFrame, NDArray[float_], None]

Translates new data into the trained features.

Transforms the data passed in population_table and peripheral_tables into features, which can be inserted into machine learning models.

PARAMETER DESCRIPTION
population_table

Main table containing the target variable(s) and corresponding to the population Placeholder instance variable.

TYPE: Union[DataFrame, View, Subset]

peripheral_tables

Additional tables corresponding to the peripheral Placeholder instance variable. If passed as a list, the order needs to match the order of the corresponding placeholders passed to peripheral.

If you pass a Subset to population_table, the peripheral tables from that subset will be used. If you use a Container, StarSchema or TimeSeries, that means you are passing a Subset.

TYPE: Optional[Union[Sequence[Union[DataFrame, View]], Dict[str, Union[DataFrame, View]]]] DEFAULT: None

df_name

If not an empty string, the resulting features will be written into a newly created DataFrame.

TYPE: str DEFAULT: ''

table_name

If not an empty string, the resulting features will be written into a table in a database. Refer to Unified import interface for further information.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION
Union[DataFrame, NDArray[float_], None]

The features generated by the pipeline.

Example

By default, transform returns a ndarray:

my_features_array = pipe.transform()
You can also export your features as a DataFrame by providing the df_name argument:
my_features_df = pipe.transform(df_name="my_features")
Or you can write the results directly into a database:
getml.database.connect_odbc(...)
pipe.transform(table_name="MY_FEATURES")

Note

Only fitted pipelines (fit) can transform data into features.

Source code in getml/pipeline/pipeline.py
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
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
def transform(
    self,
    population_table: Union[DataFrame, View, data.Subset],
    peripheral_tables: Optional[
        Union[
            Sequence[Union[DataFrame, View]],
            Dict[str, Union[DataFrame, View]],
        ]
    ] = None,
    df_name: str = "",
    table_name: str = "",
) -> Union[DataFrame, NDArray[np.float_], None]:
    """Translates new data into the trained features.

    Transforms the data passed in `population_table` and
    `peripheral_tables` into features, which can be inserted into
    machine learning models.


    Args:
        population_table:
            Main table containing the target variable(s) and
            corresponding to the ``population``
            [`Placeholder`][getml.data.Placeholder] instance
            variable.

        peripheral_tables:
            Additional tables corresponding to the ``peripheral``
            [`Placeholder`][getml.data.Placeholder] instance
            variable. If passed as a list, the order needs to
            match the order of the corresponding placeholders passed
            to ``peripheral``.

            If you pass a [`Subset`][getml.data.Subset] to `population_table`,
            the peripheral tables from that subset will be used. If you use
            a [`Container`][getml.data.Container], [`StarSchema`][getml.data.StarSchema]
            or [`TimeSeries`][getml.data.TimeSeries], that means you are passing
            a [`Subset`][getml.data.Subset].

        df_name:
            If not an empty string, the resulting features will be
            written into a newly created DataFrame.

        table_name:
            If not an empty string, the resulting features will
            be written into a table in a [`database`][getml.database].
            Refer to [Unified import interface][importing-data-unified-interface] for further information.

    Returns:
        The features generated by the pipeline.

    ??? example
        By default, `transform` returns a [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html):
        ```python
        my_features_array = pipe.transform()
        ```
        You can also export your features as a [`DataFrame`][getml.DataFrame]
        by providing the `df_name` argument:
        ```python
        my_features_df = pipe.transform(df_name="my_features")
        ```
        Or you can write the results directly into a database:
        ```python
        getml.database.connect_odbc(...)
        pipe.transform(table_name="MY_FEATURES")
        ```

    Note:
        Only fitted pipelines
        ([`fit`][getml.Pipeline.fit]) can transform
        data into features.

    """

    self._check_whether_fitted()

    if isinstance(population_table, data.Subset):
        peripheral_tables = population_table.peripheral
        population_table = population_table.population

    peripheral_tables = _transform_peripheral(peripheral_tables, self.peripheral)

    _check_df_types(population_table, peripheral_tables)

    self._validate()

    cmd: Dict[str, Any] = {}
    cmd["type_"] = self.type + ".transform"
    cmd["name_"] = self.id
    cmd["http_request_"] = False

    with comm.send_and_get_socket(cmd) as sock:
        msg = comm.recv_string(sock)
        if msg != "Found!":
            comm.handle_engine_exception(msg)
        y_hat = self._transform(
            peripheral_tables,
            population_table,
            sock,
            df_name=df_name,
            table_name=table_name,
        )

    if df_name != "":
        return data.DataFrame(name=df_name).refresh()

    return y_hat