Convolution in pymc3 with numpy and/or theano

Okay i finally managed to do a 1d convolution with the right border mode. For those having problems in the future here is a simple example to show it works

import theano
import theano.tensor as tt
from scipy import signal

xtest=np.linspace(0.1,10,101)
filt=2.0*xtest
conv=signal.convolve(xtest, filt, mode='same')

with pm.Model() as model:

 A = pm.Normal('A', mu=2.0, sigma=1.0)#also works for 
 pm.Uniform('A',lower=0.0,upper=5.0)

 xtestT=np.reshape(xtest,(1,1,101,1))#np.reshape(xtest,(1,1,1,101)) should also work

 filtt = A*xtestT

 convol=theano.tensor.nnet.conv2d(xtestT,filtt,border_mode='half')
 #'half' work the same way as 'same' for odd sized filters. 

 likelihood = pm.Normal('conv', mu=convol[0,0,:,0], observed=conv)

 trace = pm.sample(1000) 

The important thing to remember is how the data is formatted nnet.conv2d wants a 4d tensor, so we have to reshape the input and filter (since the filter is calculated from the input data in this case i only have to do it for the input). The input has the shape (batch size, input channels, input rows, input columns) and the important ones in our case is the last two. The sampling result are similar to the ones above for signal.conv.conv2d but we can now use the ‘half’ border mode! Just remember your filter has to be oddly sized for it to work like the ‘same’ border mode from numpy and scipy.

1 Like