简体   繁体   English

Keras - 获得训练层的重量

[英]Keras - get weight of trained layer

I'm trying to get the values of a layer in a trained network. 我正在尝试在训练有素的网络中获取图层的值。 I can get the layer as a TensorFlow Tensor, but I'm unable to access its values in an array shape: 我可以将图层作为TensorFlow Tensor获取,但我无法以数组形状访问其值:

from keras.models import load_model

model = load_model('./model.h5')
layer_dict = dict([(layer.name, layer) for layer in model.layers])

layer_name = 'block5_sepconv1_act'
filter_index = 0

layer_output = layer_dict['model_1'][layer_name].output
# <tf.Tensor 'block5_sepconv1_act/Relu:0' shape=(?, 16, 16, 728) dtype=float32>
layer_filter = layer_output[:, :, :, filter_index]
# <tf.Tensor 'strided_slice_11:0' shape=(?, 16, 16) dtype=float32>
# how do I get the 16x16 values ??

.get_weights() will return the weights of a specific layer or model as a numpy array .get_weights()将特定图层或模型的权重作为numpy数组返回

layer_dict[layer_name].get_weights()

If you want the output of the layer, check the answers on the question here . 如果您想要图层的输出,请在此处查看问题的答案。

If you use the tensorflow backend, you can evaluate the value of a tensor using the current session sess and feeding the correct input 如果使用tensorflow后端,则可以使用当前会话sess评估张量值并输入正确的输入

import keras.backend as K

input_value = np.zeros(size=(batch_size, input_dim))
sess = K.get_session()
output = sess.run(layer_output, feed_dict={model.input: input_value})

If you just want to retrieve the weights, you can evaluate the weights of a layers using: 如果您只想检索权重,可以使用以下方法评估图层的权重:

weights = [w.eval(K.get_session) for w in layer_dict['model_1'][layer_name].weights]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 初始化经过训练的keras网络的单层并获得预测 - Initialize single layer of a trained keras network and get predictions 如何使用Keras培训的嵌入式层? - How to use a Keras trained Embedded layer? 在 gradcam 的子类 Keras 模型中获取预训练架构的最后一个卷积层的输出 - Get the output of the last convolutional layer of a pre-trained architecture in subclassed Keras model for gradcam Keras功能API,手动将权重设置为图层 - Keras function api, setting weight manually to a layer 向训练有素的 tensorflow keras model 添加重新缩放层(或任何层) - Adding a rescaling layer (or any layer for that matter) to a trained tensorflow keras model 层权重形状 (1, 1) 与为 keras model 提供的权重形状 (1,) 不兼容 - Layer weight shape (1, 1) not compatible with provided weight shape (1,) for keras model Tensorflow Keras 嵌入层错误:层权重形状不兼容 - Tensorflow Keras Embedding Layer Error: Layer weight shape not compatible 在Keras中进行归一化或辍学训练时,如何预测? - How to do predict when trained with Normalization or dropout layer in Keras? 如何在 Keras 中更改预训练 CNN model 中层的 output? - How to change output of a layer in a pre-trained CNN model in Keras? 加载预训练时意外的层数 Keras model - Unexpected layer count when loading pre-trained Keras model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM