Python Basics

This notebook demonstrates the most basic capabilities of the vowpalwabit Python interface.

Any application using the Python package needs to begin by importing vowpalwabbit.

import vowpalwabbit

One we’ve imported vowpalwabbit, we can initialize VW either by passing a command line string (e.g., "--quiet -q ab --l2 0.01") or, in a more python-friendly manner, providing those as named arguments. Here we do the latter.

vw = vowpalwabbit.Workspace(quiet=True, q="ab", l2=0.01)

VW objects can do a lot, but the most important thing the can do is create examples and train/predict on those examples.

One way to create an example is to pass a string. This is the equivalent of a string in a VW file. For instance:

ex = vw.example("1 |a two features |b more features here")

Documentation can be looked at with help or you can look it up in the generated docs.

help(vw.learn)
Help on method learn in module vowpalwabbit.pyvw:

learn(ec: Union[ForwardRef('Example'), List[ForwardRef('Example')], str, List[str]]) -> None method of vowpalwabbit.pyvw.Workspace instance
    Perform an online update
    
    Args:
        ec: Examples on which the model gets updated. If using a single object the learner must be a single line learner. If using a list of objects the learner must be a multiline learner. If passing strings they are parsed using :py:meth:`~vowpalwabbit.Workspace.parse` before being learned from. If passing Example objects then they must be given to :py:meth:`~vowpalwabbit.Workspace.finish_example` at a later point.

Let’s run that learn function and get a prediction:

vw.learn(ex)
print(f"current prediction = {ex.get_updated_prediction()}")
current prediction = 0.8230787515640259

Here, get_updated_prediction retrieves the prediction made internally during learning. The “updated” aspect means “if I were to make a prediction on this example after this call to learn, what would that prediction be?”

Okay, so the prediction isn’t quite where we want it yet. Let’s learn a few more times and then print the prediction.

for _ in range(4):
    vw.learn(ex)

print(f"current prediction = {ex.get_updated_prediction()}")
current prediction = 0.9992854595184326

This is now quite a bit closer to what is desired.

Now let’s create a new example another form of example creation: python dictionaries. Here, you must provide a dictionary that maps namespaces (eg, ‘a’ and ‘b’) to lists of features. Features can either be strings (eg "foo"), or pairs of string/floats (eg ("foo", 0.5)). We’ll create an example that’s similar, but not identical to, the previous example to see how well VW has generalized.

Note that in this setup there is no label provided, which means that this will be considered a test example.

ex2 = vw.example({"a": ["features"], "b": ["more", "features", "there"]})

Given this example, we execute learn. But since it’s a test example (no label), this will only make a prediction!

vw.learn(ex2)
print(f"current prediction = {ex2.get_updated_prediction()}")
current prediction = 0.0

Because this is a test example, we can get the raw prediction with get_simplelabel_prediction(). This is simplelabel because it’s a regression problem. If we were doing, for instance, One-Against-All multiclass prediction, we would use get_multiclass_prediction, etc.

This prediction is only about half of what we want, but we’re also missing a number of features.

Let’s now give this example a label and train on it a few times:

ex2.set_label_string("-2.0")
for _ in range(5):
    vw.learn(ex2)

print(f"current prediction = {ex2.get_updated_prediction()}")
current prediction = 0.0

Now we can go back and see how this has affected the prediction behavior on the original example ex. We do this first by removing the label and then calling learn to make a prediction.

ex.set_label_string("")
vw.learn(ex)
print(f"current prediction = {ex.get_updated_prediction()}")
current prediction = 0.9994353652000427

Clearly this has had an impact on the prediction for the first example. Let’s put the label back and then iterate between learning on ex and ex2:

ex.set_label_string("1")
for i in range(10):
    vw.learn(ex)
    vw.learn(ex2)
    print(f"ex prediction = {ex.get_updated_prediction()}")
    print(f"ex2 prediction = {ex2.get_updated_prediction()}")
ex prediction = 0.9994622468948364
ex2 prediction = 0.0
ex prediction = 0.9994670152664185
ex2 prediction = 0.0
ex prediction = 0.9994679093360901
ex2 prediction = 0.0
ex prediction = 0.9994680285453796
ex2 prediction = 0.0
ex prediction = 0.9994680881500244
ex2 prediction = 0.0
ex prediction = 0.9994680285453796
ex2 prediction = 0.0
ex prediction = 0.9994680881500244
ex2 prediction = 0.0
ex prediction = 0.9994680881500244
ex2 prediction = 0.0
ex prediction = 0.9994680285453796
ex2 prediction = 0.0
ex prediction = 0.9994680881500244
ex2 prediction = 0.0

After a handful of updates, we can see that the prediction for ex is going back toward 1.0 and for ex2 back toward -2.0.

Now that we’re done, it’s safest to tell VW that we’re done with these examples and that it can garbage collect them. (This should happen by default when they pass out of scope per Python’s build in garbage collector, but that may not run soon enough if you’re manipulating large numbers of examples at once!)

vw.finish_example(ex)
vw.finish_example(ex2)

Finally, when we’re done with VW entirely, or perhaps want to start up a new VW instance, it’s good behavior to close out any old ones. This is especially important if we wanted to save a model to disk: calling vw.finish() tells it to write the file. You can add f='mymodel' to the initialization line of the vw object if you want to play around with this!

vw.finish()

This is the end of the intro. For more, check out the docs for the main module vowpalwabbit.