简体   繁体   English

从 Keras 层获取权重

[英]Get Weights from Keras Layer

I am trying to obtain the weights from the following Dense layer:我正在尝试从以下Dense层获取权重:

x = Dense(1024)(Flatten()(previous_layer))

If I try to do the following:如果我尝试执行以下操作:

x = Dense(1024)
weights = x.get_weights()

this works fine, but my understanding is that these weights will be useless, as we have not supplied any input to the layer.这工作正常,但我的理解是这些权重将无用,因为我们没有向层提供任何输入。

However, if I try to do the following:但是,如果我尝试执行以下操作:

x = Dense(1024)(Flatten()(previous_layer))
weights = x.get_weights()

this doesn't work, as x is now a Tensor object and does not have the get_weights method:这不起作用,因为x现在是Tensor对象并且没有get_weights方法:

'Tensor' object has no attribute 'get_weights'

What am I doing wrong?我究竟做错了什么?

There's a difference between the layer ( Dense(n) ) and the output tensor you get when applying this layer to some input tensor ( Dense(n)(input) ).层 ( Dense(n) ) 与将此层应用于某个输入张量 ( Dense(n)(input) ) 时获得的输出张量之间存在差异。 You need to store the layer in a variable, not just the output tensor:您需要将图层存储在变量中,而不仅仅是输出张量:

>>> import keras
>>> input_layer = keras.layers.Input((2,))
>>> layer = keras.layers.Dense(3) # create a layer
>>> print(layer)
<keras.layers.core.Dense object at 0x7f03ca9d4d68>
>>> print(layer.get_weights()) # the layer does not have weights yet
[]
>>> output_tensor = layer(input_layer) # apply the layer to the input tensor
>>> print(output_tensor)
Tensor("dense_1/BiasAdd:0", shape=(?, 3), dtype=float32)
>>> print(layer.get_weights()) # now get the weights
[array([[-0.84973848, -0.19682372, -0.14602524],
       [ 0.70318353, -0.1578933 , -0.94751853]], dtype=float32),
 array([ 0.,  0.,  0.], dtype=float32)]
lstm_output = keras.layers.LSTM(100,return_sequences = True)(x_5)

output_location_final = Dense(2,activation='tanh')

#lstm_output is a tensor

result = output_location_final(lstm_output)

#result is a layer

weight = output_location_final.get_weights()

print(weight)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM