Here is the performance with the compiled only once func:
import theano
import theano.tensor as tt
import pymc3 as pm
import numpy as np
import matplotlib.pyplot as plt
import time
def my_func(x, θ):
return pm.math.exp(-θ * x)
def compile_my_func():
x = tt.vector()
θ = tt.scalar()
result = my_func(x, θ)
return theano.function([x, θ], result)
# faux posterior samples
n_samples = 1000
θ = np.random.randn(n_samples)
xi = np.linspace(-1, 2, 100)
# how long to evaluate the function 100 times? ----------------------
start = time.time()
for i in np.random.choice(n_samples, 100, replace=False):
my_func(xi, θ[i]).eval()
end = time.time()
print(end - start) # 5 seconds on Colab
# how long to evaluate the function 100 times? ----------------------
start = time.time()
my_func_compiled = compile_my_func()
for i in np.random.choice(n_samples, 100, replace=False):
my_func_compiled(xi, θ[i])
end = time.time()
print(end - start) # 0.03 seconds on Colab