How to access kernel weights in Conv2D?

output = Conv2D(filters=3, kernel_size=3, padding='same')(input)

and i want something like Conv2D(filters=3, kernel_size=3, padding='same', weights=my_tensor_of_kernel_weights)(input)

how can I set weights and print current weights?

.get_weights() and .set_weights() methods can be applied to any layer. Here is the documentation: The base Layer class

2 Likes

I tried this, but I’m not sure what I’m doing wrong (?) but I receive this error when trying to set weights:

ValueError: You called set_weights(weights) on layer “conv2d” with a weight list of length 9, but the layer was expecting 0 weights. Provided weights: [0.1111111111111111, 0.1111111111111111, 0.1111111…

I’m setting weights like this:

from tensorflow.keras.layers import Conv2D
import tensorflow as tf

output = Conv2D(filters=3, kernel_size=3, padding='same')
weights = output.get_weights()
print(weights) # []
output.set_weights([1/9]*9)
print(weights)

I would like to add weight of 1/9 for each cell of kernel

Apparently, you have to pass some data through the layer to be able to get or set weights. I took the example from Keras (Conv2D layer) and got this result:

input_shape = (4, 28, 28, 3)

# Without passing data through the layer
l = tf.keras.layers.Conv2D(input_shape=input_shape[1:], filters=3, kernel_size=3, padding='same')
print(l.get_weights())  # Empty list

# After passing data through the layer
x = tf.random.normal(input_shape)
l = tf.keras.layers.Conv2D(input_shape=input_shape[1:], filters=3, kernel_size=3, padding='same')
y = l(x)
weights = l.get_weights()
print(weights)  # List containing 2 numpy arrays
print(weights[0].shape)
print(weights[1].shape)