Search code examples
pythonpython-3.xtensorflowkeraspython-module

Meaning and working of a function_f()(variable_v) ( a function followed by variable in () )


I have recently started working with Keras and in their documentation, few lines of codes are shown

inp = Input(shape=(2,))

hl_x = Dense(4, activation='tanh', name= 'First_Hidden_Layer_Following_Input' )(inp)

where

type(Input)

>> function

type(inp)

>>>tensorflow.python.framework.ops.Tensor

Input is a function and inp is a variable of type tensor

What is the meaning of this and how is it working?


Solution

  • Dense(....) returns an object, that can be __called__(), similar to a parametrized function:

    def print_multiple(k):
        """Returns a function that prints 'k' times whatever you give it."""
        return lambda x: print(*(x for _ in range(k)))
    
    print_multiple(6)("Merry")  
    print_multiple(4)("Christmas")  
    

    prints

    Merry Merry Merry Merry Merry Merry
    Christmas Christmas Christmas Christmas 
    

    keras.layers.dense is a callable object - so along the lines of:

    class PrintMult:
        """Object that prints 'how_often' times whatever you give it."""
        def __init__(self, how_often):
            self.how_often = how_often
    
        def __call__(self, what_ever):
            print(*(what_ever for _ in range(self.how_often)))
    
    PrintMult(5)("Yeeha")    # Yeeha Yeeha Yeeha Yeeha Yeeha