'What do parentheses do when used after a variable in Python?
This question might be stupid but I don't know Python well enough to know what's going on. So I was trying to learn TensorFlow and noticed this weird invocation:
model = Sequential(
# ...
)
predictions = model(x_train[:1]).numpy()
Can someone please explain what model(x_train[:1])
is doing here? From what I can tell, model is an object that's already constructed above? Is this using the object as a method/function? Or is something else going on here?
Solution 1:[1]
In this case the Tensorflow authors have provided an implementation for the __call__
"magic method" in the tf.keras.Sequential
class hierarchy.
This allows you to invoke the instance of the object as-if it were a function. The call to model = Sequential(...)
initialises the class itself via the __init__
constructor. The model()
calls into the __call__
magic method.
Tensorflow and torch use this as convenience wrapper for a forward pass through the network (in most cases).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Grantus |