pygmtools.utils.gaussian_aff_fn

pygmtools.utils.gaussian_aff_fn(feat1, feat2, sigma=1.0, backend=None)[source]

Gaussian kernel affinity function. The affinity is defined as

\[\exp(-\frac{(\mathbf{f}_1 - \mathbf{f}_2)^2}{\sigma})\]
Parameters
  • feat1\((b\times n_1 \times f)\) the feature vectors \(\mathbf{f}_1\)

  • feat2\((b\times n_2 \times f)\) the feature vectors \(\mathbf{f}_2\)

  • sigma – (default: 1) the parameter \(\sigma\) in Gaussian kernel

  • backend – (default: pygmtools.BACKEND variable) the backend for computation.

Returns

\((b\times n_1\times n_2)\) element-wise Gaussian affinity matrix

Note

Use functools.partial to specify sigma before passing it to build_aff_mat().

Example:

>>> import functools
>>> gaussian_aff = functools.partial(pygm.utils.gaussian_aff_fn, sigma=1.)
>>> K2 = pygm.utils.build_aff_mat(None, edge1, conn1, None, edge2, conn2, n1, ne1, n2, ne2, edge_aff_fn=gaussian_aff)
Numpy Implementation Example

This is an example of Numpy implementation for your reference if you want to customize the affinity function:

import numpy as np

def gaussian_aff_fn(feat1, feat2, sigma): # feat1 has shape (n_1, f), feat2 has shape (n_2, f)
                                          # use functools.partial if you want to specify sigma value
    feat1 = np.expand_dims(feat1, axis=2)
    feat2 = np.expand_dims(feat2, axis=1)
    return np.exp(-((feat1 - feat2) ** 2).sum(axis=-1) / sigma)

The most important thing to bear in mind when customizing is to write an affinity function that respects the input & output dimensions:

  • Input feat1: \((b\times n_1 \times f)\),

  • Input feat2: \((b\times n_2 \times f)\),

  • Output: \((b\times n_1\times n_2)\).

Another example can be found at inner_prod_aff_fn().