Loading...

vastorbit.machine_learning.vast.cluster.NearestCentroid

class vastorbit.machine_learning.vast.cluster.NearestCentroid(name: str = None, overwrite_model: bool = False, p: int = 2)

Creates a NearestCentroid object using the k-nearest centroid algorithm. This object uses pure SQL to compute the distances and final score.

Important

This algorithm is not VAST Native and relies solely on SQL for attribute computation. While this model does not take advantage of the benefits provided by a model management system, including versioning and tracking, the SQL code it generates can still be used to create a pipeline.

Parameters:

p (int, optional) – The p corresponding to the one of the p-distances (distance metric used to compute the model).

Variables:
  • created (Many attributes are)

  • phase. (during the fitting)

  • clusters_ (numpy.array) – Cluster centers.

  • p_ (int) – The p of the p-distances.

  • classes_ (numpy.array) – The classes labels.

  • 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.

Load data for machine learning

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 from vastorbit are used as intended without interfering with functions from other libraries.

For this example, we will use the iris dataset.

import vastorbit.datasets as vod

data = vod.load_iris()
123
sepallengthcm
Decimal(5, 2)
123
sepalwidthcm
Decimal(5, 2)
123
petallengthcm
Decimal(5, 2)
123
petalwidthcm
Decimal(5, 2)
Abc
species
Varchar(30)
15.13.51.40.2Iris-setosa
24.93.01.40.2Iris-setosa
34.73.21.30.2Iris-setosa
44.63.11.50.2Iris-setosa
55.03.61.40.2Iris-setosa
65.43.91.70.4Iris-setosa
74.63.41.40.3Iris-setosa
85.03.41.50.2Iris-setosa
94.42.91.40.2Iris-setosa
104.93.11.50.1Iris-setosa
115.43.71.50.2Iris-setosa
124.83.41.60.2Iris-setosa
134.83.01.40.1Iris-setosa
144.33.01.10.1Iris-setosa
155.84.01.20.2Iris-setosa
165.74.41.50.4Iris-setosa
175.43.91.30.4Iris-setosa
185.13.51.40.3Iris-setosa
195.73.81.70.3Iris-setosa
205.13.81.50.3Iris-setosa
215.43.41.70.2Iris-setosa
225.13.71.50.4Iris-setosa
234.63.61.00.2Iris-setosa
245.13.31.70.5Iris-setosa
254.83.41.90.2Iris-setosa
265.03.01.60.2Iris-setosa
275.03.41.60.4Iris-setosa
285.23.51.50.2Iris-setosa
295.23.41.40.2Iris-setosa
304.73.21.60.2Iris-setosa
314.83.11.60.2Iris-setosa
325.43.41.50.4Iris-setosa
335.24.11.50.1Iris-setosa
345.54.21.40.2Iris-setosa
354.93.11.50.1Iris-setosa
365.03.21.20.2Iris-setosa
375.53.51.30.2Iris-setosa
384.93.11.50.1Iris-setosa
394.43.01.30.2Iris-setosa
405.13.41.50.2Iris-setosa
415.03.51.30.3Iris-setosa
424.52.31.30.3Iris-setosa
434.43.21.30.2Iris-setosa
445.03.51.60.6Iris-setosa
455.13.81.90.4Iris-setosa
464.83.01.40.3Iris-setosa
475.13.81.60.2Iris-setosa
484.63.21.40.2Iris-setosa
495.33.71.50.2Iris-setosa
505.03.31.40.2Iris-setosa
517.03.24.71.4Iris-versicolor
526.43.24.51.5Iris-versicolor
536.93.14.91.5Iris-versicolor
545.52.34.01.3Iris-versicolor
556.52.84.61.5Iris-versicolor
565.72.84.51.3Iris-versicolor
576.33.34.71.6Iris-versicolor
584.92.43.31.0Iris-versicolor
596.62.94.61.3Iris-versicolor
605.22.73.91.4Iris-versicolor
615.02.03.51.0Iris-versicolor
625.93.04.21.5Iris-versicolor
636.02.24.01.0Iris-versicolor
646.12.94.71.4Iris-versicolor
655.62.93.61.3Iris-versicolor
666.73.14.41.4Iris-versicolor
675.63.04.51.5Iris-versicolor
685.82.74.11.0Iris-versicolor
696.22.24.51.5Iris-versicolor
705.62.53.91.1Iris-versicolor
715.93.24.81.8Iris-versicolor
726.12.84.01.3Iris-versicolor
736.32.54.91.5Iris-versicolor
746.12.84.71.2Iris-versicolor
756.42.94.31.3Iris-versicolor
766.63.04.41.4Iris-versicolor
776.82.84.81.4Iris-versicolor
786.73.05.01.7Iris-versicolor
796.02.94.51.5Iris-versicolor
805.72.63.51.0Iris-versicolor
815.52.43.81.1Iris-versicolor
825.52.43.71.0Iris-versicolor
835.82.73.91.2Iris-versicolor
846.02.75.11.6Iris-versicolor
855.43.04.51.5Iris-versicolor
866.03.44.51.6Iris-versicolor
876.73.14.71.5Iris-versicolor
886.32.34.41.3Iris-versicolor
895.63.04.11.3Iris-versicolor
905.52.54.01.3Iris-versicolor
915.52.64.41.2Iris-versicolor
926.13.04.61.4Iris-versicolor
935.82.64.01.2Iris-versicolor
945.02.33.31.0Iris-versicolor
955.62.74.21.3Iris-versicolor
965.73.04.21.2Iris-versicolor
975.72.94.21.3Iris-versicolor
986.22.94.31.3Iris-versicolor
995.12.53.01.1Iris-versicolor
1005.72.84.11.3Iris-versicolor
Rows: 1-100 | Columns: 5

Note

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.

You can easily divide your dataset into training and testing subsets using the VastFrame.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 = vod.load_iris()
train, test = data.train_test_split(test_size = 0.2)

Warning

In this case, vastorbit 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 VastFrame.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 vastorbit, 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, vastorbit’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 vastorbit.machine_learning.vast.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 NearestCentroid model:

from vastorbit.machine_learning.vast import NearestCentroid

Then we can create the model:

model = NearestCentroid(p = 2)

Model Training

We can now fit the model:

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

Important

To train a model, you can directly use the VastFrame 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 vastorbit, we don’t work using X matrices and y vectors. Instead, we work directly with lists of predictors and the response name.

Important

As this model is not native, it solely relies on SQL statements to compute various attributes, storing them within the object. No data is saved in the database.

Metrics

We can get the entire report using:

model.report()
Iris-setosaIris-versicolorIris-virginicaavg_macroavg_weightedavg_micro
auc1.00.94642857142857140.94298245614035080.96313700918964070.9658319185059422[null]
prc_auc0.222873900293255050.52761606209882080.2835590708574580.344683011083177950.31517768027420334[null]
accuracy1.00.87096774193548390.87096774193548390.9139784946236560.92091571279916750.9139784946236559
log_loss0.242289913882663580.30527681530026310.31805821801342030.288541649065449050.2858424287049951[null]
precision1.00.63636363636363641.00.87878787878787880.91788856304985330.8709677419354839
recall1.01.00.66666666666666660.88888888888888880.87096774193548390.8709677419354839
f1_score1.00.77777777777777780.80.85925925925925920.87240143369175630.8709677419354839
mcc1.00.72821908125441910.74210823852128170.82344243992523360.83880104616246160.8064516129032258
informedness1.00.83333333333333350.66666666666666650.83333333333333340.83333333333333340.8064516129032258
markedness1.00.63636363636363620.82608695652173920.82081686429512510.85056738492923620.8064516129032258
csi1.00.63636363636363640.66666666666666660.76767676767676760.78885630498533720.7714285714285715
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-setosaIris-versicolorIris-virginicaavg_macroavg_weightedavg_micro
auc1.00.97023809523809520.99122807017543870.9871553884711780.9898839841539333[null]
prc_auc0.193548387096774240.123809523809523810.258528545826932740.191962152244410270.20295451166939196[null]
accuracy0.90322580645161290.58064516129032260.87096774193548390.78494623655913990.81789802289281990.7849462365591398
log_loss0.18951347313281370.30527681530026310.345389585986744240.280059958139940330.27599272311408185[null]
precision0.80.350.750.63333333333333330.67903225806451620.6078431372549019
recall1.01.01.01.01.01.0
f1_score0.8888888888888890.51851851851851850.85714285714285710.75485008818342160.79296808329066390.7560975609756097
mcc0.82078268166812330.40052049468993050.76948376406386550.66359564680730640.70602712295527040.6416889479197478
informedness0.84210526315789470.458333333333333260.78947368421052630.69663742690058470.73507357102433490.6774193548387095
markedness0.80.35000000000000010.750.63333333333333340.67903225806451630.607843137254902
csi0.80.350.750.63333333333333330.67903225806451620.6078431372549019
Rows: 1-11 | Columns: 7

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

model.score(metric = "f1", average = "macro")

Note

For multi-class scoring, vastorbit 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
Decimal(5, 2)
123
sepalwidthcm
Decimal(5, 2)
123
petallengthcm
Decimal(5, 2)
123
petalwidthcm
Decimal(5, 2)
Abc
species
Varchar(30)
123
seedrand
Decimal(26, 6)
Abc
prediction
Varchar(15)
14.93.01.40.2Iris-setosa0.12Iris-setosa
24.83.41.60.2Iris-setosa0.17Iris-setosa
34.83.01.40.1Iris-setosa0.1Iris-setosa
45.84.01.20.2Iris-setosa0.13Iris-setosa
55.13.71.50.4Iris-setosa0.08Iris-setosa
65.13.31.70.5Iris-setosa0.18Iris-setosa
75.03.41.60.4Iris-setosa0.03Iris-setosa
85.23.51.50.2Iris-setosa0.08Iris-setosa
94.83.11.60.2Iris-setosa0.18Iris-setosa
105.54.21.40.2Iris-setosa0.05Iris-setosa
115.03.51.30.3Iris-setosa0.14Iris-setosa
125.13.81.60.2Iris-setosa0.04Iris-setosa
136.33.34.71.6Iris-versicolor0.16Iris-versicolor
146.73.14.41.4Iris-versicolor0.17Iris-versicolor
156.63.04.41.4Iris-versicolor0.18Iris-versicolor
165.52.43.81.1Iris-versicolor0.09Iris-versicolor
176.73.14.71.5Iris-versicolor0.05Iris-versicolor
185.52.64.41.2Iris-versicolor0.0Iris-versicolor
196.22.94.31.3Iris-versicolor0.13Iris-versicolor
205.82.75.11.9Iris-virginica0.16Iris-versicolor
216.42.75.31.9Iris-virginica0.02Iris-virginica
226.43.25.32.3Iris-virginica0.1Iris-virginica
237.23.26.01.8Iris-virginica0.0Iris-virginica
246.42.85.62.2Iris-virginica0.03Iris-virginica
256.32.85.11.5Iris-virginica0.13Iris-versicolor
266.03.04.81.8Iris-virginica0.02Iris-versicolor
276.93.15.42.1Iris-virginica0.17Iris-virginica
285.82.75.11.9Iris-virginica0.0Iris-versicolor
296.73.05.22.3Iris-virginica0.15Iris-virginica
306.32.55.01.9Iris-virginica0.09Iris-virginica
316.53.05.22.0Iris-virginica0.05Iris-virginica
Rows: 1-31 | Columns: 7

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 VastFrame to the predict() function, but in this case, it’s essential that the column names of the VastFrame 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
Decimal(5, 2)
123
sepalwidthcm
Decimal(5, 2)
123
petallengthcm
Decimal(5, 2)
123
petalwidthcm
Decimal(5, 2)
Abc
species
Varchar(30)
123
seedrand
Decimal(26, 6)
Abc
prediction
Varchar(15)
123
prediction_irissetosa
Double
123
prediction_irisversicolor
Double
123
prediction_irisvirginica
Double
14.73.21.30.2Iris-setosa0.12Iris-setosa0.76139656751030030.144674175378208260.09392925711149135
24.83.01.40.1Iris-setosa0.17Iris-setosa0.72897221376644010.165335418555966670.10569236767759328
34.33.01.10.1Iris-setosa0.1Iris-setosa0.67525248817904390.194613690423302230.1301338213976539
45.74.41.50.4Iris-setosa0.13Iris-setosa0.60896272249117270.232494971630846870.15854230587798052
54.63.61.00.2Iris-setosa0.08Iris-setosa0.72290310813427170.165137693142541760.11195919872318653
64.83.41.90.2Iris-setosa0.18Iris-setosa0.78419317205724930.13352191670164010.08228491124111063
75.23.51.50.2Iris-setosa0.03Iris-setosa0.77795142185109210.135608993755401970.08643958439350587
85.23.41.40.2Iris-setosa0.08Iris-setosa0.76923822623288450.140686098929396010.09007567483771937
95.43.41.50.4Iris-setosa0.18Iris-setosa0.7625735777530490.145843029565850520.09158339268110065
104.93.11.50.1Iris-setosa0.05Iris-setosa0.74979183493321120.153236918235552830.09697124683123601
114.52.31.30.3Iris-setosa0.14Iris-setosa0.614200785294350.234432976695371550.1513662380102784
124.63.21.40.2Iris-setosa0.04Iris-setosa0.76221514389467180.14445530140843040.09332955469689763
134.92.43.31.0Iris-versicolor0.16Iris-versicolor0.33639283746546820.45989944257394410.20370771996058756
145.63.04.51.5Iris-versicolor0.17Iris-versicolor0.111219252493521260.68943190676957160.1993488407369071
156.82.84.81.4Iris-versicolor0.18Iris-versicolor0.133094138911804940.47146261061538170.39544325047281337
165.52.43.71.0Iris-versicolor0.09Iris-versicolor0.20745855993968060.60721444632949870.18532699373082068
176.32.34.41.3Iris-versicolor0.05Iris-versicolor0.122544209448061770.65115262061313060.22630316993880756
186.13.04.61.4Iris-versicolor0.0Iris-versicolor0.100603384508081480.67235352098250830.22704309450941013
195.12.53.01.1Iris-versicolor0.13Iris-versicolor0.377722354516583150.42975185386401950.19252579161939745
207.13.05.92.1Iris-virginica0.16Iris-virginica0.084429529440760360.191369730941533620.724200739617706
216.83.05.52.1Iris-virginica0.02Iris-virginica0.072904575736558440.188670394830071450.7384250294333701
226.53.05.51.8Iris-virginica0.1Iris-virginica0.070478149844994970.203735216310720470.7257866338442845
236.22.84.81.8Iris-virginica0.0Iris-versicolor0.114742192151154260.52204505829396050.3632127495548853
246.32.85.11.5Iris-virginica0.03Iris-versicolor0.112232984181018370.44654723056148940.4412197852574921
256.12.65.61.4Iris-virginica0.13Iris-virginica0.115887321892985840.35671024457740580.5274024335296085
266.93.15.42.1Iris-virginica0.02Iris-virginica0.088338605269724650.225767195224787830.6858941995054876
276.73.15.62.4Iris-virginica0.17Iris-virginica0.075061255957183440.18063635979896860.744302384243848
286.83.25.92.3Iris-virginica0.0Iris-virginica0.064287025774832280.145719720187927670.7899932540372401
296.32.55.01.9Iris-virginica0.15Iris-virginica0.118826466532705930.438537346089733050.44263618737756105
306.53.05.22.0Iris-virginica0.09Iris-virginica0.095614542848906820.29343110635920530.6109543507918879
316.23.45.42.3Iris-virginica0.05Iris-virginica0.101979548875862980.260478183238076750.6375422678860603
Rows: 1-31 | Columns: 10

Note

Probabilities are added to the VastFrame, and vastorbit 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()

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.

Specific confusion matrix:

model.confusion_matrix(pos_label = "Iris-setosa", cutoff = 0.6)

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

And to manually change some of the parameters:

model.set_params({'p': 3})

Model Register

As this model is not native, it does not support model management and versioning. However, it is possible to use the SQL code it generates for deployment.

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

To Python

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

X = [[5, 2, 3, 1]]
model.to_python()(X)

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, p: int = 2) None

Methods

__init__([name, overwrite_model, p])

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.

drop()

NearestCentroid models are not stored in the VAST 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) to draw a specific graphic.

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.

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

to_memmodel()

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

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