Loading...

vastorbit.machine_learning.vast.tsa.ARIMA

class vastorbit.machine_learning.vast.tsa.ARIMA(name: str = None, overwrite_model: bool = False, **kwargs)

Creates a inDB ARIMA model.

Parameters:
  • name (str, optional) – Name of the model. The model is stored in the database.

  • overwrite_model (bool, optional) – If set to True, training a model with the same name as an existing model overwrites the existing model.

  • order (tuple, optional) – The (p,d,q) order of the model for the autoregressive, differences, and moving average components.

  • tol (float, optional) – Determines whether the algorithm has reached the specified accuracy result.

  • max_iter (int, optional) – Determines the maximum number of iterations the algorithm performs before achieving the specified accuracy result.

  • init (str, optional) –

    Initialization method, one of the following:

    • ’zero’:

      Coefficients are initialized to zero.

    • ’hr’:

      Coefficients are initialized using the Hannan-Rissanen algorithm.

  • missing (str, optional) –

    Method for handling missing values, one of the following strings:

    • ’drop’:

      Missing values are ignored.

    • ’error’:

      Missing values raise an error.

    • ’zero’:

      Missing values are set to zero.

    • ’linear_interpolation’:

      Missing values are replaced by a linearly interpolated value based on the nearest valid entries before and after the missing value. In cases where the first or last values in a dataset are missing, the function errors.

Variables:
  • created (Many attributes are)

  • phase. (during the fitting)

  • phi_ (numpy.array) – The coefficient of the AutoRegressive process. It represents the strength and direction of the relationship between a variable and its past values.

  • theta_ (numpy.array) – The theta coefficient of the Moving Average process. It signifies the impact and contribution of the lagged error terms in determining the current value within the time series model.

  • mean_ (float) – The mean of the time series values.

  • feature_importances_ (numpy.array) – The importance of features is computed through the AutoRegressive part coefficients, which are normalized based on their range. Subsequently, an activation function calculates the final score. It is necessary to use the features_importance() method to compute it initially, and the computed values will be subsequently utilized for subsequent calls.

  • mse_ (float) – The mean squared error (MSE) of the model, based on one-step forward forecasting, may not always be relevant. Utilizing a full forecasting approach is recommended to compute a more meaningful and comprehensive metric.

  • n_ (int) – The number of rows used to fit the model.

  • note:: (..) – All attributes can be accessed using the get_attributes() method.

Examples

The following examples provide a basic understanding of usage. For more detailed examples, please refer to the Machine Learning or the Examples section on the website.

Initialization

We import vastorbit:

import vastorbit as vo

Hint

By assigning an alias to vastorbit, we mitigate the risk of code collisions with other libraries. This precaution is necessary because vastorbit uses commonly known function names like “average” and “median”, which can potentially lead to naming conflicts. The use of an alias ensures that the functions from vastorbit are used as intended without interfering with functions from other libraries.

For this example, we will use the airline passengers dataset.

import vastorbit.datasets as vod

data = vod.load_airline_passengers()
📅
date
Date
123
passengers
Integer
11949-01-01112
21949-02-01118
31949-03-01132
41949-04-01129
51949-05-01121
61949-06-01135
71949-07-01148
81949-08-01148
91949-09-01136
101949-10-01119
111949-11-01104
121949-12-01118
131950-01-01115
141950-02-01126
151950-03-01141
161950-04-01135
171950-05-01125
181950-06-01149
191950-07-01170
201950-08-01170
211950-09-01158
221950-10-01133
231950-11-01114
241950-12-01140
251951-01-01145
261951-02-01150
271951-03-01178
281951-04-01163
291951-05-01172
301951-06-01178
311951-07-01199
321951-08-01199
331951-09-01184
341951-10-01162
351951-11-01146
361951-12-01166
371952-01-01171
381952-02-01180
391952-03-01193
401952-04-01181
411952-05-01183
421952-06-01218
431952-07-01230
441952-08-01242
451952-09-01209
461952-10-01191
471952-11-01172
481952-12-01194
491953-01-01196
501953-02-01196
511953-03-01236
521953-04-01235
531953-05-01229
541953-06-01243
551953-07-01264
561953-08-01272
571953-09-01237
581953-10-01211
591953-11-01180
601953-12-01201
611954-01-01204
621954-02-01188
631954-03-01235
641954-04-01227
651954-05-01234
661954-06-01264
671954-07-01302
681954-08-01293
691954-09-01259
701954-10-01229
711954-11-01203
721954-12-01229
731955-01-01242
741955-02-01233
751955-03-01267
761955-04-01269
771955-05-01270
781955-06-01315
791955-07-01364
801955-08-01347
811955-09-01312
821955-10-01274
831955-11-01237
841955-12-01278
851956-01-01284
861956-02-01277
871956-03-01317
881956-04-01313
891956-05-01318
901956-06-01374
911956-07-01413
921956-08-01405
931956-09-01355
941956-10-01306
951956-11-01271
961956-12-01306
971957-01-01315
981957-02-01301
991957-03-01356
1001957-04-01348
Rows: 1-100 | Columns: 2

Note

vastorbit offers a wide range of sample datasets that are ideal for training and testing purposes. You can explore the full list of available datasets in the Datasets, which provides detailed information on each dataset and how to use them effectively. These datasets are invaluable resources for honing your data analysis and machine learning skills within the vastorbit environment.

We can plot the data to visually inspect it for the presence of any trends:

data["passengers"].plot(ts = "date")

Though the increasing trend is obvious in our example, we can confirm it by the mkt() (Mann Kendall test) test:

from vastorbit.machine_learning.model_selection.statistical_tests import mkt

mkt(data, column = "passengers", ts = "date")
value
Mann Kendall Test Statistic14.381116595949713
S8327.0
STDS578.9536538730886
p_value6.798871500366548e-47
Monotonic Trend
Trendincreasing
Rows: 1-6 | Columns: 2

The above tests gives us some more insights into the data such as that the data is monotonic, and is increasing. Furthermore, the low p-value confirms the presence of a trend with respect to time. Now we are sure of the trend so we can apply the appropriate time-series model to fit it.

Model Initialization

First we import the ARIMA model:

from vastorbit.machine_learning.vast.tsa import ARIMA

Then we can create the model:

model = ARIMA(order = (12, 0, 0))

Important

The model name is crucial for the model management system and versioning. It’s highly recommended to provide a name if you plan to reuse the model later.

Model Fitting

We can now fit the model:

model.fit(data, "date", "passengers")

Important

To train a model, you can directly use the VastFrame or the name of the relation stored in the database. The test set is optional and is only used to compute the test metrics. In vastorbit, we don’t work using X matrices and y vectors. Instead, we work directly with lists of predictors and the response name.

Features Importance

We can conveniently get the features importance:

model.features_importance()

Important

Feature importance is determined by using the coefficients of the auto-regressive (AR) process and normalizing them. This method tends to be precise when your time series primarily consists of an auto-regressive component. However, its accuracy may be a topic of discussion if the time series contains other components as well._____

One important thing in time-series forecasting is that it has two types of forecasting:

  • One-step ahead forecasting

  • Full forecasting

Important

The default method is one-step ahead forecasting. To use full forecasting, use method = "forecast".

One-step ahead

In this type of forecasting, the algorithm utilizes the true value of the previous timestamp (t-1) to predict the immediate next timestamp (t). Subsequently, to forecast additional steps into the future (t+1), it relies on the actual value of the immediately preceding timestamp (t).

A notable drawback of this forecasting method is its tendency to exhibit exaggerated accuracy, particularly when predicting more than one step into the future.

Metrics

We can get the entire report using:

model.report()
value
explained_variance0.7968735700002738
max_error28.235556067114082
median_absolute_error7.782895
mean_absolute_error9.246920621817747
mean_squared_error168.3521776055204
root_mean_squared_error12.975059830517948
r20.7092363081079095
r2_adj0.6728908466213982
aic58.11772366227439
bic55.86575099111963
Rows: 1-10 | Columns: 2

You can also choose the number of predictions and where to start the forecast. For example, the following code will allow you to generate a report with 30 predictions, starting the forecasting process at index 40.

model.report(start = 40, npredictions = 30)
value
explained_variance0.7329944262123258
max_error42.40391018451546
median_absolute_error13.395048
mean_absolute_error14.247677486941015
mean_squared_error312.2669458874625
root_mean_squared_error17.671076534480363
r20.7020808408187085
r2_adj0.691440870847948
aic177.05649327441657
bic179.11814729700015
Rows: 1-10 | Columns: 2

Note

No matter what value you give for npredictons, in the report, the comparison will only be until the extent of the availability of true value. For exaxmple, even if we give n_predictions = 300, the report result will be the same as n_predictions = 104 starting from 40. This is because there are only 104 values beyond 40 in the dataset.

Important

Most metrics are computed using a single SQL query, but some of them might require multiple SQL queries. Selecting only the necessary metrics in the report can help optimize performance. E.g. model.report(metrics = ["mse", "r2"]).

You can utilize the score() function to calculate various regression metrics, with the explained variance being the default.

model.score()

The same applies to the score. You can choose where to start and the number of predictions to use.

model.score(start = 40, npredictions = 30)

Important

If you do not specify a starting point and the number of predictions, the forecast will begin at one-fourth of the dataset, which can result in an inaccurate score, especially for large datasets. It’s important to choose these parameters carefully.

Prediction

Prediction is straight-forward:

model.predict()
123
prediction
Decimal(38, 18)
1122.34789051920173
2119.97270878863017
3130.40511857650353
4135.03356898479817
5137.523254048988
6129.04989433328802
7161.0599479833417
8168.63663958343994
9158.84924127220378
10136.35686983685878
Rows: 1-10 | Column: prediction | Type: decimal(38, 18)

Hint

You can control the number of prediction steps by changing the npredictions parameter: model.predict(npredictions = 30).

Note

Predictions can be made automatically by using the training set, in which case you don’t need to specify the predictors. Alternatively, you can pass only the VastFrame to the predict() function, but in this case, it’s essential that the column names of the VastFrame match the predictors and response name in the model.

If you would like to have the ‘time-stamps’ (ts) in the output then you can switch the output_estimated_ts the parameter. And if you also would like to see the standard error then you can switch the output_standard_errors parameter:

model.predict(output_estimated_ts = True, output_standard_errors = True)
123
prediction
Decimal(38, 18)
1122.34789051920173
2119.97270878863017
3130.40511857650353
4135.03356898479817
5137.523254048988
6129.04989433328802
7161.0599479833417
8168.63663958343994
9158.84924127220378
10136.35686983685878
Rows: 1-10 | Column: prediction | Type: decimal(38, 18)

Important

The output_estimated_ts parameter provides an estimation of ‘ts’ assuming that ‘ts’ is regularly spaced.

If you don’t provide any input, the function will begin forecasting after the last known value. If you want to forecast starting from a specific value within the input dataset or another dataset, you can use the following syntax.

model.predict(
    data,
    "date",
    "passengers",
    start = 40,
    npredictions = 20,
    output_estimated_ts = True,
    output_standard_errors = True,
)
123
prediction
Decimal(38, 18)
1179.3054162957827
2189.7644439328859
3227.41829985639995
4223.7650566670624
5223.45126830994622
6180.1391715915681
7185.3950484887631
8166.43552143932914
9200.44379321117344
10191.3952577629153
11193.59608981548453
12220.6932515210783
13238.82145713737486
14225.9409935157178
15253.68959883060876
16259.2084026630325
17251.96504984439684
18208.4777226990456
19200.68770927526185
20179.57978119031512
Rows: 1-20 | Column: prediction | Type: decimal(38, 18)

Plots

We can conveniently plot the predictions on a line plot to observe the efficacy of our model:

model.plot(data, "date", "passengers", npredictions = 20, start = 140)

Note

You can control the number of prediction steps by changing the npredictions parameter: model.plot(npredictions = 30).

Please refer to Machine Learning - Time Series Plots for more examples.

Full forecasting

In this forecasting approach, the algorithm relies solely on a chosen true value for initiation. Subsequently, all predictions are established based on a series of previously predicted values.

This methodology aligns the accuracy of predictions more closely with reality. In practical forecasting scenarios, the goal is to predict all future steps, and this technique ensures a progressive sequence of predictions.

Metrics

We can get the report using:

model.report(start = 40, method = "forecast")

By selecting start = 40, we will measure the accuracy from 40th time-stamp and continue the assessment until the last available time-stamp.

value
explained_variance0.6731441121563337
max_error42.45215308811038
median_absolute_error23.365067
mean_absolute_error21.45994039189248
mean_squared_error597.6418180151178
root_mean_squared_error24.44671384900469
r2-0.42468668625025074
r2_adj-0.6027725220315321
aic70.78705893682901
bic68.53508626567424
Rows: 1-10 | Columns: 2

Notice that the accuracy using method = forecast is poorer than the one-step ahead forecasting.

You can utilize the score() function to calculate various regression metrics, with the explained variance being the default.

model.score(start = 40, npredictions = 30, method = "forecast")

Prediction

Prediction is straight-forward:

model.predict(start = 50, npredictions = 40, method = "forecast")
123
prediction
Decimal(17, 14)
1193.5960898154845
2179.0679443090135
3194.81945740698478
4205.56402022135435
5227.52161820942064
6226.89943595636495
7216.7023634979596
8201.35766095439442
9196.32241558307217
10201.2486966063865
11199.63782093326114
12200.9144583687937
13189.28441631125628
14188.27398671872254
15191.8786747715333
16204.69931779689432
17217.40774073106303
18219.80899945781456
19216.7577632381002
20209.08231043629414
21208.72140886687794
22207.56842350436645
23208.30530063303055
24203.01759964248367
25196.2372761050883
26193.00926508422626
27194.5971885428085
28203.495205547232
29210.48218612558918
30215.10173795730086
31214.18963417280375
32213.39672348851468
33213.35960978372268
34213.98673612984902
35213.26798710918212
36208.4984202351696
37203.34571079133818
38198.93190471855524
39199.68422182790826
40203.39111510032632
Rows: 1-40 | Column: prediction | Type: decimal(17, 14)

If you want to forecast starting from a specific value within the input dataset or another dataset, you can use the following syntax.

model.predict(
    data,
    "date",
    "passengers",
    start = 40,
    npredictions = 20,
    output_estimated_ts = True,
    output_standard_errors = True,
    method = "forecast"
)
123
prediction
Decimal(17, 14)
1179.3054162957827
2186.13769863888962
3197.09100625447027
4199.54784691188962
5189.6291499815959
6172.80740811618108
7167.63812810498695
8169.59450368779417
9172.63493396747546
10182.01450412200944
11181.85087247527034
12180.4339054984652
13181.67752933033785
14188.14389492897527
15196.85828658374413
16198.92244286889195
17193.0121194340164
18184.25404329132496
19179.52248803697313
20177.1789259890237
Rows: 1-20 | Column: prediction | Type: decimal(17, 14)

Plots

We can conveniently plot the predictions on a line plot to observe the efficacy of our model:

model.plot(data, "date", "passengers", npredictions = 40, start = 120, method = "forecast")
__init__(name: str = None, overwrite_model: bool = False, **kwargs) None

Methods

__init__([name, overwrite_model])

contour([nbins, chart])

Draws the model's contour plot.

deploySQL([ts, y, start, npredictions, ...])

Returns the SQL code needed to deploy the model.

drop()

Drops the model from the VAST DataBase.

export_models(name, path[, kind])

Exports machine learning models.

features_importance([idx, show, chart])

Computes the model's features importance.

fit(input_relation, ts, y[, test_relation, ...])

Trains the model using pure SQL.

get_attributes([attr_name])

Returns the model attributes.

get_match_index(x, col_list[, str_check])

Returns the matching index.

get_params()

Returns the parameters of the model.

get_plotting_lib([class_name, chart, ...])

Returns the first available library (Plotly, Matplotlib) to draw a specific graphic.

import_models(path[, schema, kind])

Imports machine learning models.

plot([vdf, ts, y, start, npredictions, ...])

Draws the model.

predict([vdf, ts, y, start, npredictions, ...])

Predicts using the input relation.

regression_report([metrics, start, ...])

Computes a regression report using multiple metrics to evaluate the model (r2, mse, max error...).

report([metrics, start, npredictions, method])

Computes a regression report using multiple metrics to evaluate the model (r2, mse, max error...).

score([metric, start, npredictions, method])

Computes the model score.

set_params([parameters])

Sets the parameters of the model.

summarize()

Summarizes the model.

to_binary(path)

Exports the model to the VAST Binary format.

to_python([return_proba, ...])

Returns the Python function needed for in-memory scoring without using built-in VAST functions.

to_sql([X, return_proba, ...])

Returns the SQL code needed to deploy the model without using built-in VAST functions.

Attributes