AI Logic

Activation Functions

Adaptive Piecewise Linear (APL)

Updated๏ผš

Graph of APL with two examples for S = 1. With a = โˆ’0.2, b = 0, it has a small slope on the negative side; with a = 0.5, b = โˆ’1, the output increases to the left of x = โˆ’1. In both cases, the output is x for x โ‰ฅ 0

What is APL?

APL (Adaptive Piecewise Linear) is an activation function that adds several "hinges" (bends) to ReLU. The position and slope of each bend are learned separately for every neuron. It was proposed so that the network learns a shape that fits the data, instead of a person choosing which activation function to use (Agostinelli et al., 2015).

hi(x)=maxโก(0,โ€‰x)+โˆ‘s=1Saismaxโก(0,โ€‰โˆ’x+bis)h_i(x) = \max(0,\, x) + \sum_{s=1}^{S} a_i^s \max(0,\, -x + b_i^s)
  • ii: index of the neuron (unit)
  • SS: number of hinges, set by hand before training
  • aisa_i^s: slope of each hinge, learned during training
  • bisb_i^s: position of each hinge, learned during training

Each added term maxโก(0,โˆ’x+b)\max(0, -x + b) is 0 when xx is at least bb, and grows as xx decreases below bb. A hinge therefore changes the shape only to the left of its own position. Where xx is large enough, every hinge is 0 and the output equals xx.

With S=1S = 1, the two examples in the graph take the following values.

Input xxโˆ’3โˆ’102
a=โˆ’0.2,ย b=0a = -0.2,\ b = 0โˆ’0.6โˆ’0.202
a=0.5,ย b=โˆ’1a = 0.5,\ b = -11002

The first has the same shape as Leaky ReLU, with a small slope on the negative side. In the second, the output increases to the left of x=โˆ’1x = -1.

Training adds 2S2S parameters per neuron (SS values each of aa and bb). Across the whole network this is 2SM2SM parameters (MM is the total number of hidden units), which the paper describes as small compared with the number of weights in a typical network.

What shapes can it represent?

With a large enough SS, APL can represent many piecewise linear shapes. The paper shows that a continuous piecewise linear function g(x)g(x) can be written in the APL form if it satisfies the following two conditions (Theorem 1).

  1. g(x)=xg(x) = x for all inputs at or above some value uu.
  2. The slope is constant for all inputs below some value vv.

In other words, under the constraint that the right end is a line with slope 1 and the left end is a line with constant slope, the shape in between can be anything.

The constraint that fixes the right-end slope at 1 is weaker than it looks. The output of APL is multiplied by weights and summed in the next layer (wโ‹…g(x)+zw \cdot g(x) + z), so the next layer can adjust the slope and position (as the paper explains).

APL can also represent non-convex shapes with a single unit. Maxout (Goodfellow et al., 2013), which takes the maximum of several linear functions, can only represent convex shapes with one unit. According to the paper, building the same shape as APL with Maxout requires O(SK)O(SK) times as many parameters (KK is the input size of the Maxout layer).

Experimental results

The paper tested the effect of replacing ReLU with APL on image recognition (CIFAR-10 and CIFAR-100) and on particle physics data (classifying Higgs boson decays). Each value in the table is the average of 5 training runs (4 for the Higgs boson data).

SettingMetricReLULeaky ReLUAPL
CIFAR-10, CNN, no data augmentationError rate (lower is better)12.56%11.86%11.38%
CIFAR-100, CNN, no data augmentationError rate37.34%35.82%34.54%
CIFAR-10, Network in Network, with data augmentationError rate7.73%โ€”7.51%
CIFAR-100, Network in Network, with data augmentationError rate32.75%โ€”30.83%
Higgs boson decay classificationAUC (higher is better)0.803โ€”0.804
  • CNN without data augmentation: The error rate dropped by more than 1 point on CIFAR-10 and by about 3 points on CIFAR-100. Leaky ReLU did not reach APL even when the best slope was chosen from several candidates.
  • The effect of learning the shape itself: With S=1S = 1 and the APL shape frozen at its initial values, the error rate was 12.55%, almost the same as ReLU (12.56%). Letting the shape be learned lowered it to 11.59%.
  • Learned shapes: The shapes differed from neuron to neuron and from layer to layer, and some resembled Leaky ReLU. The paper states that this result suggests using the same activation function for every neuron is not necessarily optimal.

Practical notes

Apply an L2 penalty to the slope aa and the position bb: Without a penalty, training drifts toward solutions in which aa becomes very large and the surrounding weights shrink to compensate, which makes the computation unstable. The paper applied an L2 penalty with coefficient 0.001 to aa and bb and reports that results also improved.

  • Choose SS on validation data: The paper selects it per dataset and network (S=5S = 5 for the CIFAR-10 CNN, S=2S = 2 for CIFAR-100, and S=2S = 2 for the Higgs boson data). On CIFAR-10, S=10S = 10 (11.60%) was worse than S=5S = 5 (11.38%), so larger is not always better.
  • More computation and memory: Computation grows with the number of hinges. Parameters are also held per unit, so in convolutional layers, giving every position of the feature map its own parameters makes the parameter count large.
  • No built-in PyTorch implementation: It has to be implemented by hand (see the example below).

Comparison with other activation functions and how to choose

The table below compares APL with other activation functions, some of which learn their shape and some of which do not.

FunctionWhat is learnedShapes one unit can representAdded parameters
ReLUNothingA fixed shape that bends at 0None
Leaky ReLUNothing (the negative-side slope is set by hand)A bent line with a slope on the negative sideNone
PReLUThe negative-side slopeA bent line with a slope on the negative side1 per channel (or similar)
APLPositions and slopes of SS hingesContinuous piecewise linear shapes, including non-convex ones (under conditions)2S2S per unit
MaxoutWeights of several linear functionsConvex piecewise linear shapesGrows with the number of linear functions

Rough guidelines for choosing:

  • Start with ReLU: It is lightweight and accurate enough for many tasks.
  • Try APL to gain accuracy by changing the activation's shape: In the paper, it gave a larger improvement than re-tuning the slope of Leaky ReLU.
  • Try PReLU to avoid adding many parameters: It learns only the negative-side slope, so it adds far fewer parameters.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class APL(nn.Module):
    """Adaptive Piecewise Linear (Agostinelli et al., 2015).

    h_i(x) = max(0, x) + ฮฃ_s a_i^s ยท max(0, โˆ’x + b_i^s)
    Learns the slope a and the hinge position b for each unit and each hinge.
    """

    def __init__(self, num_features: int, num_hinges: int = 2):
        super().__init__()
        # The paper does not give initial values, so a starts at 0 (same shape as ReLU) and b at small random values
        self.a = nn.Parameter(torch.zeros(num_hinges, num_features))
        self.b = nn.Parameter(torch.randn(num_hinges, num_features) * 0.5)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # x: (batch, num_features). Add a hinge dimension and compute all hinges at once
        hinges = torch.relu(-x.unsqueeze(1) + self.b)  # (batch, S, num_features)
        return torch.relu(x) + (self.a * hinges).sum(dim=1)

    def penalty(self) -> torch.Tensor:
        # As in the paper, apply an L2 penalty (coefficient 0.001) to a and b
        return 0.001 * (self.a.pow(2).sum() + self.b.pow(2).sum())


# Example input and output (same values as a = 0.5, b = โˆ’1 in the table above)
apl = APL(num_features=3, num_hinges=1)
with torch.no_grad():
    apl.a.fill_(0.5)
    apl.b.fill_(-1.0)
    print(apl(torch.tensor([[-3.0, -1.0, 2.0]])))  # tensor([[1., 0., 2.]])

# During training, add the penalty to the loss
# loss = criterion(model(inputs), targets) + apl.penalty()

FAQ

Q. How many hinges S should be used?
A.

Choose it on validation data. In the paper, S = 1, 2, or 5 was selected depending on the data and network. Comparing S = 1, 2, 5, and 10 on CIFAR-10, S = 5 performed best, so a larger S does not always help.

Q. How should the slope a and position b be initialized?
A.

The paper does not say. The implementation example starts a at 0 (the same shape as ReLU). The configuration files used in the paper's experiments are available on the author's GitHub.

Q. How does APL differ from Leaky ReLU?
A.

Leaky ReLU uses a negative-side slope set by hand, with the same shape for every neuron. APL learns the position and slope of each bend for every neuron. APL with S = 1 and b = 0 has the same shape as Leaky ReLU.

References

  1. F. Agostinelli, M. Hoffman, P. Sadowski, and P. Baldi, "Learning Activation Functions to Improve Deep Neural Networks," ICLR Workshop, 2015.
  2. F. Agostinelli, "Learned-Activation-Functions-Source" (configuration files for the paper's experiments), GitHub.
  3. I. J. Goodfellow, D. Warde-Farley, M. Mirza, A. Courville, and Y. Bengio, "Maxout Networks," ICML, 2013.
  4. M. Lin, Q. Chen, and S. Yan, "Network In Network," arXiv:1312.4400, 2013.
  5. A. L. Maas, A. Y. Hannun, and A. Y. Ng, "Rectifier Nonlinearities Improve Neural Network Acoustic Models," ICML Workshop on Deep Learning for Audio, Speech and Language Processing, 2013.
  6. K. He, X. Zhang, S. Ren, and J. Sun, "Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification," ICCV, 2015.