The vaex.ml
package brings some machine learning algorithms to vaex
. If you installed the individual subpackages (vaex-core
, vaex-hdf5
, ...) instead of the vaex
metapackage, you may need to install it by running pip install vaex-ml
, or conda install -c conda-forge vaex-ml
.
The API of vaex.ml
stays close to that of scikit-learn, while providing better performance and the ability to efficiently perform operations on data that is larger than the available RAM. This page is an overview and a brief introduction to the capabilities offered by vaex.ml
.
In [1]:
import vaex
import vaex.ml
import numpy as np
import pylab as plt
We will use the well known Iris flower and Titanic passenger list datasets, two classical datasets for machine learning demonstrations.
In [2]:
df = vaex.ml.datasets.load_iris()
df
Out[2]:
In [3]:
df.scatter(df.petal_length, df.petal_width, c_expr=df.class_);
vaex.ml
packs the common numerical scalers:
vaex.ml.StandardScaler
- Scale features by removing their mean and dividing by their variance;vaex.ml.MinMaxScaler
- Scale features to a given range;vaex.ml.RobustScaler
- Scale features by removing their median and scaling them according to a given percentile range;vaex.ml.MaxAbsScaler
- Scale features by their maximum absolute value.The usage is quite similar to that of scikit-learn
, in the sense that each transformer implements the .fit
and .transform
methods.
In [4]:
features = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width']
scaler = vaex.ml.StandardScaler(features=features, prefix='scaled_')
scaler.fit(df)
df_trans = scaler.transform(df)
df_trans
Out[4]:
The output of the .transform
method of any vaex.ml
transformer is a shallow copy of a DataFrame that contains the resulting features of the transformations in addition to the original columns. A shallow copy means that this new DataFrame just references the original one, and no extra memory is used. In addition, the resulting features, in this case the scaled numerical features are virtual columns, which do not take any memory but are computed on the fly when needed. This approach is ideal for working with very large datasets.
vaex.ml
contains several categorical encoders:
vaex.ml.LabelEncoder
- Encoding features with as many integers as categories, startinfg from 0;vaex.ml.OneHotEncoder
- Encoding features according to the one-hot scheme;vaex.ml.FrequencyEncoder
- Encode features by the frequency of their respective categories;vaex.ml.BayesianTargetEncoder
- Encode categories with the mean of their target value;vaex.ml.WeightOfEvidenceEncoder
- Encode categories their weight of evidence value.
The following is a quick example using the Titanic dataset.
In [5]:
df = vaex.ml.datasets.load_titanic()
df.head(5)
Out[5]:
In [6]:
label_encoder = vaex.ml.LabelEncoder(features=['embarked'])
one_hot_encoder = vaex.ml.OneHotEncoder(features=['pclass'])
freq_encoder = vaex.ml.FrequencyEncoder(features=['home_dest'])
df = label_encoder.fit_transform(df)
df = one_hot_encoder.fit_transform(df)
df = freq_encoder.fit_transform(df)
df.head(5)
Out[6]:
Notice that the transformed features are all included in the resulting DataFrame and are appropriately named. This is excellent for the construction of various diagnostic plots, and engineering of more complex features. The fact that the resulting (encoded) features take no memory, allows one to try out or combine a variety of preprocessing steps without spending any extra memory.
The PCA implemented in vaex.ml
can scale to a very large number of samples, even if that data we want to transform does not fit into RAM. To demonstrate this, let us do a PCA transformation on the Iris dataset. For this example, we have replicated this dataset thousands of times, such that it contains over 1 billion samples.
In [7]:
df = vaex.ml.datasets.load_iris_1e9()
n_samples = len(df)
print(f'Number of samples in DataFrame: {n_samples:,}')
In [8]:
features = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width']
pca = vaex.ml.PCA(features=features, n_components=4, progress=True)
pca.fit(df)
The PCA transformer implemented in vaex.ml
can be fit in well under a minute, even when the data comprises 4 columns and 1 billion rows.
In [9]:
df_trans = pca.transform(df)
df_trans
Out[9]:
Recall that the transformed DataFrame, which includes the PCA components, takes no extra memory.
In [10]:
import vaex.ml.cluster
df = vaex.ml.datasets.load_iris()
features = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width']
kmeans = vaex.ml.cluster.KMeans(features=features, n_clusters=3, max_iter=100, verbose=True, random_state=42)
kmeans.fit(df)
df_trans = kmeans.transform(df)
df_trans
Out[10]:
K-Means is an unsupervised algorithm, meaning that the predicted cluster labels in the transformed dataset do not necessarily correspond to the class label. We can map the predicted cluster identifiers to match the class labels, making it easier to construct diagnostic plots.
In [11]:
df_trans['predicted_kmean_map'] = df_trans.prediction_kmeans.map(mapper={0: 1, 1: 2, 2: 0})
df_trans
Out[11]:
Now we can construct simple scatter plots, and see that in the case of the Iris dataset, K-Means does a pretty good job splitting the data into 3 classes.
In [12]:
fig = plt.figure(figsize=(12, 5))
plt.subplot(121)
df_trans.scatter(df_trans.petal_length, df_trans.petal_width, c_expr=df_trans.class_)
plt.title('Original classes')
plt.subplot(122)
df_trans.scatter(df_trans.petal_length, df_trans.petal_width, c_expr=df_trans.predicted_kmean_map)
plt.title('Predicted classes')
plt.tight_layout()
plt.show()
As with any algorithm implemented in vaex.ml
, K-Means can be used on billions of samples. Fitting takes under 2 minutes when applied on the oversampled Iris dataset, numbering over 1 billion samples.
In [13]:
df = vaex.ml.datasets.load_iris_1e9()
n_samples = len(df)
print(f'Number of samples in DataFrame: {n_samples:,}')
In [14]:
%%time
features = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width']
kmeans = vaex.ml.cluster.KMeans(features=features, n_clusters=3, max_iter=100, verbose=True, random_state=31)
kmeans.fit(df)
While vaex.ml
does not yet implement any supervised machine learning models, it does provide wrappers to several popular libraries such as scikit-learn, XGBoost, LightGBM and CatBoost.
The main benefit of these wrappers is that they turn the models into vaex.ml
transformers. This means the models become part of the DataFrame state and thus can be serialized, and their predictions can be returned as virtual columns. This is especially useful for creating various diagnostic plots and evaluating performance metrics at no memory cost, as well as building ensembles.
Scikit-Learn
exampleThe vaex.ml.sklearn
module provides convenient wrappers to the scikit-learn
estimators. In fact, these wrappers can be used with any library that follows the API convention established by scikit-learn
, i.e. implements the .fit
and .transform
methods.
Here is an example:
In [15]:
from vaex.ml.sklearn import Predictor
from sklearn.ensemble import GradientBoostingClassifier
df = vaex.ml.datasets.load_iris()
features = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width']
target = 'class_'
model = GradientBoostingClassifier(random_state=42)
vaex_model = Predictor(features=features, target=target, model=model, prediction_name='prediction')
vaex_model.fit(df=df)
df = vaex_model.transform(df)
df
Out[15]:
One can still train a predictive model on datasets that are too big to fit into memory by leveraging the on-line learners provided by scikit-learn
. The vaex.ml.sklearn.IncrementalPredictor
conveniently wraps these learners and provides control on how the data is passed to them from a vaex
DataFrame.
Let us train a model on the oversampled Iris dataset which comprises over 1 billion samples.
In [16]:
from vaex.ml.sklearn import IncrementalPredictor
from sklearn.linear_model import SGDClassifier
df = vaex.ml.datasets.load_iris_1e9()
features = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width']
target = 'class_'
model = SGDClassifier(learning_rate='constant', eta0=0.0001, random_state=42)
vaex_model = IncrementalPredictor(features=features, target=target, model=model,
batch_size=11_000_000, partial_fit_kwargs={'classes':[0, 1, 2]})
vaex_model.fit(df=df, progress=True)
df = vaex_model.transform(df)
df
Out[16]:
XGBoost
exampleLibraries such as XGBoost
provide more options such as validation during training and early stopping for example. We provide wrappers that keeps close to the native API of these libraries, in addition to the scikit-learn
API.
While the following example showcases the XGBoost
wrapper, vaex.ml
implements similar wrappers for LightGBM
and CatBoost
.
In [17]:
from vaex.ml.xgboost import XGBoostModel
df = vaex.ml.datasets.load_iris_1e5()
df_train, df_test = df.ml.train_test_split(test_size=0.2, verbose=False)
features = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width']
target = 'class_'
params = {'learning_rate': 0.1,
'max_depth': 3,
'num_class': 3,
'objective': 'multi:softmax',
'subsample': 1,
'random_state': 42,
'n_jobs': -1}
booster = XGBoostModel(features=features, target=target, num_boost_round=500, params=params)
booster.fit(df=df_train, evals=[(df_train, 'train'), (df_test, 'test')], early_stopping_rounds=5)
df_test = booster.transform(df_train)
df_test
Out[17]:
Each vaex
DataFrame consists of two parts: data and state. The data is immutable, and any operation such as filtering, adding new columns, or applying transformers or predictive models just modifies the state. This is extremely powerful concept and can completely redefine how we imagine machine learning pipelines.
As an example, let us once again create a model based on the Iris dataset. Here, we will create a couple of new features, do a PCA transformation, and finally train a predictive model.
In [18]:
# Load data and split it in train and test sets
df = vaex.ml.datasets.load_iris()
df_train, df_test = df.ml.train_test_split(test_size=0.2, verbose=False)
# Create new features
df_train['petal_ratio'] = df_train.petal_length / df_train.petal_width
df_train['sepal_ratio'] = df_train.sepal_length / df_train.sepal_width
# Do a PCA transformation
features = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width', 'petal_ratio', 'sepal_ratio']
pca = vaex.ml.PCA(features=features, n_components=6)
df_train = pca.fit_transform(df_train)
# Display the training DataFrame at this stage
df_train
Out[18]:
At this point, we are ready to train a predictive model. In this example, let's use LightGBM
with its scikit-learn
API.
In [19]:
import lightgbm
features = df_train.get_column_names(regex='^PCA')
booster = lightgbm.LGBMClassifier()
vaex_model = Predictor(model=booster, features=features, target='class_')
vaex_model.fit(df=df_train)
df_train = vaex_model.transform(df_train)
df_train
Out[19]:
The final df_train
DataFrame contains all the features we created, including the predictions right at the end. Now, we would like to apply the same transformations to the test set. All we need to do, is to simply extract the state from df_train
and apply it to df_test
. This will propagate all the changes that were made to the training set on the test set.
In [20]:
state = df_train.state_get()
df_test.state_set(state)
df_test
Out[20]:
And just like that df_test
contains all the columns, transformations and the prediction we modelled on the training set. The state can be easily serialized to disk in a form of a JSON file. This makes deployment of a machine learning model as trivial as simply copying a JSON file from one environment to another.
In [21]:
df_train.state_write('./iris_model.json')
df_test.state_load('./iris_model.json')
df_test
Out[21]: