CS58700 - Foundations of Deep Learning¶

Spring 2026¶

Instructor and Copyright: Bruno Ribeiro with help by S. Chandra Mouli¶


Learning G-Invariant Representations¶

Reading assigment for this lecture:¶

The reading assigments for this lecture:

Reading assigment: Linear Algebra

  • Chapter 2.1 (Scalars, Vectors, Matrices and Tensors)
  • Chapter 2.2 (Multiplying Matrices and Vectors)
  • Chapter 2.3 (Identity and Inverse Matrices)
  • Chapter 2.4 (Linear Dependence and Span)
  • Chapter 2.5 (Norms)
  • Chapter 2.6 (Special Kinds of Matrices and Vectors)
  • Chapter 2.7 (Eigendecomposition)
  • Chapter 2.8 (Singular Value Decomposition)

Reading assigment: Course in the Theory of Groups, by Robinson, Derek J.S, Springer Graduate Texts in Mathematics (Access through Purdue Library. Requires BolierKey)

  • Chapter 1.1 (Binary Operations, Semigroups, and Groups)
  • Chapter 1.2 (Examples of Groups) Groups of Matrices, of Linear Transformations, of Isometries, of Permutations
  • Chapter 1.3 (Subgroups and Cosets) Subgroups, Intersections, Subgroup Generation, Hasse Diagrams, Normal Subgroups,

Understanding Symmetries¶

The concept of symmetry is at least as fundamental as the concept of a number.

  • The study of symmetries occurs particularly in geometry, and dates as far back as 2,500 years ago.
  • However, while symmetry examples are often geometric, the concept has wide applicability.
    • To understand non-geometric applications of symmetry, we will be treating symmetry in an axiomatic form using group theory.

First, we need the concept of a (transformation) group.

Definition of a Group¶

A group consists of:

  1. A set $G$,
  2. A definition of a product between two elements, such that $\forall A,B \in G$, $A B \in G$. The product has the following axioms:
    1. (Associative) The product is associative: $A(BC) = (AB)C$ and holds for all $A,B,C \in G$.
    2. (Identity) There exists an element $I \in G$ with the property that $I A = A = A I$ for all $I \in G$.
      • $I$ is unique and is called the identity of $G$.
    3. (Inverse) To each $A \in G$ there exists $A^{-1} \in G$ with the property that $A A^{-1} = I = A^{-1} A$.
      • $A^{-1}$ is unique and is called the inverse of $A$.

Extra Properties¶

  1. (Commutative (Abelian) groups) If $AB=BA$ for all $A,B \in G$, we call $G$ an Abelian or commutative group.

  2. (Finite & Infinite groups) If $G$ has a finite number of elements it is called a finite group, otherwise it is an infinite group.

  3. (Linear Group) If $T \in G$ is a linear transformation, $G$ is a linear group

    • That is, $\forall T \in G$, $T$ is a linear transformation, i.e., $T(x+x')= T(x) + T(x')$ and $T(\alpha x) = \alpha T(x)$ for any scalar $\alpha$.
  4. (General Linear Group) (simplified definition) Let $\text{GL}(n,\mathbb{R})$ denote the set of all bijective linear transformations of $\mathbb{R}^n$ into $\mathbb{R}^n$.

    • Matrix multiplication is the group operation.
    • The Identity element $I$ is the $n \times n$ identity matrix.
    • Bijective implies the matrix has an inverse.
    • Hence, $\text{GL}(n,\mathbb{R})$ is the set of all nonsingular matrices $T \in \mathbb{R}^{n\times n}$.
    • This group is nonabelian if $n > 1$. That means, $\exists A,B \in \text{GL}(n,\mathbb{R})$ such that $AB \neq BA$ if $n > 1$.

General Linear Transformation Group of Images¶

In the following examples we will consider an input $x \in \mathbb{R}^{3 m^2}$ representing a vectorized $m \times m$ RGB image.

We now define general linear groups of transformations over the images.

  • We will call these general linear transformation groups.
  • The general linear transformation group of our image is $\text{GL}(3 m^2,\mathbb{R})$.

Examples ($\equiv$ means "defined as"):

  1. $G_\text{rot} \equiv \{T^{(\theta)}\}_{\theta\in \{0^\circ,90^\circ,180^\circ,270^\circ\}}$, which rotates the image by $\theta$ degrees, where $T^{(0)}$ is the identity element.

  2. $G_\text{flip} \equiv \{T^{(v)}, T^{(h)},T^{(180^\circ)}, T^{(0)}\}$, which are vertical flip, horizontal flip, $180^\circ$ rotation and identity transformation, respectively. Note that rotation $T^{(180^\circ)}$ is needed in $G_\text{flip}$ to satisfy the group requirements.

Examples of transformations from $G_\text{rot}$:

No description has been provided for this image

Q: Can the $45^\circ$ rotation $T^{(45)} \in GL(3 m^2,\mathbb{R})$?

A: No. Note that $T^{(45)}$ is not invertible. since anything at the corners of the image will be cut from the output.

No description has been provided for this image

Q: Can the $45^\circ$ rotation and scaling $T^{(45 \text{ \& scale})} \in G(3 m^2,\mathbb{R})$?

A:: No. In the definition of a group, if $A,B \in G$, then $A B \in G$. But that does not happen in this scenario:

No description has been provided for this image

An important group: The permutation group¶

  • A permutation group $G$ is a group whose elements are permutations of a given set $A$ and whose group operation is the composition of permutations in G
    • Given a set $A$, a permutation of $A$ is a function $f : A \to A$ which is a bijection. A permutation group of $A$ is a set of permutations of $A$ that forms a group under function composition.
    • We’ll focus specifically on the case when $A = \{1, \ldots, n\}$ for some fixed integer $n \geq 1$. This means each group element will permute this set.
      • For example if $A = \{1, 2, 3\}$ then a permutation $\pi$ might have $\pi(1) = 2$, $\pi(2) = 1$, and $\pi(3) = 3$.
  • Example: Examples of permutation groups include
    • the symmetric group $\mathbb{S}_n$ (of order $n!$),
      • The symmetric group $\mathbb{S}_n$ is the group of all permutations of the set $\{1, 2, \ldots, n\}$.
    • the alternating group $\mathbb{A}_n$ (of order $n!/2$ for $n\geq 2$),
    • the cyclic group $\mathbb{C}_n$ (of order $n$), and
    • the dihedral group $\mathbb{D}_n$ (of order $2n$).

Applications of the Symmetric Group¶

  • A 3D point could is a sequence of $m$ 3D points ${\bf x} \in \mathbb{R}^{m \times 3}$
    • Representations of a point cloud should not depend on the order of the $m$ points in ${\bf x}$.
No description has been provided for this image
  • A $n$-size graph is a sequence of $n$ nodes and $n^2$ edges ${\bf A} \in \mathbb{R}^{n\times n \times d}$ (adjacency tensor), where $d \geq 1$ is a feature vector (may include node attributes, as we will discuss in our class on graph representations).
    • Representations of a graph should not depend on to the oder of the $n$ nodes in the adjacency tensor.
No description has been provided for this image
Common Mistake¶
  • Above we see that we want our final representations to be invariant (equivariant) to the symmetric group $\mathbb{S}_n$.

    • But the symmetric group acts on integer values (i.e., permuting indices), not matrices or tensors.
    • It is common to find papers on point clouds that will erroneously say $\pi \in \mathbb{S}_n$ and then apply $\pi \circ {\bf x}$.
  • We will now introduce the concept of group representations (actions of a group on a space)

Group Representations¶

For us, the concept of group insofar as it acts as a transformation on an input.

A (linear finite dimensional) group representation $\rho : G \to \text{GL}(m,\mathbb{R})$ associates each $g \in G$ to an invertible matrix $\rho(g) \in \mathbb{R}^{m \times m}$ that acts on $\mathbb{R}^m$.

  • The representation satisfies:
    • for the identity element $ e \in G$: $\rho(e) = I$ is the identity matrix.
    • $\forall g_1,g_2 \in G : \rho(g_1g_2) = \rho(g_1)\rho(g_2),$ and therefore also $\rho(g^{-1}) = \rho(g)^{-1}$.

The representation specifies how objects transform under the group, and can be considered a specification of the type of an object.

  • Set representation example: $\pi \in \mathbb{S}_n$ be a permutation of $\{1,\ldots,n\}$. Define $\rho(\pi)$ as the (linear) group representation of $\pi$ that will permute the 3D points in the sequence ${\bf x} \in \mathbb{R}^{n \times 3}$ according to the permutation provided by $\pi$.
    • Hence, $\text{vec}({\bf x}') = \rho(\pi) \text{vec}({\bf x})$ is a sequence of 3D points permuted according to the permutation given in $\pi$.

Group Equivariant and Invariant Neural Networks¶

Let $X \subseteq \mathbb{R}^d$ and $Y \subseteq \mathbb{R}^k$ be two vector spaces

Let $f: X \to Y$ be a neural network function

$\mathcal{G}$-equivariant function¶

Commutative Diagram:

$$ \begin{array}{ccc} X & \xrightarrow{\pi} & X \\ \downarrow f & & \downarrow f \\ Y & \xrightarrow{\pi} & Y \end{array} $$

Definition: $$f(\pi \circ x) = \pi \circ f(x) \quad \forall \pi \in \mathcal{G}$$

Note: Group representations of appropriate dimensions act on X and Y

$\mathcal{G}$-invariant function¶

Definition: $$f(\pi \circ x) = f(x) \quad \forall \pi \in \mathcal{G}$$

Example: Symmetries of a Triangle (2D)¶

Property Behavior under Translation
Area of the triangle Invariant to translations
Centroid of the triangle Equivariant to translations
No description has been provided for this image

When you translate a triangle, its area stays the same (invariant), but its centroid moves accordingly (equivariant).

Group-Invariant ($G$-Invariant) Transformation¶

  • Today's class is based on a few works, but our presentation focuses mostly on (Mouli & Ribeiro, ICLR 2021), which offers an application to causality that we will revist later in the course.

  • Let $G$ be a discrete transformation group.

    • Let $\mathbb{T}=\{\rho(g): \forall g \in G\}$, where $\rho(g)$, $g \in G$ is a group representation.
  • A transformation $\bar{T}$ is $G$-invariant iff $\forall T \in \mathbb{T}$ and $\forall {\bf x} \in \mathbb{R}^m$ we have $$\bar{T} \circ (T \circ {\bf x}) = \bar{T}\circ {\bf x}.$$

    • Since the above is true for all ${\bf x}$, then $$\bar{T} \circ T = \bar{T}.$$
  • Lemma: Reynolds operator (Billik and Rota, 1960). The transformation $$\bar{T} = \frac{1}{|\mathbb{T}|} \sum_{T \in \mathbb{T}} T,$$ is $G$-invariant.

Proof: Consider an arbitrary transformation $T_\dagger \in G$. Then $$\bar{T} \circ T_\dagger = \frac{1}{\vert G \vert}\sum_{T \in \mathbb{T}} T \circ T_\dagger = \frac{1}{\vert G \vert}\sum_{T' \in \mathbb{T}_\dagger} T' ,$$ where we define $\mathbb{T}_\dagger = \{T \circ T_\dagger: \forall T \in \mathbb{T} \}$.

  • Now, in order to prove $\bar{T} \circ T_\dagger = \bar{T}$, we only need to show that $\mathbb{T}_\dagger = \mathbb{T}$.
  • Since groups are closed under compositions, we have $\forall T \in \mathbb{T}$, $T \circ T_\dagger \in \mathbb{T}$, and thus $\mathbb{T}_\dagger \subseteq \mathbb{T}$.
  • Finally, since $T_\dagger$ is a bijection and $T_a \circ T_\dagger = T_b \circ T_\dagger$ only if $T_a = T_b$ for any $T_a, T_b \in \mathbb{T}$, it must be that $|\mathbb{T}_\dagger| = |\mathbb{T}|$.
  • Hence, $\mathbb{T}_\dagger = \mathbb{T}$.

Group-Equivariant ($G$-Equivariant) Transformation¶

  • Equivariance requires that transforming the input is the same as transforming the output.
  • Let $G$ be a discrete transformation group of transformations $T:\mathbb{R}^a \to \mathbb{R}^a$.
  • (Special case) A function $f:\mathbb{R}^m \to \mathbb{R}^m$ is $G$-equivariant iff $\forall g \in G$ and $\forall {\bf x} \in \mathbb{R}^m$ we have $$f(\rho(g) {\bf x}) = \rho(g) f({\bf x}),$$ where $\rho: G \to (\mathbb{R}^m \to \mathbb{R}^m)$.
  • (More general) A function $f:\mathbb{R}^m \to \mathbb{R}^d$ is $G$-equivariant iff $\forall g \in G$ and $\forall {\bf x} \in \mathbb{R}^m$ we have $$f(\rho_1(g) {\bf x}) = \rho_2(g) f({\bf x}),$$ where $\rho_1: G \to (\mathbb{R}^m \to \mathbb{R}^m)$ and $\rho_2: G \to (\mathbb{R}^d \to \mathbb{R}^d)$.
  • We will first focus on $G$-invariant representations.
  • $G$-equivariant representations will appear at the end of the lecture.

$G$-Invariant Representations¶

  • Our goal is to learn a neuron with

    • Weights ${\bf w} \in \mathbb{W}$ on a subspace $\mathbb{W}$
    • Bias $b \in \mathbb{R}$
    • And activation function $\sigma:\mathbb{R} \to \mathbb{R}$.
    • Such that $$\sigma({\bf w}^T x + b) = \sigma({\bf w}^T T x + b) , \quad \forall T \in G. $$
  • This means that the output of the neuron does not depend on the transformation of $G$ applied to the input.

    • We call it a $G$-Invariant representation

First: Understading Invariant Subspaces¶

A subspace $M \subseteq \mathbb{R}^d$, $d \geq 1$, is an invariant subspace of a linear transformation $\bar{T}:\mathbb{R}^d \to \mathbb{R}^d$ if $$ {\bf w}^T \bar{T} \in M, ~\forall {\bf w}^T \in M. $$

For instance. The left 1-eigenspace is an invariant subspace defined as: $$\text{Left-1-Eig}(\bar{T}) = \{ {\bf w} \in \mathbb{R}^d | {\bf w}^T \bar{T} = {\bf w}^T \}.$$

Second: Reynods Operator Eigenvalues¶

  • Note that $\bar{T}$ is a projection (i.e., $\bar{T}^2 = \bar{T}$), all the eigenvalues of $\bar{T}$ are either 0 or 1.
    • You can verify this: $\bar{T}^2 = \bar{T} \frac{1}{|G|} \sum_{T \in G} T = \frac{1}{|G|} \sum_{T \in G} \bar{T} T = \frac{1}{\vert G \vert}\sum_{T' \in G_\dagger} T' = \frac{1}{|G|} \sum_{T \in G} T = \bar{T}$
  • Note:
    • Since $T \in G$, $T:\mathbb{R}^d \to \mathbb{R}^d$, is invertible, it would have $d$ non-zero eigenvalues (full rank)
    • But the average $\bar{T}$ may not be full rank!

$G$-Invariant Neuron¶

Proposition (G-invariant neuron):

  • Let $\mathcal{W}$ denote the right eigenspace corresponding to the eigenvalue 1 of the Reynolds operator $\bar{T}$ for the group $G$.

  • Let ${\bf v}_1,\ldots,{\bf v}_k$ be the left eigenvectors of $\bar{T}$. That is, $$ {\bf v}_i^T \bar{T} = \lambda_i {\bf v}_i, \quad i =1,\ldots,k. $$

  • Since $\bar{T}$ is a projection operator, $$ {\bf v}_i^T \bar{T} = {\bf v}_i, \quad i =1,\ldots,k. $$

  • Now consider a vector of neuron weights ${\bf w}$.
  • Consider a set of free parameters $\{\alpha_i\}_{i=1}^k$, $\alpha_i \in \mathbb{R}$ and a bias $b \in \mathbb{R}$.
  • Define ${\bf w}^T = \sum_{i=1}^{k} \alpha_i {\bf v}_i^T$.
    • Note that $\mathcal{W} = \text{span}({\bf v}_1,\ldots,{\bf v}_k)$
      • $\text{span}({\bf v}_1,\ldots,{\bf v}_k)$ is the space defined by all linear combinations of the vectors ${\bf v}_1,\ldots,{\bf v}_k$.
    • Then, by construction ${\bf w} \in \mathcal{W}$.
  • Consider a transformed input ${\bf x}' = T {\bf x}$, $T \in G$.
  • Consider an activation function $\sigma:\mathbb{R} \to \mathbb{R}$.
  • Then, the neuron is $G$-invariant: $$\sigma({\bf w}^T {\bf x}' + b) = \sigma({\bf w}^T {\bf x} + b).$$

Proof:

  • Note that since $\bar{T}$ is a projection operator, $\lambda_i = 1$,$i=1,\ldots,k$.
    • Also note that ${\bf w}^T = \sum_{i=1}^{k} \alpha_i {\bf v}_i^T = \sum_{i=1}^{k} \alpha_i {\bf v}_i^T \bar{T} = {\bf w}^T \bar{T} $.
  • Hence, ${\bf w}^T {\bf x}' + b = {\bf w}^T \bar{T} {\bf x}' + b = {\bf w}^T \bar{T}\, T {\bf x} + b = {\bf w}^T \bar{T} {\bf x} + b = {\bf w}^T {\bf x} + b$.
    • Which means the neuron output is the same for ${\bf x}'$ and ${\bf x}$.

$G$-Invariant Neuron¶

  • Note that the parameters are $\{\alpha_i\}_{i=1}^k$ and a bias $b$.
  • The number of parameters is at most the same as the original neuron (since $k\leq d$), but often much smaller.
  • The computation takes $k$ inner products, one element-wise product, and a sum (a little more expensive but GPUs can do this very efficiently).

Example¶

  • Task: MNIST handwritten digit classification task.

  • Our tranformation group of interest is the $G_\text{rot} \equiv \{T^{(\theta)}\}_{k\in \{0^\circ,90^\circ,180^\circ,270^\circ\}}$, which rotates the image by $\theta$ degrees, where $T^{(0)}$ is the identity element.

  • Consider the MNIST dataset of handwritten digits:

    No description has been provided for this image
  • The input to our transformation group is ${\bf x}$, the vectorized image

You will need files g_invariance.py and mnist.pt to run the following examplar code.

In [12]:
# See link above for g_invariance.py
from g_invariance import *

# Define 90-rotation function.
def rotate_array(array, degree):
    if (array.ndim == 2 and degree % 90 == 0):
        return onp.rot90(array, degree // 90)
    else:
        print("Can only rorate 2D array by 90n degrees.")
        raise RuntimeError


# Define average of 4 rotations (0, 90, 180, 270) function.
def averaged_four_rotations(array):
    buf = []
    for degree in (0, 90, 180, 270):
        buf.append(rotate_array(array, degree))
    return sum(buf) / len(buf)

First: Get the eigenvectors of the Reynolds operator¶

  • First, we need to get the matrix of the Reynolds operator.
    • Often our group transformations are given by a black-box:
      • How do we get the tranformation matrix from a black-box?
      • For all $i=1,\ldots,d$, do $\bar{T}_{:,i} = \bar{T}_\text{BB} e_i^T$, where $e_i = (0,\ldots,1,\ldots,0)$ is the $i$-th standard basis.
      • The stack all column $\bar{T}_{:,i}$.
In [13]:
# Define number of CPUs to use for subspace generation.
NUM_TRANSFORM_CPUS = 4

#Important variables
#  - transform_mat is out Reynods operator \bar{T}
#  - null_eigenvectors are the eigenvectors of \bar{T}

# Apply given transformation on onehot corresponding to each pixel of 2D image.
# Use Python multiprocessing since it is work with numpy array.
# If it is torch Tensor, it is recommended to use PyTorch wrapped version of
# multiprocessing (torch.multiprocessing).
def get_invariant_subspace(transform_func, shape):
    # Use multiprocessing to get transformation matrix correspond to given
    # transformation function by paralleling onehot dimensions.
    numel = onp.prod(shape)
    pool = mp.Pool(NUM_TRANSFORM_CPUS)
    transformed_buf = pool.map(
        partial(
            transformed_onehot,
            transform_func=transform_func, shape=shape,
        ),
        range(numel),
    )
    pool.close()
    pool.join()
    
    # Form a single Reynods operator matrix from all results
    transform_mat = onp.stack(transformed_buf,axis=1)

    # Eigenvectors is used to describe the transformation subspace.
    # Use right side of decomposition thus eigenvectors are located at rows.
    # Transformation matrix is assumed to be real symmetric, thus Hermitian is
    # used for optimization.
    _, eigenvalues, eigenvectors = onp.linalg.svd(transform_mat,hermitian=True)

    # Eigenvalues are sorted from high to low, thus for over rank eigenvectors,
    # they are null eigenvectors assigned with 0 eigenvalues.
    # We should focus on non-trival eigenvectors.
    rank = onp.linalg.matrix_rank(onp.diag(eigenvalues),hermitian=True)
    
    eigenvectors = eigenvectors[:rank]
    return transform_mat, eigenvectors.T

Eigenvectors of the Reynolds Operator¶

In [14]:
transform_mat, eigenvectors = get_invariant_subspace(averaged_four_rotations, (height, width))

print(f"The Reynolds operator tranformation matrix has dimension {transform_mat.shape}")
print(f"The subspace W is the subspace span by {eigenvectors.shape[1]} eigenvectors")
print("--- First 16 eigenvectors shown as images ---")
showSubspace(eigenvectors, (height, width), ndim=16, channels=False)
The Reynolds operator tranformation matrix has dimension (784, 784)
The subspace W is the subspace span by 196 eigenvectors
--- First 16 eigenvectors shown as images ---
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image

Standard MLP¶

  • First, we will test the performance of a standard MLP
  • The Original Train data contains regular MNIST images
  • The Original Validation data contains regular MNIST images
  • The Original Test data contains regular MNIST images
  • The Rotated Test data contains rotated MNIST images (rotated at random)
In [19]:
import torch.nn as nn

class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        
        # We will later replace the first layer with a G-invariant layer.
        # Rest of the code remains the same.
        self.first_layer = nn.Linear(784, 50)
        
        self.mlp = nn.Sequential(
                self.first_layer,
                nn.ReLU(),
                nn.Linear(50, 10)
        )
                
    def forward(self, X):
        out = self.mlp(X)
        return out
        
model = MLP()
In [20]:
# Standard MLP with 1 hidden layer.
rng = torch.Generator("cpu")
rng.manual_seed(0)

# Use Pytorch's pre-defined SGD optimizer
optimizer = torch.optim.SGD(model.parameters(),lr=LR)

best_acc = 0
best_state_dict = copy.deepcopy(model.state_dict())
print("=====", "=" * 8)
print("Epoch", "Train Accuracy")
print("-----", "-" * 8)
for epc in range(NUM_EPOCHS):
    # Creates a mini-batch
    for batch_cnt, batch_itr in enumerate(
        torch.randperm(
            len(train_input),
            generator=rng,
        )[0:NUM_SAMPLES].view(
            NUM_BATCHES, BATCH_SIZE,
        ),
    ):
        # Zero gradients of optimize
        optimizer.zero_grad()
        # Forward pass of model
        train_output = model(train_input[batch_itr])
        # Define loss
        train_loss = torch.nn.functional.cross_entropy(train_output, train_target[batch_itr])
        # Backprop
        train_loss.backward()
        # One gradient step
        optimizer.step()
        
    valid_acc = accuracy(model, valid_input, valid_target)
    if (valid_acc > best_acc):
        print("{:5d} {:.6f}".format(epc + 1, valid_acc))
        best_acc = valid_acc
        best_state_dict = copy.deepcopy(model.state_dict())
    elif ((epc + 1) % 100 == 0):
        print("{:5d} {:.6f}".format(epc + 1, valid_acc))
    else:
        pass
print("=====", "=" * 8)
model.load_state_dict(best_state_dict)
train_acc = accuracy(model, train_input, train_target)
valid_acc = accuracy(model, valid_input, valid_target)
test_acc = accuracy(model, test_input, test_target)
aug_test_acc = accuracy(model, aug_test_input, aug_test_target)
print("=====", "=" * 8)
print("Data ", "\tAccuracy")
print("-----", "-" * 8)
print("Original Train", "{:.6f}".format(train_acc))
print("Original Valid", "{:.6f}".format(valid_acc))
print("Original Test ", "{:.6f}".format(test_acc))
print("Rotated  Test ", "{:.6f}".format(aug_test_acc))
print("=====", "=" * 8)
===== ========
Epoch Train Accuracy
----- --------
    1 0.837191
    2 0.881836
    3 0.895008
    4 0.904400
    5 0.909238
    6 0.912992
    7 0.914837
    8 0.918475
    9 0.921252
   10 0.924050
   12 0.925555
   13 0.929452
   15 0.931796
   17 0.932742
   18 0.932750
   20 0.933319
   21 0.934537
   22 0.936521
   26 0.937423
   27 0.938605
   30 0.938694
   31 0.941817
   37 0.942573
   53 0.943196
   61 0.944435
   66 0.944688
   85 0.945852
  100 0.945048
===== ========
===== ========
Data  	Accuracy
----- --------
Original Train 0.986855
Original Valid 0.945852
Original Test  0.947650
Rotated  Test  0.372948
===== ========

G-Invariant MLP¶

  • Now we will test the performance of a G-invariant MLP
  • The Original Train data contains regular MNIST images
  • The Original Validation data contains regular MNIST images
  • The Original Test data contains regular MNIST images
  • The Rotated Test data contains rotated MNIST images (rotated at random)
In [34]:
import math
eigentensor = torch.from_numpy(eigenvectors).float()

class GInvariantLayer(nn.Module):
    
    def __init__(self, input_dim, output_dim):
        super().__init__()
        
        # Load the left 1-eigenvectors of the Reynolds operator that we computed before.
        self.basis = eigentensor.T
        assert self.basis.shape[1] == input_dim
        
        self.coeffs = nn.Parameter(torch.Tensor(output_dim, self.basis.shape[0], 1))
        self.bias = nn.Parameter(torch.Tensor(output_dim))
        
        stdv = 1.0/math.sqrt(output_dim)
        self.coeffs.data.uniform_(-stdv, stdv)
        self.bias.data.zero_()
    

    def forward(self, X):
        # Input shape: torch.Size([minibatch, input_dim])
        
        if self.basis.device != X.device:
            self.basis = self.basis.to(X.device)

        # Construct weight w \in \mathcal{W} (the left 1-eigenspace)
        #      using the current learnable coefficients.
        # coeffs: (output_dim, n_basis, 1)
        # basis  : (n_basis, input_dim)
        # result after torch.mul : (output_dim, n_basis, input_dim)
        # result after sum : (output_dim, input_dim)
        weights = torch.mul(self.coeffs, self.basis)
        weights = weights.sum(dim=-2)

        # Output shape: torch.Size([minibatch, output_dim])
        out = X @ weights.T + self.bias

        return out
In [35]:
class GInvariantMLP(nn.Module):
    def __init__(self):
        super().__init__()
        
        # Replace the first layer with a G-invariant layer.
        self.first_layer = GInvariantLayer(784, 50)
        
        self.mlp = nn.Sequential(
                self.first_layer,
                nn.ReLU(),
                nn.Linear(50, 10)
        )
                
    def forward(self, X):
        out = self.mlp(X)
        return out

        
model = GInvariantMLP()
In [36]:
# G-invariant MLP with 1 hidden layer.
rng = torch.Generator("cpu")
rng.manual_seed(0)

# Use Pytorch's pre-defined SGD optimizer
optimizer = torch.optim.SGD(model.parameters(),lr=LR)
best_acc = 0
best_state_dict = copy.deepcopy(model.state_dict())
print("=====", "=" * 8)
print("Epoch", "Train Accuracy")
print("-----", "-" * 8)
linear_transform = torch.Tensor(transform_mat.T)
for epc in range(NUM_EPOCHS):
    for batch_cnt, batch_itr in enumerate(
        torch.randperm(
            len(train_input),
            generator=rng,
        )[0:NUM_SAMPLES].view(
            NUM_BATCHES, BATCH_SIZE,
        ),
    ):
        optimizer.zero_grad()
        train_output = model.forward(
            train_input[batch_itr],
        )
        train_loss = torch.nn.functional.cross_entropy(
            train_output, train_target[batch_itr],
        )
        train_loss.backward()
        optimizer.step()
    valid_acc = accuracy(
        model,
        valid_input,
        valid_target,
    )
    if (valid_acc > best_acc):
        print("{:5d} {:.6f}".format(epc + 1, valid_acc))
        best_acc = valid_acc
        best_state_dict = copy.deepcopy(model.state_dict())
    elif ((epc + 1) % 50 == 0):
        print("{:5d} {:.6f}".format(epc + 1, valid_acc))
    else:
        pass
print("=====", "=" * 8)
model.load_state_dict(best_state_dict)
train_acc = accuracy(
    model,
    train_input,
    train_target,
)
valid_acc = accuracy(
    model,
    valid_input,
    valid_target,
)
test_acc = accuracy(
    model,
    test_input,
    test_target,
)
aug_test_acc = accuracy(
    model,
    aug_test_input,
    aug_test_target,
)
print("=====", "=" * 8)
print("Data  ", "Accuracy")
print("-----", "-" * 8)
print("Original Train", "{:.6f}".format(train_acc))
print("Original Valid", "{:.6f}".format(valid_acc))
print("Original Test ", "{:.6f}".format(test_acc))
print("Rotated  Test  ", "{:.6f}".format(aug_test_acc))
print("=====", "=" * 8)
===== ========
Epoch Train Accuracy
----- --------
    1 0.308690
    2 0.390732
    3 0.473029
    4 0.488353
    5 0.515366
    6 0.522194
    7 0.528756
    8 0.564369
    9 0.580975
   10 0.585732
   12 0.587812
   13 0.601295
   16 0.620082
   18 0.621791
   20 0.625342
   22 0.631214
   23 0.638681
   24 0.643150
   27 0.652897
   30 0.654865
   31 0.659390
   35 0.667046
   36 0.669251
   37 0.669282
   41 0.676899
   44 0.681269
   50 0.677041
   55 0.682113
   56 0.686409
   57 0.688299
   61 0.690130
   77 0.692890
   85 0.695984
   90 0.696916
   96 0.697655
  100 0.695011
===== ========
===== ========
Data   Accuracy
----- --------
Original Train 0.713258
Original Valid 0.697655
Original Test  0.709855
Rotated  Test   0.709855
===== ========

G-equivariant Representations¶

  • Consider an input in $\mathbb{R}^m$.
  • And the output in $\mathbb{R}^k$.
  • Let ${\bf W} \in \mathbb{R}^{k \times m}$ be the neuron parameters
  • Equivariance requires that transforming the input is the same as transforming the output: $$ {\bf x} \in \mathbb{R}^m, \forall g \in G , \quad \rho_2(g) {\bf W} {\bf x} = {\bf W} \rho_1(g) {\bf x}, $$ where $\rho_1:G \to \mathbb{R}^{m \times m}$ and $\rho_2:G \to \mathbb{R}^{k \times k}$.
  • Since the above is true for all ${\bf x}$, then $$\rho_2(g) {\bf W} \rho_1(g)^{-1} = {\bf W},$$ or equivalently $$\forall g \in G, \qquad \rho_2(g) \otimes \rho_1(g^{-1})^T \text{vec}({\bf W}) = \text{vec}({\bf W}),$$ where vec flattens the matrix into a vector, and so the whole transformation is $\rho_2(g) \otimes \rho_1(g^{-1})^T = \rho_{12}(g)$ that is a representation of how $g$ acts on matrices mapping from $A_1 \to A_2$.
  • Note: Special operators acting on matrices (and tensors):
    • $\oplus$ is the direct sum which concatenates the matrices on the diagonal $$X \oplus Y =\begin{bmatrix} X & 0 \\ 0 & Y\\ \end{bmatrix}$$ and facilitates multiple representations which are acted upon separately.
    • $\otimes$ is the Kronecker product, where for matrices ${\bf A}$ and ${\bf B}$ is defined as $$\mathbf {A} \otimes \mathbf {B} =\begin{bmatrix}a_{11}\mathbf {B} &\cdots &a_{1n}\mathbf {B} \\\vdots &\ddots &\vdots \\a_{m1}\mathbf {B} &\cdots &a_{mn}\mathbf {B} \end{bmatrix}.$$
      • Example (from Wikipedia) $${\begin{bmatrix}1&2\\3&4\\\end{bmatrix}}\otimes {\begin{bmatrix}0&5\\6&7\\\end{bmatrix}}={\begin{bmatrix}1{\begin{bmatrix}0&5\\6&7\\\end{bmatrix}}&2{\begin{bmatrix}0&5\\6&7\\\end{bmatrix}}\\3{\begin{bmatrix}0&5\\6&7\\\end{bmatrix}}&4{\begin{bmatrix}0&5\\6&7\\\end{bmatrix}}\\\end{bmatrix}}={\begin{bmatrix}1\times 0&1\times 5&2\times 0&2\times 5\\1\times 6&1\times 7&2\times 6&2\times 7\\3\times 0&3\times 5&4\times 0&4\times 5\\3\times 6&3\times 7&4\times 6&4\times 7\\\end{bmatrix}}={\begin{bmatrix}0&5&0&10\\6&7&12&14\\0&15&0&20\\18&21&24&28\end{bmatrix}}.$$

Group-Equivariant ($G$-Equivariant) Neurons¶

  • Note that equation $$\forall g \in G, \qquad \rho_2(g) \otimes \rho_1(g^{-1})^T \text{vec}({\bf W}) = \text{vec}({\bf W})$$ has a familiar form.
    • We can rewrite the above equation as $$T {\bf w} = {\bf w},$$ where $T = \rho_2(g) \otimes \rho_1(g^{-1})^T$ and ${\bf w} = \text{vec}({\bf W}).$
  • The above is the equation required for a $G$-invariant representation.
    • We can again use the Reynolds operator to find $\bar{T}$ such that $\forall {\bf x} \in \mathbb{R}^{mk}$ and $$\forall T \in \{\rho_2(g) \otimes \rho_1(g^{-1})^T : \forall g \in G\}$$ such that $$\bar{T}(T {\bf x}) = \bar{T} {\bf x}.$$

Lie Groups (Optional)¶

A Lie group is a continuous groups that uses infinitesimal generators

  • Lie theory provides a way of analyzing continuous groups in terms of their infinitesimal generators
  • The Lie Algebra $g$ of a Lie Group $G$ (a continuous group that forms a smooth manifold) is the tangent space at the identity $g := T_{id} G \subseteq \mathbb{R}^{m\times m}$, which is a vector space of infinitesimal generators of group transformations from $G$.
  • The exponential map $\exp : g \to G$ maps back to the Lie Group and can be understood through the series $$\exp(A) = \sum_{t=0}^\infty \frac{A^t}{t!}.$$
  • A classic example is the rotation group $G = \text{SO}(m)$ with matrices $\mathbb{R}^{m\times m}$ satisfying $R^T R = I$ and $\det(R) = 1$.

We will explore Lie Groups further in our lecture on set representations