在@Abhilash Majumder 的帮助下,我做到了这一点。我将其发布在这里,以便将来可能对某人有所帮助。import numpy as np import pandas as pd import tensorflow as tf tf.compat.v1.enable_eager_execution() #这将启用必须的急切执行。
tf.executing_eagerly() #check if eager execution is enabled or not. Should give "True"
data = pd.read_excel("FileName or Location ")
#My data is in the from of dataframe with 127549 rows and 5 columns(127549*5)
a = data[:20] #shape is (20,5)
b = data[50:70] # shape is (20,5)
A = [a,b] # making a list
A = np.array(A) # convert into array size (2,20,5)
At = tf.convert_to_tensor(A, np.float32) #convert into tensor
At.shape # TensorShape([Dimension(2), Dimension(20), Dimension(5)])
model = load_model('EKF-LSTM-1.h5') # Load the trained model
# I have a trained model which is shown in the question above.
# Output of this model is a single value
with tf.GradientTape(persistent=True,watch_accessed_variables=True) as tape:
tape.watch(At)
y1 = model(At) #defining your output as a function of input variables
print(y1,type(y1)
#output
tf.Tensor([[0.04251503],[0.04634088]], shape=(2, 1), dtype=float32) <class
'tensorflow.python.framework.ops.EagerTensor'>
jacobian=tape.jacobian(y1,At) #jacobian of output w.r.t both inputs
jacobian.shape
输出
TensorShape([Dimension(2), Dimension(1), Dimension(2), Dimension(20), Dimension(5)])
在这里,我计算了 Jacobian wrt 2 个输入,每个输入的大小为 (20,5)。如果你想只计算一个大小为 (20,5) 的输入,那么使用这个
jacobian=tape.jacobian(y1,At[0]) #jacobian of output w.r.t only 1st input in 'At'
jacobian.shape
输出
TensorShape([Dimension(1), Dimension(1), Dimension(1), Dimension(20), Dimension(5)])