AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
Values and records¶
Values are the terms that hold data, such as an array of counts or a record of a site's measurements. This chapter shows how to build each kind of value from plain Python and array data, how to access the fields of a record, and how to get the stored data back out. We need these steps whenever we pass data into a model or read a result. Terms introduces the labels, specs, and batch forms that values share with every other term.
# On Google Colab, install ProbPipe; elsewhere this cell does nothing.
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
# Colab's preinstalled PyMC 5 does not work with ArviZ 1.x, so the install upgrades PyMC.
%pip install --quiet "probpipe-core[pymc] @ git+https://github.com/TARPS-group/prob-pipe.git@main"
import jax
import jax.numpy as jnp
import numpy as np
import pandas as pd
import xarray as xr
from probpipe import (
Normal,
NumericArray,
Opaque,
Record,
function,
log_prob,
)
Numeric values¶
A NumericArray holds one array.
Its constructor takes the array first and the label as the keyword label=:
weights = NumericArray(jnp.array([0.2, 0.5, 0.3]), label="weights")
print("value:", repr(weights))
print("label of the value:", weights.label)
print("shape of the array:", weights.shape)
print("stored array:", weights.raw)
value: NumericArray('weights', shape=(3,), dtype=float32)
[0.2 0.5 0.3]
label of the value: weights
shape of the array: (3,)
stored array: [0.2 0.5 0.3]
The repr names the label, the shape, and the dtype, and the values follow on the next line.
NumPy's printing formats the values, so np.set_printoptions sets their precision and how a long array is shortened.
.raw is the stored array, which is the form that NumPy, JAX, and plotting code expect.
A NumericArray stores its array in the form it was given.
A NumPy array stays a NumPy array, and .raw is that array with its dtype unchanged:
heights = NumericArray(np.array([1.71, 1.64, 1.8]), label="heights")
print("type of the stored array:", type(heights.raw).__name__)
print("dtype of the stored array:", heights.raw.dtype)
type of the stored array: ndarray dtype of the stored array: float64
We rarely construct a NumericArray ourselves, because an operation accepts a plain array or number and returns its result as a NumericArray.
Here log_prob evaluates the log density of a standard normal distribution at the plain number 0.5:
theta = Normal("theta", 0.0, 1.0)
log_density = log_prob(theta, 0.5)
print("result:", repr(log_density))
print("log density of theta at 0.5:", round(float(log_density), 4))
result: NumericArray('log Normal(theta)', shape=(), dtype=float32)
-1.0439385
log density of theta at 0.5: -1.0439
The result is a NumericArray with an empty shape, which float converts to a Python number.
Its label log Normal(theta) names it in probability notation as the log density of the distribution Normal(theta), as Terms explains.
A function decorated with @function returns a NumericArray from a plain array in the same way, as Functions on values and distributions shows.
Records¶
A Record holds several named fields, such as the measurements of one survey site.
We build one from a mapping of field names to values, and label= names it.
A nested mapping becomes a nested record:
site = Record(
{"count": jnp.array([3, 5, 2]), "area": 1.5, "habitat": {"forest": 0.7, "wetland": 0.3}},
label="site",
)
print("record:", repr(site))
print("number of fields:", len(site))
print("field keys:", site.keys())
record: NumericRecord('site')
count [3 5 2]
area 1.5
habitat/forest 0.7
habitat/wetland 0.3
number of fields: 4
field keys: ('count', 'area', 'habitat/forest', 'habitat/wetland')
Every field of this record is numeric, so Record returns a NumericRecord, which is the record class whose fields are all numeric arrays.
The nested mapping habitat became a nested record with the fields forest and wetland.
Each field has a key, which is its path in the record: the field names from the top of the record down to the field, joined by /.
site.keys() lists the keys in order, and len(site) counts the four fields.
habitat is an interior node of the record, which groups the fields habitat/forest and habitat/wetland.
Record.from_fields takes the fields as keyword arguments.
Without label=, a record is labeled by its top-level field names:
point = Record.from_fields(x=1.0, y=2.0)
print("record:", repr(point))
print("label of the record:", point.label)
record: NumericRecord('record(x,y)')
x 1.
y 2.
label of the record: record(x,y)
Indexing a record by a key returns that field as a NumericArray.
A nested field is indexed by its path, and a nested record by the path of its group:
print("field count:", repr(site["count"]))
print("field habitat/forest:", repr(site["habitat/forest"]))
print("same field, through its group:", repr(site["habitat"]["forest"]))
print("is habitat/wetland a key:", "habitat/wetland" in site)
field count: NumericArray('count', shape=(3,), dtype=int32)
[3 5 2]
field habitat/forest: NumericArray('habitat/forest', shape=(), dtype=float32)
0.7
same field, through its group: NumericArray('habitat/forest', shape=(), dtype=float32)
0.7
is habitat/wetland a key: True
at_path returns the node at any path, either a field or a nested record:
print("node at habitat:", repr(site.at_path("habitat")))
node at habitat: NumericRecord('habitat')
forest 0.7
wetland 0.3
A record also carries a spec, which declares the structure of its fields. For a numeric record, the spec gives the shape of each field:
print("spec of the record:", site.spec)
spec of the record: NumericRecordSpec(count=(3,), area=(), habitat=NumericRecordSpec(forest=(), wetland=()))
count has shape (3,), and the other fields are scalars.
Terms describes the spec of each kind of value.
A change to a record returns a new record and leaves the original as it was.
replace sets the values at existing paths, and without drops fields or nested records:
larger_site = site.replace({"area": 2.0})
counts_only = site.without("habitat", "area")
print("area of the new record:", float(larger_site["area"]))
print("area of the original record:", float(site["area"]))
print("fields left after without:", counts_only.keys())
area of the new record: 2.0
area of the original record: 1.5
fields left after without: ('count',)
Getting raw values out¶
.raw is the stored data of any ProbPipe value.
On a record it returns a nested dict of the stored fields:
site.raw
{'count': Array([3, 5, 2], dtype=int32),
'area': Array(1.5, dtype=float32, weak_type=True),
'habitat': {'forest': Array(0.7, dtype=float32, weak_type=True),
'wetland': Array(0.3, dtype=float32, weak_type=True)}}
A record's .raw is a nested dict, so indexing it by a key returns the stored array for a field and a nested dict for a nested record.
Indexing the record first and then reading .raw on the field returns the same array:
print("raw count, from the record:", site.raw["count"])
print("raw count, from the field:", site["count"].raw)
print("raw habitat:", site.raw["habitat"])
raw count, from the record: [3 5 2]
raw count, from the field: [3 5 2]
raw habitat: {'forest': Array(0.7, dtype=float32, weak_type=True), 'wetland': Array(0.3, dtype=float32, weak_type=True)}
A numeric record also flattens into one vector, which suits optimizers and other code that works on a single array.
to_vector concatenates the fields in the order of site.keys(), and vector_size is the length of the vector:
print("flat vector of the record:", site.to_vector())
print("length of the vector:", site.vector_size)
flat vector of the record: [3. 5. 2. 1.5 0.7 0.3] length of the vector: 6
The vector holds the three counts, then the area, then the two habitat shares.
The tutorials read results with .raw as well, as tutorial 7 does with the posterior quantiles of each parameter.
Field names and labels¶
A field returned by indexing is labeled by its key. A labeled value stored as a field also takes the field's key as its label, because the key is what names it within the record:
holder = Record({"w": weights}, label="holder")
print("label of site['habitat/forest']:", site["habitat/forest"].label)
print("label of holder['w']:", holder["w"].label)
label of site['habitat/forest']: habitat/forest label of holder['w']: w
The field names and the label answer different questions: the label names the record, and the field names name its parts.
rename renames fields by their paths, and the record keeps its label:
renamed = site.rename({"area": "area_km2", "habitat/forest": "habitat/woodland"})
print("record after renaming fields:", repr(renamed))
record after renaming fields: NumericRecord('site')
count [3 5 2]
area_km2 1.5
habitat/woodland 0.7
habitat/wetland 0.3
A function that returns a mapping returns a record whose fields are the keys of the mapping:
@function
def tally(counts: jax.Array) -> dict[str, jax.Array]:
return {"total": jnp.sum(counts), "largest": jnp.max(counts)}
summary = tally(jnp.array([3, 5, 2]))
print("result of tally:", repr(summary))
print("total count:", int(summary["total"]))
result of tally: NumericRecord('tally(counts)')
total 10
largest 5
total count: 10
total and largest are the outputs of the result, and a later step indexes them by these names.
Opaque values¶
A field can hold any Python value.
A string, a pandas DataFrame with text columns, or another non-numeric object becomes an opaque field:
plots = pd.DataFrame({"plot": ["north", "south"], "count": [3, 5]})
survey = Record({"count": jnp.array([3, 5]), "observer": "Ana", "plots": plots}, label="survey")
print("record:", repr(survey))
print("field observer:", repr(survey["observer"]))
print("observer:", survey["observer"].raw)
print("spec of the record:", survey.spec)
record: Record('survey', fields=('count', 'observer', 'plots'))
field observer: Opaque('observer', type=str)
observer: Ana
spec of the record: RecordSpec(count=(2,), observer=OpaqueSpec(type=str), plots=OpaqueSpec(type=DataFrame))
A record with a non-numeric field is a plain Record, since a NumericRecord holds numeric fields only.
Indexing an opaque field returns an Opaque value, whose spec records the Python type it holds, and its .raw is the object itself.
to_vector applies only to a NumericRecord, and survey.to_numeric() raises TypeError, naming the field observer.
An Opaque value can also be constructed on its own, for example to hold a fitted model from another library:
observer = Opaque("Ana", label="observer")
print("value:", repr(observer))
print("stored object:", observer.raw)
value: Opaque('observer', type=str)
stored object: Ana
pandas and xarray fields¶
A pandas Series or an xarray DataArray of numbers is a numeric field.
The record stores it in its native form, so the index of a Series and the dimensions and coordinates of a DataArray are kept:
moose = pd.Series(
[31.0, 44.0, 38.0],
index=pd.Index([1967, 1968, 1969], name="year"),
name="moose",
)
temperature = xr.DataArray(
np.array([[-12.0, -9.5], [-14.0, -11.0]]),
dims=("site", "month"),
coords={"site": ["north", "south"], "month": ["jan", "feb"]},
)
census = Record({"moose": moose, "temperature": temperature}, label="census")
print("record:", repr(census))
print("field temperature:", repr(census["temperature"]))
record: NumericRecord('census')
moose [31. 44. 38.]
temperature [[-12. -9.5]
[-14. -11. ]]
field temperature: NumericArray('temperature', shape=(2, 2), dtype=float64)
[[-12. -9.5]
[-14. -11. ]]
The record is a NumericRecord, and indexing returns each field as a NumericArray with the shape of the stored data.
.raw is the stored object, with its index or coordinates:
census["moose"].raw
year 1967 31.0 1968 44.0 1969 38.0 Name: moose, dtype: float64
census["temperature"].raw.sel(site="south")
<xarray.DataArray (month: 2)> Size: 16B
array([-14., -11.])
Coordinates:
* month (month) <U3 24B 'jan' 'feb'
site <U5 20B 'south'Code that expects a JAX array converts a field with jnp.asarray, which drops the index and the coordinates:
print("moose counts as a JAX array:", jnp.asarray(census["moose"]))
moose counts as a JAX array: [31. 44. 38.]
Tutorial 5 passes counts indexed by year as an xarray DataArray to condition_on and selects the counts of a span of years by year.
See also¶
- Values and records: the API reference for
Record,NumericRecord,NumericArray, andOpaque. - Input and output specs: the specs that declare the structure of a value.
- Terms: the labels, specs, and batches of every term.
- Distributions: the distributions whose draws are values and records.
- Functions on values and distributions: functions that take and return values, and batches of values.
- How a result was computed: the provenance that every value records.
- Tutorial 7 reads posterior quantiles with
.raw, and tutorial 5 uses an xarrayDataArrayof counts.