I fond the following code in (https://www.tensorflow.org/tutorials/eager/custom_layers)
class MyDenseLayer(tf.keras.layers.Layer):
def __init__(self, num_outputs):
super(MyDenseLayer, self).__init__()
self.num_outputs = num_outputs
def build(self, input_shape):
self.kernel = self.add_variable("kernel",
shape=[int(input_shape[-1]),
self.num_outputs])
def call(self, input):
return tf.matmul(input, self.kernel)
The last two lines is call method, while it does not like usual python class method call with two underlines. Is any differences between those?
The call function gets run twice at the beginning of training through the first epoch and then gets run almost at the end of the first epoch. It is never run after that.
Sequential class : Sequential groups a linear stack of layers into a tf. keras. Model . Model class : Model group's layers into an object with training and inference features.
The first important takeaway is that deep learning practitioners using the keras package should start using tf. keras inside TensorFlow 2.0. Not only will you enjoy the added speed and optimization of TensorFlow 2.0, but you'll also receive new feature updates — the latest release of the keras package (v2.
The core idea of Sequential API is simply arranging the Keras layers in a sequential order and so, it is called Sequential API. Most of the ANN also has layers in sequential order and the data flows from one layer to another layer in the given order until the data finally reaches the output layer.
The following answer is based on https://tf.wiki/zh/basic/models.html.
Basically in Python, when you call an instance from class ClassA
using ClassA()
, it is equivalent to ClassA.__call__()
. So it seems reasonable to use __call__()
instead of call()
in this case, right?
However, the reason we use call()
is that when tf.keras
calls a model or a layer, it has its own inner operations which are essential to keep its inner structure. As a result, it exposes a method call()
for customer overloading. __call()__
calls call()
as well as some inner operations, so when we reload call()
inheriting from tf.keras.Model
or tf.keras.Layer
, we can call our custom code while keeping tf.keras
's inner structure.
For example, from my experience, if your input is a numpy array instead of a tensor, you don't need to transform it manually if you write customer code in call()
but if you overwrite __call__()
, it would be a problem since some inner operations are not called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With