Loading...

verticapy.machine_learning.vertica.tsa.MA

class verticapy.machine_learning.vertica.tsa.MA(name: str = None, overwrite_model: bool = False, q: int = 1, penalty: Literal[None, 'none', 'l2'] = 'none', C: Annotated[int | float | Decimal, 'Python Numbers'] = 1.0, missing: Literal['drop', 'error', 'zero', 'linear_interpolation'] = 'linear_interpolation')

Creates a inDB Moving Average model.

Added in version 11.0.0.

Note

The MA model may be faster and more accurate than ARIMA(0, 0, q) or ARMA(0, q) because the underlying algorithm of MA is quite different.

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.

q: int, optional

Integer in the range [1, 67), the number of lags to consider in the computation.

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.

Attributes

Many attributes are created during the fitting phase.

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.

mu_: float

Represents the mean or average of the series. It is a constant term that reflects the expected value of the time series in the absence of any temporal dependencies or influences from past error terms.

mean_: float

The mean of the time series values.

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 that has some noise variation centered around a mean value.

# Initialization
N = 30 # Number of rows
temp = [23] * N
noisy_temp = [x + random.uniform(-5, 5) for x in temp]

# Building the vDataFrame
data = vp.vDataFrame(
    {
        "day": [i for i in range(1, N + 1)],
        "temp": noisy_temp,
    }
)
123
day
Integer
123
temp
Numeric(19)
1125.99776868256501
2223.78509620789828
3326.987101573945598
4421.083253940016643
5520.086225167143944
6626.68675571707755
7725.121102270162815
8825.66505511256704
9926.20872552468033
101020.59732455277258
111127.009308124075822
121219.51075948939808
131318.179989341221436
141418.103543469447445
151523.370681706296967
161627.636906267910163
171723.926083966340908
181827.277480863553272
191918.080295390297355
202020.66355338354831
212125.470466078666668
222222.200767496639735
232323.257428899548415
242423.198625671701933
252526.367332215581534
262620.641455054989436
272725.481105635616593
282824.511424622975156
292927.68434950257479
303024.339209990522313
Rows: 1-30 | Columns: 2

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["temp"].plot(ts = "day")

It is obvious there is no trend in our example, but we can confirm it by the mkt() (Mann Kendall test) test:

from verticapy.machine_learning.model_selection.statistical_tests import mkt

mkt(data, column = "temp", ts = "day")
value
Mann Kendall Test Statistic0.03568206200700313
S3.0
STDS56.0505724026675
p_value0.9715358738879936
Monotonic Trend
❌
Trendno trend
Rows: 1-6 | Columns: 2

The above report confirms that there is no trend in our data and hence it is stationary. Note the high p-value which is also indicative of the absemce of trend. Once we have established that the data is statioanry, we can then apply MovingAverage model on it.

Model Initialization

First we import the MA model:

from verticapy.machine_learning.vertica.tsa import MA

Then we can create the model:

model = MA(q = 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, "day", "temp")


============
coefficients
============
parameter| value  
---------+--------
  alpha  |-0.18935
phi_(t-1)|-1.11907
phi_(t-2)|-0.65551


===============
timeseries_name
===============
temp

==============
timestamp_name
==============
day

==============
missing_method
==============
linear_interpolation

===========
call_string
===========
moving_average('"public"."_verticapy_tmp_ma_v_demo_7b7740e055a511ef880f0242ac120002_"', '"public"."_verticapy_tmp_view_v_demo_7b838bca55a511ef880f0242ac120002_"', 'temp', 'day'
USING PARAMETERS q=2, missing=linear_interpolation, regularization='none', lambda=1, compute_mse=true);

===============
Additional Info
===============
       Name       |  Value   
------------------+----------
       mean       | 23.63760 
    lag_order     |    2     
      lambda      |  1.00000 
mean_squared_error|4309.56977
rejected_row_count|    0     
accepted_row_count|    30    

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.

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 = 3)
value
explained_variance-1.75165648574836
max_error9.69292628707444
median_absolute_error3.59637179353554
mean_absolute_error4.05972507057071
mean_squared_error25.6051268204896
root_mean_squared_error5.06015086934072
r2-1.75998568189474
r2_adj-1.87038510917053
aic92.38873347556
bic94.1470738742354
Rows: 1-10 | Columns: 2

Important

The value for start has to be greater than the q value selected for the MA 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 10 predictions, starting the forecasting process at index 25.

model.report(start = 25, npredictions = 10)
value
explained_variance-1.49289720704668
max_error5.57379646792889
median_absolute_error3.59637179353554
mean_absolute_error3.27891135112869
mean_squared_error13.3720097557971
root_mean_squared_error3.65677586895849
r2-1.57035016751736
r2_adj-2.42713355668982
aic26.9658184906331
bic16.1846943155013
Rows: 1-10 | Columns: 2

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 = 25, npredictions = 10)
Out[5]: -1.57035016751736

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
Float(22)
126.8860856340679
227.5434357195859
329.9485570910623
433.0709474389758
538.1416913309188
645.862949456756
757.8274747750378
876.2779371940548
9104.768099191753
10148.744950154913
Rows: 1-10 | Column: prediction | Type: Float(22)

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
day
Float(22)
123
prediction
Float(22)
131.026.8860856340679
232.027.5434357195859
333.029.9485570910623
434.033.0709474389758
535.038.1416913309188
636.045.862949456756
737.057.8274747750378
838.076.2779371940548
939.0104.768099191753
1040.0148.744950154913
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,
    "day",
    "temp",
    start = 25,
    npredictions = 10,
    output_estimated_ts = True,
)
123
day
Float(22)
123
prediction
Float(22)
126.026.2152515229183
227.021.8847338420811
328.023.5472536822833
429.025.6345564492153
530.028.54963449065
631.026.8860856340679
732.027.5434357195859
833.029.9485570910623
934.033.0709474389758
1035.038.1416913309188
Rows: 1-10 | Columns: 2

Plots

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

model.plot(data, "day", "temp", npredictions = 15, start=25)

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.

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.

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

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

value
explained_variance-2.1500796531772
max_error14.623695842718
median_absolute_error5.64505003835683
mean_absolute_error6.89645304383813
mean_squared_error63.9490635387499
root_mean_squared_error7.99681583749119
r2-11.2922050747192
r2_adj-15.3896067662923
aic34.7904344213513
bic24.0093102462194
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 = 25, npredictions = 30, method = "forecast")
Out[6]: -11.2922050747192

Prediction

Prediction is straight-forward:

model.predict(start = 25, npredictions = 15, method = "forecast")
123
prediction
Float(22)
126.2152515229183
228.122182546842
330.156474661332
433.6829954615364
538.9629058332403
647.1831467813304
759.8431778009141
879.3990456501726
9109.582140868074
10156.178101146864
11228.107404120281
12339.145201611428
13510.554268046629
14775.158813600652
151183.62927638196
Rows: 1-15 | Column: prediction | Type: Float(22)

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,
    "day",
    "temp",
    start = 25,
    npredictions = 20,
    output_estimated_ts = True,
    output_standard_errors = True,
    method = "forecast",
)
123
day
Float(22)
123
prediction
Float(22)
126.026.2152515229183
227.028.122182546842
328.030.156474661332
429.033.6829954615364
530.038.9629058332403
631.047.1831467813304
732.059.8431778009141
833.079.3990456501726
934.0109.582140868074
1035.0156.178101146864
1136.0228.107404120281
1237.0339.145201611428
1338.0510.554268046629
1439.0775.158813600652
1540.01183.62927638196
1641.01814.18584862748
1742.02787.57711276634
1843.04290.20289101052
1944.06609.80889944925
2045.010190.5887019083
Rows: 1-20 | Columns: 2

Plots

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

model.plot(
    data,
    "day",
    "temp",
    npredictions = 15,
    start = 25,
    method = "forecast",
)
__init__(name: str = None, overwrite_model: bool = False, q: int = 1, penalty: Literal[None, 'none', 'l2'] = 'none', C: Annotated[int | float | Decimal, 'Python Numbers'] = 1.0, missing: Literal['drop', 'error', 'zero', 'linear_interpolation'] = 'linear_interpolation') → None

Must be overridden in the child class

Methods

__init__([name, overwrite_model, q, ...])

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