Skip to main content

Multi-feature inference

from phasic import (
    Graph, with_ipv,
    GaussPrior, HalfCauchyPrior, DataPrior,
    SparseObservations, dense_to_sparse,
    ConstantStepSize, ExpStepSize, AdaptiveStepSize, WarmupExpStepSize,
    ConstantRegularization, ExpRegularization, ExponentialCDFRegularization,
    Adam, Adamelia,
    set_log_level, clear_caches,
)
import sys
import numpy as np
import jax.numpy as jnp
import matplotlib.pyplot as plt
import seaborn as sns
np.random.seed(42)
import vscodenb
import svgd_tests
sns.set_palette('tab10')
set_log_level('INFO')
clear_caches()
[INFO] phasic.graph_cache: Cleared 0 cached graphs
  Removed 3 file(s), preserved directory structure
nr_samples = 4

@with_ipv([nr_samples]+[0]*(nr_samples-1))
def coalescent_1param(state):
    transitions = []
    for i in range(state.size):
        for j in range(i, state.size):            
            same = int(i == j)
            if same and state[i] < 2:
                continue
            if not same and (state[i] < 1 or state[j] < 1):
                continue 
            new = state.copy()
            new[i] -= 1
            new[j] -= 1
            new[i+j+1] += 1
            transitions.append([new, [state[i]*(state[j]-same)/(1+same)]])
    return transitions

true_theta = [7]
graph = Graph(coalescent_1param)
graph.update_weights(true_theta)
graph.plot()
[INFO] phasic.graph_cache: Saved graph to cache: 4e7d3baaa4030c3c... (6 vertices)
[INFO] phasic: Saved graph to cache: 6 vertices

observed_data = graph.sample(10000)
observed_data.shape
(10000,)
fig, ax = plt.subplots()
ax.hist(observed_data, density=True, bins=50, label='Sampled data')
x = np.linspace(0, observed_data.max(), 100)
ax.plot(x, graph.pdf(x), color='C1', label='Unit reward PDF')
ax.legend() ;

svgd = graph.svgd(observed_data=observed_data, 
                  prior=GaussPrior(ci=[5, 20]),
                  optimizer=Adam(learning_rate=0.2),
                  n_iterations=200,
                  n_particles=100,
                  )
svgd.summary()
Parameter  Fixed          MAP        Mean       SD         HPD 95% lo   HPD 95% hi  
0          No             7.03       7.054      0.1454     6.722        7.356       

Particles: 100, Iterations: 200
svgd.plot_convergence()

svgd.plot_ci(true_theta=true_theta)

svgd.plot_trace() ;

Rewards

We can fit to reward transformed observations, like the total branch length of the coalescent. In the example below, we sample total branch lengths from the model and pass them to svgd along with the appropriate rewards.

# def log_likelihood(graph, theta, data, rewards=None):
#     graph.update_weights(list(theta))
#     g = graph.reward_transform(rewards) if rewards is not None else graph
#     p = np.array([g.pdf(float(t)) for t in data])
#     return float(np.sum(np.log(np.clip(p, 1e-300, None))))

# base = log_likelihood(graph, true_theta, data, rewards)
# assert np.isfinite(base), "log-likelihood at the true parameters is not finite"
# for i in range(len(true_theta)):
#     pert = 0.1
#     for p in [-pert, pert]:
#         th = list(true_theta)
#         th[i] = th[i] * (1 + p)
#         alt = log_likelihood(graph, th, data, rewards)
#         assert alt < base


# # import matplotlib.pyplot as plt
# # values = np.linspace(4, 10, 50)
# # ll = [log_likelihood(graph, [x], data, rewards) for x in values]
# # print(ll)
# # plt.plot(x, ll)
graph = Graph(coalescent_1param)
true_theta = [7]
graph.update_weights(true_theta)

rewards = graph.states().T[:-1]
rewards = np.sum(rewards, axis=0)
rewards
[INFO] phasic.graph_cache: Saved graph to cache: 4e7d3baaa4030c3c... (6 vertices)
[INFO] phasic: Saved graph to cache: 6 vertices
array([0, 4, 3, 2, 2, 0])
observed_data = graph.sample(10000, rewards=rewards)
observed_data.shape
(10000,)
fig, ax = plt.subplots()
ax.hist(observed_data, density=True, bins=50, label='Sampled data')
x = np.linspace(0, observed_data.max(), 100)
ax.plot(x, graph.reward_transform(rewards).pdf(x), color='C1', label='Rev. trans. PDF')
ax.plot(x, graph.pdf(x), color='C1', ls='--', label='Unit reward PDF')
ax.legend() ;

svgd = graph.svgd(observed_data=observed_data,
                  rewards=rewards,
                  prior=GaussPrior(ci=[5, 20]),
                  optimizer=Adam(learning_rate=0.3),
                  n_iterations=200,
                  n_particles=100,
                  )
svgd.summary()
Parameter  Fixed          MAP        Mean       SD         HPD 95% lo   HPD 95% hi  
0          No             6.98       6.991      0.08644    6.871        7.135       

Particles: 100, Iterations: 200
svgd.plot_convergence()

svgd.plot_ci(true_theta=true_theta)

svgd.plot_trace() ;

svgd.plot_posterior(bins=100)

Multi-feature observations

Observations can be vectors of features.

With more than one feature, SVGD computes the likelihood for each feature using the the provided rewards. In this example, sample 1’ton, 2’ton, and 3’ton branch lengths are first, second and third observation features. The reward matrix passed to svgd must have as many rows as your data has features. Three rows in the reward matrix:

Reward-vector validity:

Graph.svgd enforces two structural conditions on every feature:

  1. No absorbing-vertex rewards. Absorbing vertices have zero sojourn time, so rewarding them carries no information about theta. Graph.svgd raises ValueError with a list of offending vertices. For graph.states().T, the last row indexes the absorbing state — drop it with [:-1].

  2. Partial coverage is auto-handled. When some absorbing trajectories never visit any vertex with reward > 0 in a feature, that feature’s reward distribution has a point mass at zero. Graph.svgd detects this and switches to a zero-inflated likelihood: n_zero · log(1 − p(θ)) + Σ log(pdf(r)), where p(θ) = P(visit a rewarded vertex). You see a one-time UserWarning naming the offending features.

To opt out of either check, pass validate_rewards=False.

graph = Graph(coalescent_1param)
graph.update_weights(true_theta)

# `graph.states().T` is the (n_features, n_vertices) reward matrix:
# each ROW is one feature's reward vector. The LAST row indexes the
# absorbing state — absorbing vertices have zero sojourn time, so
# rewarding them produces an identically-zero sample that carries no
# information about theta. Drop that row with `[:-1]`; `Graph.svgd`
# raises with a clear error if you forget.
#
# Among the remaining three rows, "feature 2" = `[0,0,0,0,1,0]`
# rewards only state 4, which some trajectories never visit. The
# resulting reward distribution has a point mass at zero;
# `Graph.svgd` handles this *partial coverage* automatically with a
# zero-inflated likelihood and emits a one-time UserWarning.

rewards = graph.states().T[:-1]
rewards
[INFO] phasic.graph_cache: Cache hit: 4e7d3baaa4030c3c... (6 vertices)
[INFO] phasic: Loaded graph from cache: 6 vertices
array([[0, 4, 2, 0, 1, 0],
       [0, 0, 1, 2, 0, 0],
       [0, 0, 0, 0, 1, 0]], dtype=int32)

Data must be passed to svgd as a SparseData object. You can create it by specifying features and feature_slices like this:

n_obs = 10000

idxs = np.arange(rewards.shape[0])
feature_data = np.concatenate([graph.sample(n_obs, rewards=rewards[i]) for i in idxs])
features = np.concatenate([[i]*n_obs for i in idxs])
feature_slices = [(i*n_obs, (i+1)*n_obs) for i in idxs]

sparse_observations = SparseObservations(
    values=observed_data,
    features=features,
    n_features=3, 
    slices=feature_slices
)
sparse_observations
SparseObservations(values=<10000 values>, n_features=<3, features=<10000 values>, slices=<10000 values>)

Or by craeting a two-dimensional array where each row is an observation with all but a single non-nan value and then converting that to SparseObservations using dense_to_sparse:

n_obs = 10000

observed_data = np.zeros((n_obs * (rewards.shape[0]), rewards.shape[0]), dtype=float)
observed_data[:] = np.nan
for i in range(rewards.shape[0]):
    observed_data[(i*n_obs):((i+1)*n_obs), i] = graph.sample(n_obs, rewards=rewards[i])
np.random.shuffle(observed_data)

observed_data
array([[0.30998551,        nan,        nan],
       [       nan,        nan, 0.        ],
       [       nan,        nan, 0.        ],
       ...,
       [       nan,        nan, 0.07074932],
       [       nan,        nan, 0.0824024 ],
       [0.2540951 ,        nan,        nan]], shape=(30000, 3))
sparse_observations = dense_to_sparse(observed_data)
sparse_observations
SparseObservations(values=<30000 values>, n_features=<3, features=<30000 values>, slices=<30000 values>)
svgd = graph.svgd(observed_data=sparse_observations,
                  rewards=rewards,
                  prior=GaussPrior(ci=[5, 20]),
                  optimizer=Adam(learning_rate=0.3),
                  n_iterations=200,
                  n_particles=100,
                  )
svgd.summary()
Parameter  Fixed          MAP        Mean       SD         HPD 95% lo   HPD 95% hi  
0          No             6.998      6.994      0.08827    6.751        7.106       

Particles: 100, Iterations: 200
Zero-inflated likelihood: feature 2 (n_zero = 3375)

svgd.plot_convergence() ;

svgd.plot_trace()

svgd.plot_ci()