Bastech
Bastech

Reputation: 3

Issues creating custom keras layer

I am trying to create a custom keras layer to do a particular task

I have input of shape=(batch_size, M, N, p) I want my output to be of shape=(batch_size, M, N, f)

So, I set up a trainable conv_weight of shape=(M, N, p, f)

Below is my code

class convLayer(Layer):
    """
    Self defined convolutional layer
    """
    def __init__(self, filter_no, **kwargs):
        self.filter_no = filter_no

        super(convLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        self.conv_weights = self.add_weight(name='weight',
                                      shape=(input_shape[1], input_shape[2], 
                                             input_shape[3], self.filter_no),
                                      initializer='uniform',
                                      trainable=True)

        super(convLayer, self).build(input_shape)

    def call(self, inputs):
        outputs = K.placeholder(shape=(inputs.shape[0], inputs.shape[1], 
                                 inputs.shape[2], self.filter_no), 
                                 dtype=tf.float32)
        for i in range(self.filter_no):
            weight = self.conv_weights[:,:,:, i]
            val = tf.math.multiply(inputs, weight)
            for j in range(val.shape[3]):
                if i==0:
                    outputs[:,:,:,i].assign(val[:,:,:,j])
                else:        
                    outputs[:,:,:,i].assign(tf.math.add(outputs[:,:,:,i], val[:,:,:,j]))

        return outputs

    def compute_output_shape(self, input_shape):
        return (input_shape[0], input_shape[1], input_shape[2], self.filter_no)

My output should be of shape=(batch_size, M, N, f) for each f, all elements of axis p in both input and conv_weight should be multiplied and summed together.

I have been trying and getting several errors. I am relatively new to creating custom layers. Kindly help. Thank you.

Error Message: Sliced assignment is only supported for variables.

Upvotes: 0

Views: 126

Answers (1)

Safvan CK
Safvan CK

Reputation: 1340

You cannot assign to tensors, because they are immutable. What you can do is create a new tensor with copied from another with some values replaced.You can try like this.

Upvotes: 2

Related Questions