# Looping through random variables

**URL:** <https://discourse.pymc.io/t/looping-through-random-variables/2555>\
**Category:** Questions\
**Created:** [January 20, 2019, 8:59am UTC](https://discourse.pymc.io/t/looping-through-random-variables/2555 "2019-01-20T08:59:50Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![junpenglao](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/junpenglao/32/8_2.png) [@junpenglao](https://discourse.pymc.io/u/junpenglao)\
**Post date:** [January 21, 2019, 10:38am UTC](https://discourse.pymc.io/t/looping-through-random-variables/2555/6 "2019-01-21T10:38:57Z")

</div>

In your model you have a latent discrete variable, which is why sampling needs a `BinaryGibbsMetropolis`. In general, discrete latent variable are very difficult to inference, the general recommendation is that to treat it as a mixture model problem and rewrite it into a marginalized mixture model.

I think this post is the closest to your problem that you can start with:

> [@Problem with hierachical occupancy model](https://discourse.pymc.io/t/problem-with-hierachical-occupancy-model/1702/6):
>
> I would do it this way: First reshape everything so within the pm.Model we are not dealing with dict: index = [] W\_r = [] y\_r = [] for i in range(n): index.append(np.ones((W[i].shape[0], 1))\*i) W\_r.append(W[i]) y\_r.append(y[i][:, np.newaxis]) index = np.concatenate(index, axis=0).astype(int64) W\_r = np.concatenate(W\_r, axis=0) y\_r = np.concatenate(y\_r, axis=0) Then I will use matrix multiplication instead of nested for loops: with pm.Model() as m: beta = pm.Normal('beta', mu=…

See also:

> [@Naive Bayes model with PyMC3](https://discourse.pymc.io/t/naive-bayes-model-with-pymc3/2314/10):
>
> So here is how I would approach it: First, I would rewrite the explicit model, so that the observed is a flatten array - it is easier to handle shape wise: # flatten and index data data\_flatten = np.reshape(data, data.shape[0]\*data.shape[1]) data\_index = np.repeat(np.arange(data.shape[0]), data.shape[1]) with pm.Model() as model: # Global topic distribution theta = pm.Dirichlet("theta", a=alpha) # Word distributions for K topics phi = pm.Dirichlet("phi", a=beta, shape=(K,…

It provides a way to marginalizing the latent discrete variables.

---

_[View the full topic](https://discourse.pymc.io/t/looping-through-random-variables/2555)._
