Loading...

verticapy.machine_learning.vertica.naive_bayes.NaiveBayes

class verticapy.machine_learning.vertica.naive_bayes.NaiveBayes(name: str = None, overwrite_model: bool = False, alpha: Annotated[int | float | Decimal, 'Python Numbers'] = 1.0, nbtype: Literal['auto', 'bernoulli', 'categorical', 'multinomial', 'gaussian'] = 'auto')

Creates a NaiveBayes object using the Vertica Naive Bayes algorithm. It is a “probabilistic classifier” based on applying Bayes’ theorem with strong (naïve) independence assumptions between the features.

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.

alpha: float, optional

A float that specifies use of Laplace smoothing if the event model is categorical, multinomial, or Bernoulli.

nbtype: str, optional

Naive Bayes type.

  • auto:

    Vertica NaiveBayes objects treat columns according to data type:

    • FLOAT:

      values are assumed to follow some Gaussian distribution.

    • INTEGER:

      values are assumed to belong to one multinomial distribution.

    • CHAR/VARCHAR:

      values are assumed to follow some categorical distribution. The string values stored in these columns must be no greater than 128 characters.

    • BOOLEAN:

      values are treated as categorical with two values.

  • bernoulli:

    Casts the variables to boolean.

  • categorical:

    Casts the variables to categorical.

  • multinomial:

    Casts the variables to integer.

  • gaussian:

    Casts the variables to float.

Attributes

Many attributes are created during the fitting phase.

prior_: numpy.array

The model’s classes probabilities.

attributes: list of dict

list of the model’s attributes. Each feature is represented by a dictionary, which differs based on the distribution.

classes_: numpy.array

The classes labels.

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.

Load data for machine learning

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 use the iris dataset.

import verticapy.datasets as vpd

data = vpd.load_iris()
123
SepalLengthCm
Numeric(7)
123
SepalWidthCm
Numeric(7)
123
PetalLengthCm
Numeric(7)
123
PetalWidthCm
Numeric(7)
Abc
Species
Varchar(30)
14.63.61.00.2Iris-setosa
24.73.21.30.2Iris-setosa
34.73.21.60.2Iris-setosa
44.83.01.40.1Iris-setosa
54.83.11.60.2Iris-setosa
64.83.41.90.2Iris-setosa
74.93.01.40.2Iris-setosa
84.93.11.50.1Iris-setosa
94.93.11.50.1Iris-setosa
104.93.11.50.1Iris-setosa
115.02.33.31.0Iris-versicolor
125.03.41.50.2Iris-setosa
135.13.51.40.2Iris-setosa
145.43.04.51.5Iris-versicolor
155.43.41.50.4Iris-setosa
165.43.91.30.4Iris-setosa
175.52.43.71.0Iris-versicolor
185.52.43.81.1Iris-versicolor
195.62.74.21.3Iris-versicolor
205.73.04.21.2Iris-versicolor
215.74.41.50.4Iris-setosa
225.82.85.12.4Iris-virginica
235.93.24.81.8Iris-versicolor
246.13.04.61.4Iris-versicolor
256.13.04.91.8Iris-virginica
266.32.54.91.5Iris-versicolor
276.33.34.71.6Iris-versicolor
286.33.36.02.5Iris-virginica
296.42.94.31.3Iris-versicolor
306.53.05.51.8Iris-virginica
316.53.05.82.2Iris-virginica
326.73.05.01.7Iris-versicolor
336.82.84.81.4Iris-versicolor
346.83.25.92.3Iris-virginica
357.03.24.71.4Iris-versicolor
367.13.05.92.1Iris-virginica
377.73.86.72.2Iris-virginica
384.42.91.40.2Iris-setosa
394.52.31.30.3Iris-setosa
404.83.41.60.2Iris-setosa
415.02.03.51.0Iris-versicolor
425.13.31.70.5Iris-setosa
435.13.41.50.2Iris-setosa
445.22.73.91.4Iris-versicolor
455.23.51.50.2Iris-setosa
465.24.11.50.1Iris-setosa
475.43.91.70.4Iris-setosa
485.53.51.30.2Iris-setosa
495.63.04.11.3Iris-versicolor
505.82.73.91.2Iris-versicolor
515.82.75.11.9Iris-virginica
525.82.75.11.9Iris-virginica
535.93.04.21.5Iris-versicolor
545.93.05.11.8Iris-virginica
556.02.75.11.6Iris-versicolor
566.02.94.51.5Iris-versicolor
576.12.84.71.2Iris-versicolor
586.22.84.81.8Iris-virginica
596.22.94.31.3Iris-versicolor
606.32.34.41.3Iris-versicolor
616.32.74.91.8Iris-virginica
626.43.25.32.3Iris-virginica
636.52.84.61.5Iris-versicolor
646.53.05.22.0Iris-virginica
656.53.25.12.0Iris-virginica
666.62.94.61.3Iris-versicolor
676.63.04.41.4Iris-versicolor
686.73.14.41.4Iris-versicolor
696.73.14.71.5Iris-versicolor
706.93.14.91.5Iris-versicolor
716.93.15.42.1Iris-virginica
726.93.25.72.3Iris-virginica
737.23.05.81.6Iris-virginica
747.23.26.01.8Iris-virginica
757.32.96.31.8Iris-virginica
767.72.66.92.3Iris-virginica
773.34.55.67.8Iris-setosa
783.34.55.67.8Iris-setosa
793.34.55.67.8Iris-setosa
803.34.55.67.8Iris-setosa
813.34.55.67.8Iris-setosa
823.34.55.67.8Iris-setosa
833.34.55.67.8Iris-setosa
843.34.55.67.8Iris-setosa
853.34.55.67.8Iris-setosa
863.34.55.67.8Iris-setosa
873.34.55.67.8Iris-setosa
883.34.55.67.8Iris-setosa
893.34.55.67.8Iris-setosa
903.34.55.67.8Iris-setosa
913.34.55.67.8Iris-setosa
923.34.55.67.8Iris-setosa
933.34.55.67.8Iris-setosa
943.34.55.67.8Iris-setosa
953.34.55.67.8Iris-setosa
963.34.55.67.8Iris-setosa
973.34.55.67.8Iris-setosa
983.34.55.67.8Iris-setosa
993.34.55.67.8Iris-setosa
1003.34.55.67.8Iris-setosa
Rows: 1-100 | Columns: 5

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.

You can easily divide your dataset into training and testing subsets using the vDataFrame.train_test_split() method. This is a crucial step when preparing your data for machine learning, as it allows you to evaluate the performance of your models accurately.

data = vpd.load_iris()
train, test = data.train_test_split(test_size = 0.2)

Warning

In this case, VerticaPy utilizes seeded randomization to guarantee the reproducibility of your data split. However, please be aware that this approach may lead to reduced performance. For a more efficient data split, you can use the vDataFrame.to_db() method to save your results into tables or temporary tables. This will help enhance the overall performance of the process.

Balancing the Dataset

In VerticaPy, balancing a dataset to address class imbalances is made straightforward through the balance() function within the preprocessing module. This function enables users to rectify skewed class distributions efficiently. By specifying the target variable and setting parameters like the method for balancing, users can effortlessly achieve a more equitable representation of classes in their dataset. Whether opting for over-sampling, under-sampling, or a combination of both, VerticaPy’s balance() function streamlines the process, empowering users to enhance the performance and fairness of their machine learning models trained on imbalanced data.

To balance the dataset, use the following syntax.

from verticapy.machine_learning.vertica.preprocessing import balance

balanced_train = balance(
    name = "my_schema.train_balanced",
    input_relation = train,
    y = "good",
    method = "hybrid",
)

Note

With this code, a table named train_balanced is created in the my_schema schema. It can then be used to train the model. In the rest of the example, we will work with the full dataset.

Hint

Balancing the dataset is a crucial step in improving the accuracy of machine learning models, particularly when faced with imbalanced class distributions. By addressing disparities in the number of instances across different classes, the model becomes more adept at learning patterns from all classes rather than being biased towards the majority class. This, in turn, enhances the model’s ability to make accurate predictions for under-represented classes. The balanced dataset ensures that the model is not dominated by the majority class and, as a result, leads to more robust and unbiased model performance. Therefore, by employing techniques such as over-sampling, under-sampling, or a combination of both during dataset preparation, practitioners can significantly contribute to achieving higher accuracy and better generalization of their machine learning models.

Model Initialization

First we import the NaiveBayes model:

from verticapy.machine_learning.vertica import NaiveBayes

Then we can create the model:

model = NaiveBayes()

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 Training

We can now fit the model:

model.fit(
    train,
    [
        "SepalLengthCm",
        "SepalWidthCm",
        "PetalLengthCm",
        "PetalWidthCm",
    ],
    "Species",
    test,
)



=======
details
=======
index|  predictor  |  type   
-----+-------------+---------
  0  |   Species   |ResponseC
  1  |SepalLengthCm|Gaussian 
  2  |SepalWidthCm |Gaussian 
  3  |PetalLengthCm|Gaussian 
  4  |PetalWidthCm |Gaussian 


=====
prior
=====
     class     |probability
---------------+-----------
  Iris-setosa  |  0.41500  
Iris-versicolor|  0.19500  
Iris-virginica |  0.39000  


===========
call_string
===========
naive_bayes('"public"."_verticapy_tmp_naivebayes_v_mldb_3135b3cc979a11efa8720242ac120002_"', '"public"."_verticapy_tmp_view_v_mldb_316d4026979a11efa8720242ac120002_"', '"species"', '"SepalLengthCm", "SepalWidthCm", "PetalLengthCm", "PetalWidthCm"' USING PARAMETERS exclude_columns='', alpha=1)

====================
gaussian.Iris-setosa
====================
index|   mu   |sigma_sq
-----+--------+--------
  1  | 4.08554| 0.79369
  2  | 3.98675| 0.38507
  3  | 3.71687| 4.26044
  4  | 4.34217|14.33637


========================
gaussian.Iris-versicolor
========================
index|   mu   |sigma_sq
-----+--------+--------
  1  | 5.91026| 0.28094
  2  | 2.75385| 0.09571
  3  | 4.22564| 0.22933
  4  | 1.32051| 0.04009


=======================
gaussian.Iris-virginica
=======================
index|   mu   |sigma_sq
-----+--------+--------
  1  | 5.54744| 1.53006
  2  | 3.74872| 0.80669
  3  | 7.38077| 4.23846
  4  | 1.91667| 0.05517


===============
Additional Info
===============
       Name       | Value  
------------------+--------
      alpha       | 1.00000
accepted_row_count|  200   
rejected_row_count|   0    

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.

Metrics

We can get the entire report using:

model.report()
Iris-setosa
Iris-versicolor
Iris-virginica
avg_macro
avg_weighted
avg_micro
auc1.00.99766899766899760.99837662337662340.99868187368187360.9987728937728937[null]
prc_auc1.00.99207988980716240.99797879985627020.9966862298878110.9973682476943346[null]
accuracy1.00.980.980.98666666666666670.98680000000000010.9866666666666667
log_loss0.001093867922060960.01729863311088110.01781353943913640.0120686801573594870.012015571731114585[null]
precision1.00.91666666666666661.00.97222222222222220.98166666666666660.98
recall1.01.00.95454545454545460.98484848484848490.980.98
f1_score1.00.95652173913043480.97674418604651170.97775530839231550.98020222446916080.98
mcc1.00.94507269199908270.96001567385323830.96836278861744030.97032288873522310.97
informedness1.00.97435897435897450.95454545454545460.97630147630147630.97435897435897430.97
markedness1.00.91666666666666650.96551724137931050.9607279693486590.96649425287356340.97
csi1.00.91666666666666660.95454545454545460.95707070707070710.96166666666666660.9607843137254902
Rows: 1-11 | Columns: 7

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 = ["auc", "accuracy"]).

For classification models, we can easily modify the cutoff to observe the effect on different metrics:

model.report(cutoff = 0.2)
Iris-setosa
Iris-versicolor
Iris-virginica
avg_macro
avg_weighted
avg_micro
auc1.00.99766899766899760.99837662337662340.99868187368187360.9987728937728937[null]
prc_auc1.00.99207988980716240.99797879985627020.9966862298878110.9973682476943346[null]
accuracy1.00.980.980.98666666666666670.98680000000000010.9866666666666667
log_loss0.001093867922060960.01729863311088110.01781353943913640.0120686801573594870.012015571731114585[null]
precision1.00.91666666666666660.95652173913043480.95772946859903390.9625362318840580.9615384615384616
recall1.01.01.01.01.01.0
f1_score1.00.95652173913043480.97777777777777770.97809983896940410.98065700483091780.9803921568627451
mcc1.00.94507269199908270.96039588110695540.96848952436867940.97049017992685860.9707253433941511
informedness1.00.97435897435897450.96428571428571440.97954822954822960.97864468864468880.98
markedness1.00.91666666666666650.95652173913043480.95772946859903390.9625362318840580.9615384615384617
csi1.00.91666666666666660.95652173913043480.95772946859903390.9625362318840580.9615384615384616
Rows: 1-11 | Columns: 7

You can also use the NaiveBayes.score function to compute any classification metric. The default metric is the accuracy:

model.score(metric = "f1", average = "macro")
Out[4]: 0.9777553083923155

Note

For multi-class scoring, verticapy allows the flexibility to use three averaging techniques: micro, macro and weighted. Please refer to this link for more details on how they are calculated.

Prediction

Prediction is straight-forward:

model.predict(
    test,
    [
        "SepalLengthCm",
        "SepalWidthCm",
        "PetalLengthCm",
        "PetalWidthCm",
    ],
    "prediction",
)
123
SepalLengthCm
Numeric(7)
123
SepalWidthCm
Numeric(7)
123
PetalLengthCm
Numeric(7)
123
PetalWidthCm
Numeric(7)
Abc
Species
Varchar(30)
Abc
prediction
Varchar(100)
14.63.61.00.2Iris-setosaIris-setosa
24.83.41.90.2Iris-setosaIris-setosa
35.02.33.31.0Iris-versicolorIris-versicolor
45.13.51.40.2Iris-setosaIris-setosa
56.13.04.61.4Iris-versicolorIris-versicolor
66.42.94.31.3Iris-versicolorIris-versicolor
76.73.05.01.7Iris-versicolorIris-versicolor
86.83.25.92.3Iris-virginicaIris-virginica
97.13.05.92.1Iris-virginicaIris-virginica
103.34.55.67.8Iris-setosaIris-setosa
113.34.55.67.8Iris-setosaIris-setosa
123.34.55.67.8Iris-setosaIris-setosa
133.34.55.67.8Iris-setosaIris-setosa
143.34.55.67.8Iris-setosaIris-setosa
154.33.01.10.1Iris-setosaIris-setosa
165.03.51.30.3Iris-setosaIris-setosa
175.03.51.60.6Iris-setosaIris-setosa
185.13.51.40.3Iris-setosaIris-setosa
195.52.64.41.2Iris-versicolorIris-versicolor
206.03.44.51.6Iris-versicolorIris-versicolor
216.12.84.01.3Iris-versicolorIris-versicolor
226.32.55.01.9Iris-virginicaIris-virginica
236.93.15.12.3Iris-virginicaIris-virginica
245.23.51.50.2Iris-setosaIris-setosa
255.24.11.50.1Iris-setosaIris-setosa
265.53.51.30.2Iris-setosaIris-setosa
276.12.84.71.2Iris-versicolorIris-versicolor
286.32.34.41.3Iris-versicolorIris-versicolor
296.32.74.91.8Iris-virginicaIris-versicolor
306.93.15.42.1Iris-virginicaIris-virginica
316.93.25.72.3Iris-virginicaIris-virginica
324.34.79.61.8Iris-virginicaIris-virginica
334.34.79.61.8Iris-virginicaIris-virginica
344.34.79.61.8Iris-virginicaIris-virginica
354.34.79.61.8Iris-virginicaIris-virginica
364.34.79.61.8Iris-virginicaIris-virginica
374.34.79.61.8Iris-virginicaIris-virginica
384.34.79.61.8Iris-virginicaIris-virginica
394.34.79.61.8Iris-virginicaIris-virginica
404.34.79.61.8Iris-virginicaIris-virginica
414.43.21.30.2Iris-setosaIris-setosa
425.54.21.40.2Iris-setosaIris-setosa
435.72.84.51.3Iris-versicolorIris-versicolor
446.43.24.51.5Iris-versicolorIris-versicolor
454.34.79.61.8Iris-virginicaIris-virginica
464.34.79.61.8Iris-virginicaIris-virginica
474.34.79.61.8Iris-virginicaIris-virginica
484.34.79.61.8Iris-virginicaIris-virginica
494.34.79.61.8Iris-virginicaIris-virginica
504.34.79.61.8Iris-virginicaIris-virginica
Rows: 1-50 | Columns: 6

Note

Predictions can be made automatically using the test 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.

Probabilities

It is also easy to get the model’s probabilities:

model.predict_proba(
    test,
    [
        "SepalLengthCm",
        "SepalWidthCm",
        "PetalLengthCm",
        "PetalWidthCm",
    ],
    "prediction",
)
123
SepalLengthCm
Numeric(7)
123
SepalWidthCm
Numeric(7)
123
PetalLengthCm
Numeric(7)
123
PetalWidthCm
Numeric(7)
Abc
Species
Varchar(30)
Abc
prediction
Varchar(100)
Abc
prediction_irissetosa
Varchar(100)
Abc
prediction_irisversicolor
Varchar(100)
Abc
prediction_irisvirginica
Varchar(100)
14.63.61.00.2Iris-setosaIris-setosa11.99673e-177.13812e-13
24.83.41.90.2Iris-setosaIris-setosa11.12607e-112.45985e-12
35.02.33.31.0Iris-versicolorIris-versicolor0.02204850.977660.000291911
45.13.51.40.2Iris-setosaIris-setosa18.48865e-142.24375e-12
56.13.04.61.4Iris-versicolorIris-versicolor0.0002453070.9968890.00286587
66.42.94.31.3Iris-versicolorIris-versicolor6.93524e-050.9993950.000535208
76.73.05.01.7Iris-versicolorIris-versicolor0.0009641160.5453360.4537
86.83.25.92.3Iris-virginicaIris-virginica0.002778142.04969e-070.997222
97.13.05.92.1Iris-virginicaIris-virginica0.0003197686.21202e-060.999674
103.34.55.67.8Iris-setosaIris-setosa12.74274e-2391.97778e-136
113.34.55.67.8Iris-setosaIris-setosa12.74274e-2391.97778e-136
123.34.55.67.8Iris-setosaIris-setosa12.74274e-2391.97778e-136
133.34.55.67.8Iris-setosaIris-setosa12.74274e-2391.97778e-136
143.34.55.67.8Iris-setosaIris-setosa12.74274e-2391.97778e-136
154.33.01.10.1Iris-setosaIris-setosa16.82381e-174.78456e-14
165.03.51.30.3Iris-setosaIris-setosa12.34306e-133.51505e-11
175.03.51.60.6Iris-setosaIris-setosa14.68594e-091.22179e-07
185.13.51.40.3Iris-setosaIris-setosa11.19124e-124.4719e-11
195.52.64.41.2Iris-versicolorIris-versicolor0.0002370940.9995950.000168385
206.03.44.51.6Iris-versicolorIris-versicolor0.008063170.8160230.175914
216.12.84.01.3Iris-versicolorIris-versicolor8.38083e-050.9996120.000303761
226.32.55.01.9Iris-virginicaIris-virginica0.001143060.1911460.807711
236.93.15.12.3Iris-virginicaIris-virginica0.003685493.16115e-050.996283
245.23.51.50.2Iris-setosaIris-setosa14.04714e-132.87186e-12
255.24.11.50.1Iris-setosaIris-setosa12.38416e-178.65558e-14
265.53.51.30.2Iris-setosaIris-setosa11.12599e-134.04774e-12
276.12.84.71.2Iris-versicolorIris-versicolor0.0001288180.999610.000260846
286.32.34.41.3Iris-versicolorIris-versicolor2.48038e-050.9993650.000610549
296.32.74.91.8Iris-virginicaIris-versicolor0.001053690.6004950.398451
306.93.15.42.1Iris-virginicaIris-virginica0.0009912420.0002054460.998803
316.93.25.72.3Iris-virginicaIris-virginica0.002537636.79503e-070.997462
324.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
334.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
344.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
354.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
364.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
374.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
384.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
394.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
404.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
414.43.21.30.2Iris-setosaIris-setosa18.42109e-151.12566e-12
425.54.21.40.2Iris-setosaIris-setosa19.59925e-173.1532e-12
435.72.84.51.3Iris-versicolorIris-versicolor0.0002101410.9992740.000515488
446.43.24.51.5Iris-versicolorIris-versicolor0.0006216060.9771220.0222561
454.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
464.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
474.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
484.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
494.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
504.34.79.61.8Iris-virginicaIris-virginica0.005347966.42903e-380.994652
Rows: 1-50 | Columns: 9

Note

Probabilities are added to the vDataFrame, and VerticaPy uses the corresponding probability function in SQL behind the scenes. You can use the pos_label parameter to add only the probability of the selected category.

Confusion Matrix

You can obtain the confusion matrix.

model.confusion_matrix()
Out[5]: 
array([[17,  0,  0],
       [ 0, 11,  0],
       [ 0,  1, 21]])

Hint

In the context of multi-class classification, you typically work with an overall confusion matrix that summarizes the classification efficiency across all classes. However, you have the flexibility to specify a pos_label and adjust the cutoff threshold. In this case, a binary confusion matrix is computed, where the chosen class is treated as the positive class, allowing you to evaluate its efficiency as if it were a binary classification problem.

model.confusion_matrix(pos_label = "Iris-setosa", cutoff = 0.6)
Out[6]: 
array([[33,  0],
       [ 0, 17]])

Note

In classification, the cutoff is a threshold value used to determine class assignment based on predicted probabilities or scores from a classification model. In binary classification, if the predicted probability for a specific class is greater than or equal to the cutoff, the instance is assigned to the positive class; otherwise, it is assigned to the negative class. Adjusting the cutoff allows for trade-offs between true positives and false positives, enabling the model to be optimized for specific objectives or to consider the relative costs of different classification errors. The choice of cutoff is critical for tailoring the model’s performance to meet specific needs.

Main Plots (Classification Curves)

Classification models allow for the creation of various plots that are very helpful in understanding the model, such as the ROC Curve, PRC Curve, Cutoff Curve, Gain Curve, and more.

Most of the classification curves can be found in the Machine Learning - Classification Curve.

For example, let’s draw the model’s ROC curve.

model.roc_curve(pos_label = "Iris-setosa")

Important

Most of the curves have a parameter called nbins, which is essential for estimating metrics. The larger the nbins, the more precise the estimation, but it can significantly impact performance. Exercise caution when increasing this parameter excessively.

Hint

In binary classification, various curves can be easily plotted. However, in multi-class classification, it’s important to select the pos_label, representing the class to be treated as positive when drawing the curve.

Other Plots

Contour plot is another useful plot that can be produced for models with two predictors.

model.contour(pos_label = "Iris-setosa")

Important

Machine learning models with two predictors can usually benefit from their own contour plot. This visual representation aids in exploring predictions and gaining a deeper understanding of how these models perform in different scenarios. Please refer to Contour Plot for more examples.

Parameter Modification

In order to see the parameters:

model.get_params()
Out[7]: {'alpha': 1.0, 'nbtype': 'auto'}

And to manually change some of the parameters:

model.set_params({'alpha': 0.9})

Model Register

In order to register the model for tracking and versioning:

model.register("model_v1")

Please refer to /notebooks/ml/model_tracking_versioning/index.ipynb for more details on model tracking and versioning.

Model Exporting

To Memmodel

model.to_memmodel()

Note

MemModel objects serve as in-memory representations of machine learning models. They can be used for both in-database and in-memory prediction tasks. These objects can be pickled in the same way that you would pickle a scikit-learn model.

The following methods for exporting the model use MemModel, and it is recommended to use MemModel directly.

To SQL

You can get the SQL code by:

model.to_sql()
Out[9]: 'CASE WHEN "SepalLengthCm" IS NULL OR "SepalWidthCm" IS NULL OR "PetalLengthCm" IS NULL OR "PetalWidthCm" IS NULL THEN NULL WHEN 0.32251957572020434 * EXP(- POWER("SepalLengthCm" - 5.5474358974359, 2) / 3.06011655011654) * 0.44417860091853717 * EXP(- POWER("SepalWidthCm" - 3.74871794871795, 2) / 1.613373293373328) * 0.19377877157815893 * EXP(- POWER("PetalLengthCm" - 7.38076923076923, 2) / 8.47691308691294) * 1.698424069445676 * EXP(- POWER("PetalWidthCm" - 1.91666666666667, 2) / 0.1103463203463292) * 0.39 >= 0.4478002956817784 * EXP(- POWER("SepalLengthCm" - 4.0855421686747, 2) / 1.58738172200995) * 0.642898499888941 * EXP(- POWER("SepalWidthCm" - 3.98674698795181, 2) / 0.77013223626212) * 0.19327810066060777 * EXP(- POWER("PetalLengthCm" - 3.71686746987952, 2) / 8.520887452248) * 0.1053635639885031 * EXP(- POWER("PetalWidthCm" - 4.3421686746988, 2) / 28.6727416985012) * 0.415 AND 0.32251957572020434 * EXP(- POWER("SepalLengthCm" - 5.5474358974359, 2) / 3.06011655011654) * 0.44417860091853717 * EXP(- POWER("SepalWidthCm" - 3.74871794871795, 2) / 1.613373293373328) * 0.19377877157815893 * EXP(- POWER("PetalLengthCm" - 7.38076923076923, 2) / 8.47691308691294) * 1.698424069445676 * EXP(- POWER("PetalWidthCm" - 1.91666666666667, 2) / 0.1103463203463292) * 0.39 >= 0.7526614411763235 * EXP(- POWER("SepalLengthCm" - 5.91025641025641, 2) / 0.561889338731422) * 1.2895399654494928 * EXP(- POWER("SepalWidthCm" - 2.75384615384615, 2) / 0.191417004048581) * 0.8330750754134963 * EXP(- POWER("PetalLengthCm" - 4.22564102564103, 2) / 0.45865047233468) * 1.9923601374340967 * EXP(- POWER("PetalWidthCm" - 1.32051282051282, 2) / 0.0801889338731448) * 0.195 THEN \'Iris-virginica\' WHEN 0.7526614411763235 * EXP(- POWER("SepalLengthCm" - 5.91025641025641, 2) / 0.561889338731422) * 1.2895399654494928 * EXP(- POWER("SepalWidthCm" - 2.75384615384615, 2) / 0.191417004048581) * 0.8330750754134963 * EXP(- POWER("PetalLengthCm" - 4.22564102564103, 2) / 0.45865047233468) * 1.9923601374340967 * EXP(- POWER("PetalWidthCm" - 1.32051282051282, 2) / 0.0801889338731448) * 0.195 >= 0.4478002956817784 * EXP(- POWER("SepalLengthCm" - 4.0855421686747, 2) / 1.58738172200995) * 0.642898499888941 * EXP(- POWER("SepalWidthCm" - 3.98674698795181, 2) / 0.77013223626212) * 0.19327810066060777 * EXP(- POWER("PetalLengthCm" - 3.71686746987952, 2) / 8.520887452248) * 0.1053635639885031 * EXP(- POWER("PetalWidthCm" - 4.3421686746988, 2) / 28.6727416985012) * 0.415 THEN \'Iris-versicolor\' ELSE \'Iris-setosa\' END'

To Python

To obtain the prediction function in Python syntax, use the following code:

X = [[5, 2, 3, 1]]

model.to_python()(X)
Out[11]: array(['Iris-versicolor'], dtype='<U15')

Hint

The to_python() method is used to retrieve predictions, probabilities, or cluster distances. For specific details on how to use this method for different model types, refer to the relevant documentation for each model.

__init__(name: str = None, overwrite_model: bool = False, alpha: Annotated[int | float | Decimal, 'Python Numbers'] = 1.0, nbtype: Literal['auto', 'bernoulli', 'categorical', 'multinomial', 'gaussian'] = 'auto') None

Must be overridden in the child class

Methods

__init__([name, overwrite_model, alpha, nbtype])

Must be overridden in the child class

classification_report([metrics, cutoff, ...])

Computes a classification report using multiple model evaluation metrics (auc, accuracy, f1...).

confusion_matrix([pos_label, cutoff])

Computes the model confusion matrix.

contour([pos_label, nbins, chart])

Draws the model's contour plot.

cutoff_curve([pos_label, nbins, show, chart])

Draws the model Cutoff curve.

deploySQL([X, pos_label, cutoff, allSQL])

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.

fit(input_relation, X, 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.

lift_chart([pos_label, nbins, show, chart])

Draws the model Lift Chart.

prc_curve([pos_label, nbins, show, chart])

Draws the model PRC curve.

predict(vdf[, X, name, cutoff, inplace])

Predicts using the input relation.

predict_proba(vdf[, X, name, pos_label, inplace])

Returns the model's probabilities 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'.

report([metrics, cutoff, labels, nbins])

Computes a classification report using multiple model evaluation metrics (auc, accuracy, f1...).

roc_curve([pos_label, nbins, show, chart])

Draws the model ROC curve.

score([metric, average, pos_label, cutoff, ...])

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_memmodel()

Converts the model to an InMemory object that can be used for different types of predictions.

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