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. 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.
- 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 fromvastorbitare 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], } )
123monthInteger123GB1Integer123GB2Integer1 9 185 51 2 10 230 80 3 4 35 18 4 16 605 196 5 18 770 250 6 17 685 222 7 8 145 39 8 7 110 37 9 15 530 172 10 5 55 22 11 6 80 30 12 2 10 7 13 1 5 3 14 13 395 130 15 14 460 150 16 12 335 112 17 3 20 12 18 11 280 95 Rows: 1-18 | Columns: 3Note
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 Statistic 5.757410544997134 S 153.0 STDS 26.40075756488817 p_value 8.541400530670446e-09 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 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
VastFrameor the name of the relation stored in the database. The test set is optional and is only used to compute the test metrics. Invastorbit, 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)
Note
We use
idx=0to choose the first predictor. In our case, it isGB1. We can setidx=1to switch toGB2…_____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_variance 0.9945513984743916 0.9957015830361389 max_error 85.00000000000034 27.142420631860077 median_absolute_error 65.00000000000023 23.321726 mean_absolute_error 65.0000000000003 22.622584896874805 mean_squared_error 4391.666666666706 524.7682978697871 root_mean_squared_error 66.26965117357044 22.907821761786675 r2 0.8564293498002167 0.8263123462478639 r2_adj 0.8359192569145333 0.8014998242832729 aic 82.8205100960065 63.69994478337792 bic 79.88162591734562 60.761060604717024 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.9945513984743916 0.9957015830361389 max_error 85.00000000000034 27.142420631860077 median_absolute_error 65.00000000000023 23.321726 mean_absolute_error 65.0000000000003 22.622584896874805 mean_squared_error 4391.666666666706 524.7682978697871 root_mean_squared_error 66.26965117357044 22.907821761786675 r2 0.8564293498002167 0.8263123462478639 r2_adj 0.8359192569145333 0.8014998242832729 aic 82.8205100960065 63.69994478337792 bic 79.88162591734562 60.761060604717024 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)
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()
123prediction0Double123prediction1Decimal(32, 17)1 769.9999999999997 251.07319803735524 2 684.9999999999997 222.85757936813994 3 604.9999999999995 196.38655242579148 4 529.9999999999997 171.66011721030992 5 459.9999999999997 148.6782737216952 6 394.9999999999998 127.91902253397623 7 334.99999999999966 108.35472942635487 8 279.9999999999998 98.18303723006153 9 229.9999999999998 73.79178980189468 10 184.99999999999977 55.565634209902925 Rows: 1-10 | Columns: 2Hint
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
VastFrameto thepredict()function, but in this case, it’s essential that the column names of theVastFramematch 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)
123prediction0Double123prediction1Decimal(32, 17)1 769.9999999999997 251.07319803735524 2 684.9999999999997 222.85757936813994 3 604.9999999999995 196.38655242579148 4 529.9999999999997 171.66011721030992 5 459.9999999999997 148.6782737216952 6 394.9999999999998 127.91902253397623 7 334.99999999999966 108.35472942635487 8 279.9999999999998 98.18303723006153 9 229.9999999999998 73.79178980189468 10 184.99999999999977 55.565634209902925 Rows: 1-10 | Columns: 2Important
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, )
123prediction0Double123prediction1Decimal(32, 17)1 769.9999999999997 251.07319803735524 2 684.9999999999997 222.85757936813994 3 604.9999999999995 196.38655242579148 Rows: 1-3 | Columns: 2Plots¶
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 0.9945513984743916 0.9957015830361389 max_error 85.00000000000034 27.142420631860077 median_absolute_error 65.00000000000023 23.321726 mean_absolute_error 65.0000000000003 22.622584896874805 mean_squared_error 4391.666666666706 524.7682978697871 root_mean_squared_error 66.26965117357044 22.907821761786675 r2 0.8564293498002167 0.8263123462478639 r2_adj 0.8359192569145333 0.8014998242832729 aic 82.8205100960065 63.69994478337792 bic 79.88162591734562 60.761060604717024 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")
Prediction¶
Prediction is straight-forward:
model.predict(start = 10, npredictions = 3, method = "forecast")
123prediction0Double123prediction1Decimal(32, 17)1 769.9999999999997 251.07319803735524 2 684.9999999999997 222.85757936813994 3 604.9999999999995 196.38655242579148 Rows: 1-3 | Columns: 2If 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", )
123prediction0Double123prediction1Decimal(32, 17)1 769.9999999999997 251.07319803735524 2 684.9999999999997 222.85757936813994 3 604.9999999999995 196.38655242579148 4 529.9999999999997 171.66011721030992 Rows: 1-4 | Columns: 2Plots¶
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.
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.
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