Generate predictions with YDF in JS
mainThe ydf-inference package allows you to run inference on machine learning models trained with YDF (Python) in both NodeJS and web browsers.
To use it, you must first train and export a model from Python, typically by saving it and zipping the directory. When zipping the model directory, it is important to use the -j flag to avoid including the directory structure, which ensures the model can be loaded correctly by the JS runtime.
Workflow:
- Train a model in Python using
ydf. - Save the model using
model.save("path"). - Zip the model directory (e.g.,
zip -rj model.zip path/to/model). - Load the model in JS using
ydf.loadModelFromZipBlob()(NodeJS) orydf.loadModelFromUrl()(Browser). - Call
model.predict(examples)with a batch of data. - Call
model.unload()to release resources.
# Python training snippet
import ydf
import pandas as pd
# Train a Gradient Boosted Trees model
learner = ydf.GradientBoostedTreesLearner(label="income", pure_serving_model=True)
model = learner.train(train_ds)
# Save the model
model.save("/tmp/my_model")
# Zip the model (CRITICAL: use -j to not include directory structure)
!zip -rj /tmp/my_model.zip /tmp/my_model