Mina Gabriel
Mina Gabriel

Reputation: 25140

tf.keras.layers.Conv2D get kernel values

How do I get the Kernel values from tf.keras.layers.Conv2D?

Here is my code:

#input image is 5 X 5 and 1 channel 
input_shape = (1, 1, 5, 5)

x = tf.random.normal(input_shape) 

y = tf.keras.layers.Conv2D( 
   2, 2, activation= tf.nn.relu, input_shape=input_shape, 
   data_format='channels_first')(x) 

I am using tf version 2.2

I have tried y.get_weights() and this didn't work I got:

AttributeError: 'tensorflow.python.framework.ops.EagerTensor' 
object has no attribute 'get_weights'

Upvotes: 0

Views: 1581

Answers (1)

xdurch0
xdurch0

Reputation: 10474

You need to actually store the layer in a variable. In your code, y is the result of the convolution. For example

input_shape = (1, 1, 5, 5)

x = tf.random.normal(input_shape) 

conv_layer = tf.keras.layers.Conv2D( 
   2, 2, activation= tf.nn.relu, input_shape=input_shape, 
   data_format='channels_first')
y = conv_layer(x)

Now you should be able to use conv_layer.get_weights().

Upvotes: 3

Related Questions