The explanation Keras exposes name()
for builders is that we don’t override __call__()
instantly. Overriding __call__()
would bypass the essential inner logic that Keras depends on.
In Keras, the name()
methodology defines how knowledge flows in the course of the ahead move. This determines how the mannequin computes the output from the enter.
Sequential API
After we construct a Keras mannequin utilizing the Sequential API:
mannequin = Sequential([
Dense(32, activation='relu', input_shape=(784,)),
Dense(10, activation='softmax')
])
Keras robotically creates a name()
methodology for us.
Purposeful API
After we construct a Keras mannequin utilizing the Purposeful API:
inputs = Enter(form=(784,))
x = Dense(32, activation='relu')(inputs)
outputs = Dense(10, activation='softmax')(x)
mannequin = Mannequin(inputs=inputs, outputs=outputs)
Keras additionally creates a name()
methodology for us.
Subclassing (Inheritance)
For extra complicated fashions, we are able to subclass Mannequin
:
class MyCustomModel(Mannequin):
def __init__(self):
tremendous().__init__()
self.dense1 = Dense(32, activation='relu')
self.dense2 = Dense(10, activation='softmax')def name(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
We should explicitly implement our personal name()
methodology to outline the ahead move. This strategy is extra versatile than the Sequential or Purposeful API.
Nevertheless, in contrast to the Sequential or Purposeful API, subclassed fashions constructed like this don’t robotically create a computation graph till they see precise knowledge. Therefore, we have to “construct” the graph by passing knowledge via the mannequin as soon as, or by calling the construct()
methodology instantly:
mannequin.construct((None, 64))
This lets Keras monitor the layers internally.