Loading...

verticapy.machine_learning.vertica.tsa.VAR

class verticapy.machine_learning.vertica.tsa.VAR(name: str = None, overwrite_model: bool = False, p: int = 3, method: Literal['yule-walker'] = 'yule-walker', penalty: Literal[None, 'none', 'l2'] = 'none', C: Annotated[int | float | Decimal, 'Python Numbers'] = 1.0, missing: Literal['drop', 'error', 'zero'] = 'error', subtract_mean: bool = False)

Creates a inDB VectorAutoregressor model.

Added in version 24.2.0.

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.

Attributes

Many attributes are created during the fitting phase.

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.

features_importance_: 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.

Note

Several other attributes can be accessed by using the get_vertica_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 verticapy:

import verticapy as vp

Hint

By assigning an alias to verticapy, we mitigate the risk of code collisions with other libraries. This precaution is necessary because verticapy 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 verticapy are used as intended without interfering with functions from other libraries.

For this example, we will generate a dummy time-series dataset.

data = vp.vDataFrame(
    {
        "month": [i for i in range(1, 11)],
        "GB1": [5, 10, 20, 35, 55, 80, 110, 145, 185, 230],
        "GB2": [3, 7, 12, 18, 22, 30, 37, 39, 51, 80],
    }
)

123
month
Integer
123
GB1
Integer
123
GB2
Integer
1153
22107
332012
443518
555522
668030
7711037
8814539
9918551
101023080
Rows: 1-10 | Columns: 3

Note

VerticaPy 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 VerticaPy 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 verticapy.machine_learning.model_selection.statistical_tests import mkt

mkt(data, column = "GB1", ts = "month")
value
Mann Kendall Test Statistic3.935479640399647
S45.0
STDS11.1803398874989
p_value8.303070332644367e-05
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 verticapy.machine_learning.vertica.tsa import VAR

Then we can create the model:

model = VAR(p = 2)

Hint

In verticapy 1.0.x and higher, you do not need to specify the model name, as the name is automatically assigned. If you need to re-use the model, you can fetch the model name from the model’s attributes.

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"])


=========
phi_(t-1)
=========
predictor|  gb1   |  gb2   
---------+--------+--------
   gb1   | 2.15113|-3.77023
   gb2   | 0.18040| 0.12940


=========
phi_(t-2)
=========
predictor|  gb1   |  gb2   
---------+--------+--------
   gb1   |-2.13660| 6.37890
   gb2   |-0.27343| 1.00159


====
mean
====
predictor| value  
---------+--------
   gb1   | 0.00000
   gb2   | 0.00000


==================
mean_squared_error
==================
predictor|  value   
---------+----------
   gb1   |1234.12309
   gb2   |280.45886 


=================
predictor_columns
=================
"gb1", "gb2"

================
timestamp_column
================
month

==============
missing_method
==============
error

===========
call_string
===========
autoregressor('"public"."_verticapy_tmp_ar_v_mldb_8d772ada55a511ef880f0242ac120002_"', '"public"."_verticapy_tmp_view_v_mldb_8d8f018c55a511ef880f0242ac120002_"', '"gb1", "gb2"', 'month'
USING PARAMETERS p=2, method=yule-walker, missing=error, regularization='none', lambda=1, compute_mse=true, subtract_mean=false);

===============
Additional Info
===============
       Name       | Value  
------------------+--------
    lag_order     |   2    
  num_predictors  |   2    
      lambda      | 1.00000
rejected_row_count|   0    
accepted_row_count|   10   

Important

To train a model, you can directly use the vDataFrame 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 verticapy, 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)
Out[6]: 

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

Model Register

In order to register the model for tracking and versioning:

model.register("model_v1")

Please refer to Model Tracking and Versioning for more details on model tracking and versioning.


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.8107744706374480.592553615026319
max_error85.352218968100540.6116207481806
median_absolute_error23.283245655960210.2310437595838
mean_absolute_error29.744258579010114.4813850462212
mean_squared_error1568.16673661962351.965890988425
root_mean_squared_error39.600085058237218.760754009059
r20.565821937948038-0.00809707021905459
r2_adj0.457277422435048-0.260121337773818
aic54.812641860987645.8478722884779
bic47.72949413277738.7647245602673
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.8107744706374480.592553615026319
max_error85.352218968100540.6116207481806
median_absolute_error23.283245655960210.2310437595838
mean_absolute_error29.744258579010114.4813850462212
mean_squared_error1568.16673661962351.965890988425
root_mean_squared_error39.600085058237218.760754009059
r20.565821937948038-0.00809707021905459
r2_adj0.457277422435048-0.260121337773818
aic54.812641860987645.8478722884779
bic47.72949413277738.7647245602673
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)
Out[7]: 
None                   "GB1"                "GB2"  
r2         0.680958413483623    0.171589926689298  
Rows: 1-1 | Columns: 3

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_GB1
Float(22)
123
prediction_GB2
Float(22)
1123.19485414075352.3409983958023
286.565151526966946.2366341710794
382.550379381088340.3389839353228
4135.47340929738942.7529553824038
5211.17392789788547.8031654048894
6257.29836140125350.0601346005938
7218.48189945648643.0327263054862
877.325157865247724.7699938496104
9-119.3586357589670.517337761241563
10-265.913893678703-17.7981511154327
Rows: 1-10 | Columns: 3

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 vDataFrame to the predict() function, but in this case, it’s essential that the column names of the vDataFrame 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
month
Float(22)
123
prediction_GB1
Float(22)
123
prediction_GB2
Float(22)
111.0123.19485414075352.3409983958023
212.086.565151526966946.2366341710794
313.082.550379381088340.3389839353228
414.0135.47340929738942.7529553824038
515.0211.17392789788547.8031654048894
616.0257.29836140125350.0601346005938
717.0218.48189945648643.0327263054862
818.077.325157865247724.7699938496104
919.0-119.3586357589670.517337761241563
1020.0-265.913893678703-17.7981511154327
Rows: 1-10 | Columns: 3

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
month
Float(22)
123
prediction_GB1
Float(22)
123
prediction_GB2
Float(22)
15.041.240284034512215.1937312651203
26.075.406410797435921.2274543054372
37.081.806463974012225.3104581753953
Rows: 1-3 | Columns: 3

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_variance-1.11578522219719-0.582056843614931
max_error248.99891362401976.5087832724935
median_absolute_error32.985889983236919.4262636686903
mean_absolute_error78.254275263330128.8160721703338
mean_squared_error13765.53641688321382.72358386466
root_mean_squared_error117.32662279671737.1849913791124
r2-2.81126176510514-2.96038260952565
r2_adj-3.76407720638143-3.95047826190706
aic67.84620698531954.0575293344762
bic60.763059257108446.9743816062657
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")
Out[8]: 
None                   "GB1"                "GB2"  
r2         -2.81126176510514    -2.96038260952565  
Rows: 1-1 | Columns: 3

Prediction

Prediction is straight-forward:

model.predict(start = 10, npredictions = 3, method = "forecast")
123
prediction_GB1
Float(22)
123
prediction_GB2
Float(22)
1123.19485414075352.3409983958023
286.565151526966946.2366341710794
382.550379381088340.3389839353228
Rows: 1-3 | Columns: 3

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
month
Float(22)
123
prediction_GB1
Float(22)
123
prediction_GB2
Float(22)
15.041.240284034512215.1937312651203
26.071.468671070983817.8645025418241
37.095.190544973069919.1462197491244
48.093.837675060456418.001252913495
Rows: 1-4 | Columns: 3

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, p: int = 3, method: Literal['yule-walker'] = 'yule-walker', penalty: Literal[None, 'none', 'l2'] = 'none', C: Annotated[int | float | Decimal, 'Python Numbers'] = 1.0, missing: Literal['drop', 'error', 'zero'] = 'error', subtract_mean: bool = False) None

Must be overridden in the child class

Methods

__init__([name, overwrite_model, p, method, ...])

Must be overridden in the child class

contour([nbins, chart])

Draws the model's contour plot.

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

Returns the SQL code needed to deploy the model.

does_model_exists(name[, raise_error, ...])

Checks whether the model is stored in the Vertica database.

drop()

Drops the model from the Vertica 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.

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, or Highcharts) to draw a specific graphic.

get_vertica_attributes([attr_name])

Returns the model Vertica attributes.

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.

register(registered_name[, raise_error])

Registers the model and adds it to in-DB Model versioning environment with a status of 'under_review'.

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 Vertica Binary format.

to_pmml(path)

Exports the model to PMML.

to_python([return_proba, ...])

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

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

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

to_tf(path)

Exports the model to the Frozen Graph format (TensorFlow).

Attributes