Search code examples
pythonneural-networkkeraskeras-layerkeras-2

When is Layer.build() invoked in source code in keras?


Every derived class of Layer class in keras has build() definition.

build() is place where we assign weights to the keras layer.

When is this function invoked internally? I am unable to find any piece of code which may be callling it

In __call_() of Layer class at topology.py:580, we call self.build() but it will be invoked only when self.built = True. That is always set in self.build() which in turn will be invoked only when self.built is True.


Solution

  • You've missed not in the condition (source code):

    if not self.built:
      ...
      if len(input_shapes) == 1:
        self.build(input_shapes[0])
      else:
        self.build(input_shapes)
    

    ... which basically means "build if not already".

    By the way, build() is also called in count_params() method, again with a guard (source code).