Cannot access weights and biases within the class for further operation

Viewed 26

I am new to tensorflow. Can someone please help in this matter. I am making a class of keras nn. Now I want to extract weights/biases of each layer (for further processing). Now as there is no build(input_shape) for instance of this model, the current weights.layers of conv2d/dense layers is empty.

After creating instance of model 1, i.e., net_1 = model_1(), it requires to be build and build command wants an input shape. What I want is that before build command, is there any way to provide the input shape to model_1 ? Is there any way besides "build" that model_1 gets the input shape? class model

class model_1(tf.keras.Model):
    def __init__(self):
        super().__init__()
        
        self.conv1 = tf.keras.layers.Conv2D(filters=6, kernel_size=[5, 5],activation=tf.nn.relu, use_bias=True, bias_initializer =tf.initializers.lecun_normal(seed=137)) 
        self.pool1 = tf.keras.layers.MaxPool2D(pool_size=[2, 2], strides=2)
        self.conv2 = tf.keras.layers.Conv2D(filters=3, kernel_size=[5, 5],activation=tf.nn.relu, use_bias = True, bias_initializer=tf.initializers.lecun_normal(seed=137))
        self.pool2 = tf.keras.layers.MaxPool2D(pool_size=[2, 2], strides=2)
        self.flatten = tf.keras.layers.Reshape(target_shape=(4 * 4 * 3,))
        self.dense1 = tf.keras.layers.Dense(units=50, activation=tf.nn.relu, use_bias=True, bias_initializer=tf.initializers.lecun_normal(seed=137))
        self.dense2 = tf.keras.layers.Dense(units=10, use_bias=True, bias_initializer=tf.initializers.lecun_normal(seed=137))



    def call(self, inputs):
        x = self.conv1(inputs)                  # [batch_size, 28, 28, 32]
        x = self.pool1(x)                       # [batch_size, 14, 14, 32]
        x = self.conv2(x)                       # [batch_size, 14, 14, 64]
        x = self.pool2(x)                       # [batch_size, 7, 7, 64]
        x = self.flatten(x)                     # [batch_size, 7 * 7 * 64]
        x = self.dense1(x)                      # [batch_size, 1024]
        x = self.dense2(x)                      # [batch_size, 10]
        output = tf.nn.softmax(x)
        return output
        
        
        net_1 = model_1()
        
        net_1.build(input_shape)             ## input shape is (none,28,28,1)

0 Answers
Related