0

我有一个训练有素的 LSTM 模型,它有 1 个 LSTM 层和 3 个 Dense 层。我将它用于 One 预测的序列。我有 4 个输入变量和 1 个输出变量。我正在使用最后 20 个时间步的值来预测输出变量的下一个值。该模型的架构如下图所示

model = Sequential()
model.add(LSTM(units = 120, activation ='relu', return_sequences = False,input_shape = 
(train_in.shape[1],5)))
    
model.add(Dense(100,activation='relu'))
model.add(Dense(50,activation='relu'))
model.add(Dense(1))

训练输入和训练输出的形状如下图

train_in.shape , train_out.shape
((89264, 20, 5), (89264,))

我想计算这个模型的雅可比矩阵。说,Y = f(x1,x2,x3,x4) 是上述神经网络的表示 其中: Y -- 训练模型的输出变量, f -- 是表示模型的函数;x1,x2,x3,x4 --输入参数。

如何计算雅可比矩阵?请分享您对此的看法。如果您知道的话,还有任何有价值的参考资料。

谢谢 :)

4

2 回答 2

1

你可能想看看tf.GradientTape张量流。梯度磁带是自动区分计算的非常简单的方法。该链接有一些基本示例。

但是你的模型已经很大了。如果你有n参数,你的雅可比就会有n*n值。我相信您的模型可能已经有超过 10000 个参数。你可能需要把它变小。

于 2021-02-16T09:41:19.830 回答
1

我找到了一种获取 LSTM 模型输出相对于输入的雅可比矩阵的方法。我将其发布在这里,以便将来可能对某人有所帮助。请分享是否有更好或更简单的方法来做同样的事情

import numpy as np
import pandas as pd
import tensorflow as tf
tf.compat.v1.enable_eager_execution() #This will enable eager execution which is must.

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)])
于 2021-02-26T03:04:41.027 回答