PIXELBANKv9.1.0
Menu

Custom Polynomial Activation Function

Problem Statement

Create a custom autograd function that implements a polynomial activation: f(x) = x² + 2x + 1.

Background

Sometimes you need activation functions not available in PyTorch. By subclassing torch.autograd.Function, you can define both the forward computation and its derivative for backpropagation.

Your Task

The starter code defines a PolyActivation class and test harness. Implement the forward method to compute f(x) = x² + 2x + 1, and the backward method to compute the correct derivative. Think about what the derivative of this polynomial is.

Output Format

The function returns a dictionary with "output" (activation values) and "grad" (input gradients).

Example:

Input:
None
Output:
{'output': [4.0, 9.0, 16.0, 0.0], 'grad': [4.0, 6.0, 8.0, 0.0]}
Reasoning:
  • The input values [1.0, 2.0, 3.0, -1.0] are passed through the custom polynomial activation function f(x) = x² + 2x + 1.
  • For each input value, the function calculates the output as x2+2x+1x² + 2x + 1, resulting in [1² + 2*1 + 1, 2² + 2*2 + 1, 3² + 2*3 + 1, (-1)² + 2*(-1) + 1] = [4.0, 9.0, 16.0, 0.0].
  • The .sum().backward() call computes the gradient of the input with respect to the output, using the derivative f′(x)=2x+2f'(x) = 2x + 2, which gives [2*1 + 2, 2*2 + 2, 2*3 + 2, 2*(-1) + 2] = [4.0, 6.0, 8.0, 0.0].
  • The final output is a dictionary containing the output values and the gradient of the input, resulting in {'output': [4.0, 9.0, 16.0, 0.0], 'grad': [4.0, 6.0, 8.0, 0.0]}.

Constraints:

  • Must use torch.autograd.Function
  • Forward: x^2 + 2x + 1
  • Backward: 2x + 2
solution.py

Test Results

0/0
Run code to see test results.
Custom Polynomial Activation Function - Medium | PixelBank