小编Mar*_*cin的帖子

在推理过程中从自定义 Tensorflow/Keras 层中提取中间变量 (TF 2.0)

一点背景:

我主要使用 Tensorflow 2.0 的 Keras 功能模型位实现了 NLP 分类模型。模型架构是一个非常简单的 LSTM 网络,在 LSTM 和密集输出层之间添加了一个注意力层。注意层来自这个 Kaggle 内核(从第 51 行开始)。

我将训练好的模型包装在一个简单的 Flask 应用程序中,并获得了相当准确的预测。除了预测特定输入的类别外,我还输出来自上述注意力层的注意力权重向量“a”的值,以便我可以可视化应用于输入序列的权重。

我目前提取注意力权重变量的方法有效,但似乎效率低得令人难以置信,因为我正在预测输出类,然后使用中间 Keras 模型手动计算注意力向量。在 Flask 应用程序中,推理看起来像这样:

# Load the trained model
model = tf.keras.models.load_model('saved_model.h5')

# Extract the trained weights and biases of the trained attention layer
attention_weights = model.get_layer('attention').get_weights()

# Create an intermediate model that outputs the activations of the LSTM layer
intermediate_model = tf.keras.Model(inputs=model.input, outputs=model.get_layer('bi-lstm').output)

# Predict the output class using the trained model
model_score = model.predict(input)

# …
Run Code Online (Sandbox Code Playgroud)

python deep-learning keras tensorflow

5
推荐指数
1
解决办法
811
查看次数

标签 统计

deep-learning ×1

keras ×1

python ×1

tensorflow ×1