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. IfFalse(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 toFalse. 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 fromverticapyare 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], } )
123month123GB1123GB21 1 5 3 2 2 10 7 3 3 20 12 4 4 35 18 5 5 55 22 6 6 80 30 7 7 110 37 8 8 145 39 9 9 185 51 10 10 230 80 Rows: 1-10 | Columns: 3Note
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 Statistic 3.935479640399647 S 45.0 STDS 11.1803398874989 p_value 8.303070332644367e-05 Monotonic Trend ✅ Trend increasing Rows: 1-6 | Columns: 2The 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
VARmodel:from verticapy.machine_learning.vertica.tsa import VAR
Then we can create the model:
model = VAR(p = 2)
Hint
In
verticapy1.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
vDataFrameor the name of the relation stored in the database. The test set is optional and is only used to compute the test metrics. Inverticapy, we don’t work usingXmatrices andyvectors. 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=0to choose the first predictor. In our case, it isGB1. We can setidx=1to switch toGB2…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
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_variance 0.810774470637448 0.592553615026319 max_error 85.3522189681005 40.6116207481806 median_absolute_error 23.2832456559602 10.2310437595838 mean_absolute_error 29.7442585790101 14.4813850462212 mean_squared_error 1568.16673661962 351.965890988425 root_mean_squared_error 39.6000850582372 18.760754009059 r2 0.565821937948038 -0.00809707021905459 r2_adj 0.457277422435048 -0.260121337773818 aic 54.8126418609876 45.8478722884779 bic 47.729494132777 38.7647245602673 Rows: 1-10 | Columns: 3Important
The value for
startcannot be less than thepvalue selected for theVARmodel.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_variance 0.810774470637448 0.592553615026319 max_error 85.3522189681005 40.6116207481806 median_absolute_error 23.2832456559602 10.2310437595838 mean_absolute_error 29.7442585790101 14.4813850462212 mean_squared_error 1568.16673661962 351.965890988425 root_mean_squared_error 39.6000850582372 18.760754009059 r2 0.565821937948038 -0.00809707021905459 r2_adj 0.457277422435048 -0.260121337773818 aic 54.8126418609876 45.8478722884779 bic 47.729494132777 38.7647245602673 Rows: 1-10 | Columns: 3Important
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()
123prediction_GB1123prediction_GB21 123.194854140753 52.3409983958023 2 86.5651515269669 46.2366341710794 3 82.5503793810883 40.3389839353228 4 135.473409297389 42.7529553824038 5 211.173927897885 47.8031654048894 6 257.298361401253 50.0601346005938 7 218.481899456486 43.0327263054862 8 77.3251578652477 24.7699938496104 9 -119.358635758967 0.517337761241563 10 -265.913893678703 -17.7981511154327 Rows: 1-10 | Columns: 3Hint
You can control the number of prediction steps by changing the
npredictionsparameter: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
vDataFrameto thepredict()function, but in this case, it’s essential that the column names of thevDataFramematch 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_tsthe parameter.model.predict(output_estimated_ts = True)
123month123prediction_GB1123prediction_GB21 11.0 123.194854140753 52.3409983958023 2 12.0 86.5651515269669 46.2366341710794 3 13.0 82.5503793810883 40.3389839353228 4 14.0 135.473409297389 42.7529553824038 5 15.0 211.173927897885 47.8031654048894 6 16.0 257.298361401253 50.0601346005938 7 17.0 218.481899456486 43.0327263054862 8 18.0 77.3251578652477 24.7699938496104 9 19.0 -119.358635758967 0.517337761241563 10 20.0 -265.913893678703 -17.7981511154327 Rows: 1-10 | Columns: 3Important
The
output_estimated_tsparameter 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, )
123month123prediction_GB1123prediction_GB21 5.0 41.2402840345122 15.1937312651203 2 6.0 75.4064107974359 21.2274543054372 3 7.0 81.8064639740122 25.3104581753953 Rows: 1-3 | Columns: 3Plots¶
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
npredictionsparameter:model.plot(npredictions = 30).Please refer to Machine Learning - Time Series Plots for more examples.
Note
We use
idx=0to choose the first predictor. In our case, it isGB1. We can setidx=1to switch toGB2…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_error 248.998913624019 76.5087832724935 median_absolute_error 32.9858899832369 19.4262636686903 mean_absolute_error 78.2542752633301 28.8160721703338 mean_squared_error 13765.5364168832 1382.72358386466 root_mean_squared_error 117.326622796717 37.1849913791124 r2 -2.81126176510514 -2.96038260952565 r2_adj -3.76407720638143 -3.95047826190706 aic 67.846206985319 54.0575293344762 bic 60.7630592571084 46.9743816062657 Rows: 1-10 | Columns: 3Notice that the accuracy using
method = forecastis 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")
123prediction_GB1123prediction_GB21 123.194854140753 52.3409983958023 2 86.5651515269669 46.2366341710794 3 82.5503793810883 40.3389839353228 Rows: 1-3 | Columns: 3If 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", )
123month123prediction_GB1123prediction_GB21 5.0 41.2402840345122 15.1937312651203 2 6.0 71.4686710709838 17.8645025418241 3 7.0 95.1905449730699 19.1462197491244 4 8.0 93.8376750604564 18.001252913495 Rows: 1-4 | Columns: 3Plots¶
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.
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.
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