Code
tensorflow
import tensorflow as tf
# Sequential for linear stacks
seq_model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation="relu", input_shape=(784,)),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation="softmax"),
])
# Functional API for flexible topology
inputs = tf.keras.Input(shape=(784,))
x = tf.keras.layers.Dense(128, activation="relu")(inputs)
x = tf.keras.layers.Dropout(0.2)(x)
outputs = tf.keras.layers.Dense(10, activation="softmax")(x)
func_model = tf.keras.Model(inputs, outputs, name="mlp")
# Subclassing for full control
class MLP(tf.keras.Model):
def __init__(self):
super().__init__()
self.d1 = tf.keras.layers.Dense(128, activation="relu")
self.drop = tf.keras.layers.Dropout(0.2)
self.d2 = tf.keras.layers.Dense(10, activation="softmax")
def call(self, x, training=False):
x = self.d1(x)
x = self.drop(x, training=training)
return self.d2(x)
subclass_model = MLP()
subclass_model.build((None, 784))