Skip to content

Instantly share code, notes, and snippets.

@ckrapu
Created April 23, 2021 16:28
Show Gist options
  • Save ckrapu/60d79b53ab2070648d1ebfccb3e27159 to your computer and use it in GitHub Desktop.
Save ckrapu/60d79b53ab2070648d1ebfccb3e27159 to your computer and use it in GitHub Desktop.
fa-xr-ufunc
Y = xr.DataArray(Y_raw, dims=('observed_columns','rows'))
Y = Y.assign_coords({'observed_columns':np.arange(d),'rows':np.arange(n)})
def post_hoc_fun(W, psi, Y, rng=None):
'''
Recovers latent variables given observation Y and single draw of W, psi
from the posterior distribution.
'''
k, d = W.shape[-2:]
_, n = Y.shape
WW = np.linalg.inv(np.einsum("...ji,...jk", W, W))
WW_Wt = np.einsum("...ij,...kj", WW, W)
F_mu = np.einsum("...ij,...jk", 1 / np.sqrt(psi) * WW_Wt, Y)
WW_chol = np.linalg.cholesky(WW)
return F_mu + np.einsum("...ij,...jk", WW_chol, rng.standard_normal(size=(k, n)))
xr.apply_ufunc(
post_hoc_fun,
trace.posterior['W'],
trace.posterior['psi'],
Y,
input_core_dims=[['observed_columns', 'latent_columns'],
[],
["observed_columns","rows"]],
output_core_dims=[["latent_columns", "rows"]],
kwargs={"rng": rng}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment