Loading...

vastorbit.machine_learning.vast.tsa.VAR

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

Creates a inDB VectorAutoregressor 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.

  • p (int, optional) – Integer in the range [1, 1999], the number of lags to consider in the computation. Larger values for p weaken the correlation.

  • method (str, optional) –

    One of the following algorithms for training the model:

    • ols:

      Ordinary Least Squares

    • yule-walker:

      Yule-Walker

  • penalty (str, optional) –

    Method of regularization.

    • none:

      No regularization.

    • l2:

      L2 regularization.

  • C (PythonNumber, optional) – The regularization parameter value. The value must be zero or non-negative.

  • 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.

  • subtract_mean (bool, optional) – For Yule Walker, if subtract_mean is True, then the mean of the column(s) will be subtracted before calculating the coefficients. If False (default), then the calculations will be performed directly on the data, this often gives a more accurate model. Note that the means saved in the model will be saved as all 0s if this parameter is set to False. This parameter has no effect for OLS.

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.

    Note

    In the case of multivariate analysis, each coefficient is represented by a matrix of numbers.

  • intercept_ (float) –

    Represents the expected value of the time series when the lagged values are zero. It signifies the baseline or constant term in the model, capturing the average level of the series in the absence of any historical influence.

    Note

    In the case of multivariate analysis, the intercept is represented by a vector of numbers.

  • 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 generate a dummy time-series dataset.

data = vo.VastFrame(
    {
        "month": [i for i in range(1, 19)],
        "GB1": [5, 10, 20, 35, 55, 80, 110, 145, 185, 230,
                280, 335, 395, 460, 530, 605, 685, 770],
        "GB2": [3, 7, 12, 18, 22, 30, 37, 39, 51, 80,
                95, 112, 130, 150, 172, 196, 222, 250],
    }
)
123
month
Integer
123
GB1
Integer
123
GB2
Integer
1918551
21023080
343518
416605196
518770250
617685222
7814539
8711037
915530172
1055522
1168030
122107
13153
1413395130
1514460150
1612335112
1732012
181128095
Rows: 1-18 | Columns: 3

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.plot(ts = "month", columns = ["GB1", "GB2"])

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 = "GB1", ts = "month")
value
Mann Kendall Test Statistic5.757410544997134
S153.0
STDS26.40075756488817
p_value8.541400530670446e-09
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 VAR model:

from vastorbit.machine_learning.vast.tsa import VAR

Then we can create the model:

model = VAR(p = 2)

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, "month", ["GB1", "GB2"])

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 of the first predictor:

model.features_importance(idx=0)

Note

We use idx=0 to choose the first predictor. In our case, it is GB1. We can set idx=1 to switch to GB2 …_____

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(start = 4)
"GB1""GB2"
explained_variance0.99455139847439160.9957015830361389
max_error85.0000000000003427.142420631860077
median_absolute_error65.0000000000002323.321726
mean_absolute_error65.000000000000322.622584896874805
mean_squared_error4391.666666666706524.7682978697871
root_mean_squared_error66.2696511735704422.907821761786675
r20.85642934980021670.8263123462478639
r2_adj0.83591925691453330.8014998242832729
aic82.820510096006563.69994478337792
bic79.8816259173456260.761060604717024
Rows: 1-10 | Columns: 3

Important

The value for start cannot be less than the p value selected for the VAR model.

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 = 4, npredictions = 10)
"GB1""GB2"
explained_variance0.99455139847439160.9957015830361389
max_error85.0000000000003427.142420631860077
median_absolute_error65.0000000000002323.321726
mean_absolute_error65.000000000000322.622584896874805
mean_squared_error4391.666666666706524.7682978697871
root_mean_squared_error66.2696511735704422.907821761786675
r20.85642934980021670.8263123462478639
r2_adj0.83591925691453330.8014998242832729
aic82.820510096006563.69994478337792
bic79.8816259173456260.761060604717024
Rows: 1-10 | Columns: 3

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(start = 3, npredictions = 10)

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
prediction0
Double
123
prediction1
Decimal(32, 17)
1769.9999999999997251.07319803735524
2684.9999999999997222.85757936813994
3604.9999999999995196.38655242579148
4529.9999999999997171.66011721030992
5459.9999999999997148.6782737216952
6394.9999999999998127.91902253397623
7334.99999999999966108.35472942635487
8279.999999999999898.18303723006153
9229.999999999999873.79178980189468
10184.9999999999997755.565634209902925
Rows: 1-10 | Columns: 2

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.

model.predict(output_estimated_ts = True)
123
prediction0
Double
123
prediction1
Decimal(32, 17)
1769.9999999999997251.07319803735524
2684.9999999999997222.85757936813994
3604.9999999999995196.38655242579148
4529.9999999999997171.66011721030992
5459.9999999999997148.6782737216952
6394.9999999999998127.91902253397623
7334.99999999999966108.35472942635487
8279.999999999999898.18303723006153
9229.999999999999873.79178980189468
10184.9999999999997755.565634209902925
Rows: 1-10 | Columns: 2

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,
    "month",
    ["GB1", "GB2"],
    start = 4,
    npredictions = 3,
    output_estimated_ts = True,
)
123
prediction0
Double
123
prediction1
Decimal(32, 17)
1769.9999999999997251.07319803735524
2684.9999999999997222.85757936813994
3604.9999999999995196.38655242579148
Rows: 1-3 | Columns: 2

Plots

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

model.plot(data, "month", ["GB1", "GB2"], npredictions = 3, start=4)

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.

Note

We use idx=0 to choose the first predictor. In our case, it is GB1. We can set idx=1 to switch to GB2

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 = 4, method = "forecast")

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

"GB1""GB2"
explained_variance0.99455139847439160.9957015830361389
max_error85.0000000000003427.142420631860077
median_absolute_error65.0000000000002323.321726
mean_absolute_error65.000000000000322.622584896874805
mean_squared_error4391.666666666706524.7682978697871
root_mean_squared_error66.2696511735704422.907821761786675
r20.85642934980021670.8263123462478639
r2_adj0.83591925691453330.8014998242832729
aic82.820510096006563.69994478337792
bic79.8816259173456260.761060604717024
Rows: 1-10 | Columns: 3

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 = 4, npredictions = 6, method = "forecast")

Prediction

Prediction is straight-forward:

model.predict(start = 10, npredictions = 3, method = "forecast")
123
prediction0
Double
123
prediction1
Decimal(32, 17)
1769.9999999999997251.07319803735524
2684.9999999999997222.85757936813994
3604.9999999999995196.38655242579148
Rows: 1-3 | Columns: 2

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,
    "month",
    ["GB1", "GB2"],
    start = 4,
    npredictions = 4,
    output_estimated_ts = True,
    output_standard_errors = True,
    method = "forecast",
)
123
prediction0
Double
123
prediction1
Decimal(32, 17)
1769.9999999999997251.07319803735524
2684.9999999999997222.85757936813994
3604.9999999999995196.38655242579148
4529.9999999999997171.66011721030992
Rows: 1-4 | Columns: 2

Plots

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

model.plot(
    data,
    "month",
    ["GB1", "GB2",
    npredictions = 4,
    start = 5,
    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