1

Can I use keras.Layers to build custom layer to mask to whole dataset and return masked dataset. That is

class AttnMask(Layer):
    def __init__(self, img_size, attention_map):
        super().__init__()

        self.imgSize = img_size
        self.attentionMap = attention_map

    def call(self, x, *args, **kwargs):
        return tf.math.multiply(x, self.attentionMap)

And to call the function

attenMaskLayer = attention_mask.AttnMask(img_size, attention_map)
maskedDataset = attenMaskLayer(dataset)

the dataset is retrieve from the directory hierarchy via tf.keras.preprocessing.image.ImageDataGenerator() and train_datagen.flow_from_directory() method.

Now it will return error ValueError: Only input tensors may be passed as positional arguments. The following argument value should be passed as a keyword argument: <keras.src.legacy.preprocessing.image.DirectoryIterator object at 0x00000169F47DF500> (of type <class 'keras.src.legacy.preprocessing.image.DirectoryIterator'>)

1

1 Answer 1

0

Yes you can, but the problem is you are passing a python iterator to keras.Layers which only accepts tensors (Error mansions it). what you need to do is to convert your dataset to a tensor then pass it to keras.Layers.
to do this you may use convert_to_tensor function from tensorflow. your code would be something like:

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

class AttnMask(Layer):
    def __init__(self, attentionMap):
        super().__init__()
        self.attentionMap = tf.convert_to_tensor(attentionMap, dtype=tf.float32)

    def call(self, x):
        return x * self.attentionMap

if __name__ =="__main__":
inputLayer = tf.keras.Input(shape=(img_size, img_size, 3))
maskedDataset = AttnMask(attentionMap)(inputLayer)
model = tf.keras.Model(inputs=inputLayer, outputs=maskedDataset)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.