I'm trying to achieve optimization using a substitution model instead of the actual function and for that I need the gradient of my LSTM model compared to the input. In this case, I have 3 features that vary over time. The LSTM calculates from the initial value of these 3 characteristics the following 100 time steps, the jacobian matrix thus having the form 100x3x3. It turns out that my code to evaluate the gradient is slower (235 seconds per iteration) than the code that computes the gradient function (18 seconds per iteration). Could you help me speed up the gradient assessment so that I can perform an optimization using the evaluation function? I will be happy to provide the data and the complete code if necessary. The codes for both functions are below:

```
def get_grad_func(model,n_feat,n_output):
grad_func1=()
grad_func2=()
grad_func3=()
grad_func=()
for i in range(n_output):
start_time = datetime.datetime.now()
print('Calculating dx'+str(i+1)+'/dx0')
grad_func1.append(tf.gradients(model.output(:,i,0), model.input))
grad_func2.append(tf.gradients(model.output(:,i,1), model.input))
grad_func3.append(tf.gradients(model.output(:,i,2), model.input))
end_time = datetime.datetime.now()
diff = (end_time - start_time).total_seconds()
print(diff)
grad_func1= tf.reshape(grad_func1,(n_output,1,n_feat))
output1=tf.stack(grad_func1)
grad_func2= tf.reshape(grad_func2,(n_output,1,n_feat))
output2=tf.stack(grad_func2)
grad_func3= tf.reshape(grad_func3,(n_output,1,n_feat))
output3=tf.stack(grad_func3)
grad_func.append(output1)
grad_func.append(output2)
grad_func.append(output3)
return grad_func
def eval_grad(model,x0,n_feat,n_output,sess,grad_func):
jacobian_matrix = ()
for i in range(n_output):
print('Calculating dx'+str(i+1)+'/dx0')
start_time = datetime.datetime.now()
for n in range(n_feat):
for m in range(n_feat):
gradients = sess.run(grad_func(n)(i,:,m), feed_dict={model.input: x0})
jacobian_matrix.append(gradients)
end_time = datetime.datetime.now()
diff = (end_time - start_time).total_seconds()
print("time")
print(diff)
J_matrix=zeros((n_output,n_feat,n_feat))
count=0
for i in range(n_output):
for j in range(n_feat):
J_matrix(i,j,:)=jacobian_matrix(count:count+n_feat)
count=count+n_feat
return J_matrix
```