Model Subclassing (Part 1)

Learn about subclassing in OOP.

Keras's Sequential API builds models consisting of a sequence of layers arranged one after the other. The Sequential class can’t build models that have layers with multiple input or output tensors. We use the functional API to build such models. Besides the above-mentioned APIs, Keras offers an object-oriented approach, subclassing models, to building DL models. Subclassing represents the DL models as classes and allows model reusability.

Let’s review the concepts of OOP to understand subclassing.

Classes and objects

A class is a prototype defining some common properties or attributes. In OOP terminology, a class is a blueprint to create individual objects with similar behavior.

An object is an instance of a particular class that contains actual values of the class attributes. An object combines variables (data) and methods. Objects can perform operations that we define in a class. An object can have:

  • A unique name that allows it to interact with other objects.

  • A state that’s represented by the values of its attributes.

  • A behavior that’s represented by class methods.

Creating (instantiating) an object from the class gives it a name, state, and behavior. We can create any number of objects from the same class.

The self parameter and __init__ method

In Python, every class method has a parameter self in the method definition. Therefore, if a method doesn’t have any argument, it still has one argument self that represents the instance of the class. The use of the keyword self permits us to access the class methods and attributes.

In Python, the __init__ is a reserved method, also known as the class constructor. An OOP initializes the attributes when we create an object from the class definition. When we instantiate an object, Python calls __init__ to initialize the attribute values. A constructor method contains statements that execute when we instantiate an object.

For instance, we want to create student records. A student can have attributes such as a name, registration number, and grade. A student object can have a method to display the values of its attributes. We illustrate the basic OOP concepts mentioned above by implementing the Student class below.

Get hands-on with 1400+ tech skills courses.