I have a piece of code which performs geometric ad stock decay using Theano. It is a old piece of code and I need to update it using the latest version of PyTensor. Can someone please help me convert this?
def adstock_geometric_theano_pymc3(x, theta):
x = tt.as_tensor_variable(x)
def adstock_geometric_recurrence_theano(index,
input_x,
decay_x,
theta):
return tt.set_subtensor(decay_x[index],
tt.sum(input_x + theta * decay_x[index - 1]))
len_observed = x.shape[0]
x_decayed = tt.zeros_like(x)
x_decayed = tt.set_subtensor(x_decayed[0], x[0])
output, _ = theano.scan(
fn = adstock_geometric_recurrence_theano,
sequences = [tt.arange(1, len_observed), x[1:len_observed]],
outputs_info = x_decayed,
non_sequences = theta,
n_steps = len_observed - 1
)
return output[-1]
so first i'll share the converted code and then explain how and why everything works:
Original Code Issues
Your original Theano code uses
theano.scan, a powerful tool for looping over sequences in a way optimized for parallel computation. This is a common approach inTheanofor handling recursive operations efficiently. However, when switching toPyTorch(PyTensor), there isn't a direct equivalent oftheano.scan. PyTorch tends to favor explicit loops in Python, which are less optimized but more straightforward.Modified Code Explanation
In the modified
PyTorchcode, I replaced thetheano.scanwith a standard Python for-loop. This loop iteratively applies the adstock transformation. This change sacrifices some computational efficiency but maintains the core functionality.