Angad Sandhu
Search
Browse

QuadraticLayer_Question

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 SimpleQuadratic(Layer):
  # Implement a simple quadratic layer, where it has 3 state variables
  # called a, b and c
  # And the computation returned is ax^2 + bx + c
  # Make sure it can accept an activation function also

  def __init__(self, units=32, activation=None):
      # YOUR CODE HERE

  def build(self, input_shape):  # Create the state of the layer (weights)
      # YOUR CODE HERE
      # a and b should be initialized with random normal, c with zeros
   
  def call(self, inputs):  # Defines the computation from inputs to outputs
      # YOUR CODE HERE
# THIS CODE SHOULD RUN WITHOUT MODIFICATION
# AND SHOULD RETURN TRAINING/TESTING ACCURACY at 97%+
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)),
  SimpleQuadratic(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