# PyMC3 Model Error When Using Einstein Sum

**URL:** <https://discourse.pymc.io/t/pymc3-model-error-when-using-einstein-sum/8212>\
**Category:** Questions\
**Tags:** theano\
**Created:** [October 24, 2021, 11:18am UTC](https://discourse.pymc.io/t/pymc3-model-error-when-using-einstein-sum/8212 "2021-10-24T11:18:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![michnag](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/michnag/32/3376_2.png) [@michnag](https://discourse.pymc.io/u/michnag)\
**Post date:** [October 24, 2021, 11:18am UTC](https://discourse.pymc.io/t/pymc3-model-error-when-using-einstein-sum/8212/1 "2021-10-24T11:18:50Z")

</div>

I have the following model, where X is NxTxK and y is TxN:

```auto
with pm.Model() as model:
    gamma= pm.Normal("gamma", mu=0, sigma=100, shape=())
    beta= pm.Normal("beta", mu=0, sigma=100, shape=(X.shape[2], 1))
    u= pm.Normal("u", mu=0, sigma=1, shape=(1, X.shape[0]))
    r = pm.Gamma("r", alpha=9, beta=4, shape=())

    y_hat = gamma + np.einsum("jik,kl->ij", X, beta) + u

    y_like = pm.Normal("y_like", mu=y_hat, sigma=r, observed=y)

```

However, when I run the model, I get the following error

ValueError: einstein sum subscripts string contains too many subscripts for operand 1

If I do the calculation `np.einsum("jik,kl->ij", X, beta)` outside the pm.Model() environment, it works as expected so it seems that np.einsum does not work in the wrapper function.

---

<div class="post-metadata">

**Author:** ![ccaprani](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/ccaprani/32/3224_2.png) [@ccaprani](https://discourse.pymc.io/u/ccaprani)\
**Post date:** [October 25, 2021, 5:30am UTC](https://discourse.pymc.io/t/pymc3-model-error-when-using-einstein-sum/8212/2 "2021-10-25T05:30:33Z")

</div>

In

```python
y_hat = gamma + np.einsum("jik,kl->ij", X, beta) + u

```

`gamma` and `u` are pymc distribution objects but `np.einsum` will return an ndarray. So to make `y_hat` an object in the `pm.Model()` context you should use

```python
y_hat = pm.Deterministic("y_hat", gamma + np.einsum("jik,kl->ij", X, beta) + u)

```

However, if this doesn’t work (I haven’t checked), you may need to use a tensor algebra for the `np.einsum` calculation, such as [this example](https://stackoverflow.com/questions/34005271/theano-version-of-a-numpy-einsum-for-two-3dim-matrices).
