Angad Sandhu
Search
Browse

CustomWithActivation

Open In Colab

try:
  # %tensorflow_version only exists in Colab.
  %tensorflow_version 2.x
except Exception:
  pass
import tensorflow as tf
from tensorflow.keras.layers import Layer

class SimpleDense(Layer):

  def __init__(self, units=32, activation=None):
      super(SimpleDense, self).__init__()
      self.units = units
      self.activation = tf.keras.activations.get(activation)


  def build(self, input_shape):  # Create the state of the layer (weights)
    w_init = tf.random_normal_initializer()
    self.w = tf.Variable(name="kernel",
        initial_value=w_init(shape=(input_shape[-1], self.units),
                             dtype='float32'),
        trainable=True)
    b_init = tf.zeros_initializer()
    self.b = tf.Variable(name="bias",
        initial_value=b_init(shape=(self.units,), dtype='float32'),
        trainable=True)
    super().build(input_shape)


  def call(self, inputs):  # Defines the computation from inputs to outputs
      return self.activation(tf.matmul(inputs, self.w) + self.b)


import tensorflow as tf
mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  SimpleDense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)

Browse the library