skip to content
← Scientific Spaces English

Margin-Enforcing Projection

In this post, we introduce a mathematical operation called "Margin-Enforcing Projection (MEP)," which partitions a vector into two parts in a specified manner and then requires the margin between these two parts to be at least (Margin)。

Background Introduction #

As we know, classification tasks aim to select the correct class, so the training objective is usually just that positive-class scores exceed negative-class scores. In certain scenarios, however, we not only want positive-class scores to exceed negative-class scores, but also want them to exceed them by at least a specified margin .

These scenarios mainly fall into two categories. The first is when we want classification results to be more robust and less susceptible to random noise, especially in low-precision inference settings, so we prefer the margin between prediction results to be more pronounced. The second is when we do not use the classification model for inference at all, but rather intend to learn features through classification, with the ultimate scenario being feature retrieval; in this case, if we do not enforce a margin, retrieval results near the decision boundary can easily become error-prone.

In fact, both scenarios matured years ago—especially the second scenario, with the quintessential example being the training of face recognition feature models—so this post is essentially "resurrecting an old topic." The standard approach to this problem is to design various margin losses, such as hinge loss, margin softmax, and AM-Softmax, which we also briefly touched upon earlier in "Sentence Similarity Model Based on GRU and AM-Softmax" and "From Triangle Inequality to Margin Softmax".

The premise of this post is that if we had an operation capable of projecting the predicted scores into scores satisfying the margin requirement , then we could simply train the model directly toward it as the target, for instance by minimizing . This projection operation is precisely the problem we will investigate next.

Mathematical Definition #

Let , where denotes the model's predicted scores. For simplicity, we assume that the first scores represent positive scores and the remaining represent negative-class scores. We define

where , is an integer greater than 0 and less than , is a given margin, and is the distance function to be minimized. We have two choices, the L1 distance and the L2 distance, which we will discuss separately below.

This definition is very intuitive: while satisfying the margin requirement, we seek the vector closest to the predicted scores. This aligns with the general idea of projection operations, so we call it "Margin-Enforcing Projection (MEP)." Using such a projection result as the learning target theoretically allows the model to follow the easiest and fastest path, while also enabling it to "brake" in time once the target is reached, avoiding overtraining.

Common Results #

If already satisfies , then obviously , which is trivial. Without loss of generality, we assume below that . It is easy to see that regardless of whether is chosen as the L1 or L2 distance, the optimal solution must satisfy
; otherwise, one could always bring certain closer to to decrease the objective value. Based on this observation, let , so , which yields

At this point,

Next, depending on the choice of , we solve for .

The L2 Distance #

We first consider the L2 distance, in which case we have

Taking the derivative yields

where is the counting function, with the convention that . Obviously, , but it can be strengthened to .

This is because implies and , which means that both and hold simultaneously, contradicting the assumption that . Therefore, , meaning that is strictly convex; combined with the continuity of and , as well as and , we can conclude that has a unique minimizer, which must be attained at .

Since is a composition of the piecewise linear function , is also a piecewise linear function of , with the boundary points being all and . To solve , we first sort the boundary points in ascending order, obtaining intervals; within a single interval, is a straight line. By iterating over all intervals and finding the interval where and , we can simply find the zero of the linear function within that interval.

The L1 Distance #

Next, we consider the L1 distance, where we have

Clearly, is itself a piecewise linear function. The minimum of such a function can only be attained at boundary points, so the most naive approach is to traverse all boundary points , and take the one that makes minimal, with a complexity of . However, we can simplify this even further. First, taking the derivative gives

The second equality uses the identity , and now it is easy to see that monotonically increases from negative to positive. Of course, is not continuous, so we cannot guarantee finding a point where .

However, if we change to (the derivative at discontinuous boundary points can be regarded as arbitrary, so this adjustment is permissible), then means precisely that "the number of boundary points less than or equal to is exactly ". If we further assume that all boundary points are pairwise distinct, then is the element ranked among all boundary points sorted in ascending order! Therefore, in the L1 setting, a single sort is actually enough to obtain , which is quite neat.

Reference Implementation #

Reference implementations of the two MEP versions are as follows:

import jax
import jax.numpy as jnp

@jax.jit
def l2mep(inputs, mask, margin):
    x, m = inputs, margin
    u = jnp.where(mask, x, x + m).sort()[:, None]
    v = jnp.where(mask, jnp.fmax(u - x, 0), -jnp.fmax(x + m - u, 0)).sum(axis=1)
    i = ((v[:-1] < 0) & (v[1:] >= 0)).argmax()
    l = (u[i + 1] * v[i] - u[i] * v[i + 1]) / (v[i] - v[i + 1])
    return jnp.where(mask, jnp.fmax(x, l), jnp.fmin(x, l - m))

@jax.jit
def l1mep(inputs, mask, margin):
    x, m = inputs, margin
    u = jnp.where(mask, x, x + m).sort(axis=-1)
    l = jnp.take_along_axis(u, (~mask).sum(axis=-1, keepdims=True) - 1)
    return jnp.where(mask, jnp.fmax(x, l), jnp.fmin(x, l - m))

A brief explanation here: in practical scenarios, positive classes are usually not simply arranged in the first positions; both their count and their positions may be arbitrary. Therefore, in the implementation above, we use a mask vector to mark positive and negative classes.

l2mep currently only supports 1D inputs. If you need to support a batch dimension, simply wrap it with jax.vmap. This algorithm finds the zero-crossing interval by traversing all intervals; each step has a complexity of , and the total complexity is . If you want to improve efficiency, you can instead use binary search to find the zero-crossing interval, which reduces it to

l1mep is simple enough that the current implementation already supports arbitrary batch dimensions. Its core operation is just sorting, with a complexity of , which is quite ideal in terms of both simplicity and speed. Barring other considerations, the L1 version is recommended in practice.

Summary #

In this post, we introduced the operation "Margin-Enforcing Projection (MEP)": given a score vector, project it onto the nearest vector satisfying "the minimum of the positive class is greater than the maximum of the negative class by at least ". This can provide some new perspectives for traditional margin learning.