我想使用注意力模型来提取注意力分数。但是我找不到任何 TF2 API 可以使用。简单的代码:
import tensorflow as tf
model = train_model()
func = tf.function(model)
tensor_specs1 = tf.TensorSpec.from_tensor(model.input)
call = func.get_concrete_function(tensor_specs1)
graph = call.graph
tensor_names = [n for n in graph.as_graph_def().node]
for name in tensor_names:
print(name)
outputs = graph.get_tensor_by_name('model_1/word_encoder_time/word_attention/Softmax:0')
pred_model = tf.keras.models.Model(model.input,outputs)
results = pred_model(tensor_specs1)
print(results)
但引发异常:
raise ValueError("Tensor %s is not an element of this graph." % obj)
ValueError: Tensor Tensor("model_1/word_encoder_time/model/word_attention/BiasAdd:0", shape=(?, 10), dtype=float32) is not an element of this graph
它正在工作,但这不是我想要的:
outputs = [model.get_layer(name=output).get_output_at(0) for output in output_layers]
pred_model = tf.keras.models.Model(model.input,outputs)
我想获得中间张量,而不是层的输出。