Group convolutions and steerable CNNs
Construct lifting and group convolutions, understand steerable kernel constraints, and measure discretization effects and model costs.
After this lesson you can
- Explain how translation equivariance leads to convolution under stated assumptions.
- Implement p4 lifting and group convolution with periodic boundaries.
- Compare regular-field parameter and operation budgets.
- Describe steerable kernel constraints and discretization errors.
- Evaluate symmetry assumptions on real-image tasks and report measured limits.
Before you start
- 25Intertwiner spaceIrreducible representationsSchur's lemmaFourier transform on groupsInduced action on signals and fieldsEquivariant nonlinearities
- 16Discrete 2D convolution and cross-correlationMax and average poolingTranslation equivarianceConvolution as a structured sparse matrix
- 02Toeplitz matrixCirculant matrix
- 09Sampling and aliasingPolynomial interpolation
Sharing filters with symmetry
A cell under a microscope or a satellite-observed region can appear in different orientations. If the task assigns no special meaning to those orientations, an architecture sharing information across rotations can exploit that regularity. Before imposing it, check the label: rotating a 6 can produce an image ambiguous with 9 and reflecting text usually does not preserve meaning.
The convolution characterization begins with an observation from m16: on an infinite grid, a linear layer under suitable continuity and summability assumptions that commutes with every translation has shared weights and is represented by convolution. On a finite torus circular convolution results. In a finite image cropping, padding, stride and boundaries change the result; not every CNN implementation is exactly equivariant to every translation.
This idea extends to groups and homogeneous spaces under explicit assumptions on actions, fields and regularity. “Every equivariant layer is a convolution” must be read in that framework, not as a statement about arbitrary nonlinear networks, boundaries or every signal type. Field representations determine admissible kernels.
In a homogeneous space , group moves any point to any other and stabilizes a reference. A field need not be scalar: its value may transform under a representation of . Moving the field, the induced action transforms both position and components. In the framework of Cohen, Geiger and Weiler, equivariant linear maps between fixed-type fields are characterized by convolutions with compatible kernels. Group, base space, representations and regularity conditions are part of the statement. For compact groups the theory uses Haar measure instead of a finite sum; it does not turn a nonlinear layer or cropped implementation into that ideal operator.
The discrete proof is visible directly in weights. If a linear layer gives the same result when input and output are shifted, the weight connecting two positions can depend only on their relative displacement. Fixing a reference position determines the other weights. On a finite torus shifts are modulo domain size; the resulting matrix is block-circulant.
A one-pixel translation can cease to be an exact symmetry after stride-two downsampling: sampling selects another grid phase. Antialias filtering reduces certain artifacts but does not by itself restore every equality of an action no longer exactly represented. Before attributing an error to group convolution also check input, padding, pooling and resampling.
Lifting an image to p4
Group combines integer translations with rotations of 0, 90, 180 and 270 degrees. Element acts on coordinates as and composition is . Lifting convolution transforms a scalar image into a signal with one coordinate per orientation:
This can be interpreted as applying four rotated versions of the same filter, not four independent filters. The figure uses correlation with periodic boundary on a 7-by-7 grid; the convention matches the preceding formula when expressing relative kernel displacement.
If input rotates a quarter turn, each spatial map also rotates and orientation index shifts. Rotating each map without permuting channels does not reproduce the correct action. The displayed residual compares both routes over every pixel and orientation; in this integer example it is exactly zero.
With odd-sized square images and translations modulo size, quarter turns act on a discrete torus. This permits an exact test without losing boundary pixels. A normal zero-padded image poses another boundary condition and must be tested separately. The lab uses explicit functions to rotate, shift and permute channels.
Lifting does not create four independent observations. Each map uses a rotation of the same kernel and learnable weights remain those of the original filter. If the image rotates 90 degrees, the filter associated with one orientation responds in the next, after the corresponding spatial rotation. The figure checks this correspondence by maximum error, not just color similarity.
Correlation versus convolution convention changes which filter version appears for each rotation sign. Deep-learning libraries often call correlation “convolution.” Define input and output actions and check the identity using the same convention. Copying an orientation index from another implementation without its conventions can reverse the cyclic shift.
Convolution over the group
A group convolution receives a signal defined on elements of and combines positions and orientations:
For left action , change of variable gives . Order matters in noncommutative groups. Infinite groups require summability or integration assumptions; the lab uses a finite group of periodic translations and four rotations.
Regular fields have one coordinate per element of a finite orientation group. A transformation permutes those coordinates and transforms the spatial grid. Applying the same ReLU to each coordinate commutes with that permutation. For vector fields or real irreps mixing components through rotation matrices, that rule generally fails; norms, gates or other compatible nonlinearities are used.
Averaging over four orientations eliminates channel permutation, but the resulting map still rotates spatially. To obtain an invariant image scalar, aggregate positions compatibly too, for example by spatial mean on a rotation-preserved domain. adds reflections and changes the action and orientation count; imposing them makes sense only if labels are preserved.
In the lab each group filter has four components for relative orientations. To produce orientation , take the component corresponding to the difference between input and output orientation and rotate the spatial kernel by . Each output sums contributions from all four input orientations. That index rule makes orientation permutation compatible with spatial rotation.
Orientation pooling can be sum, mean or maximum if applied symmetrically to every orientation index. Choosing the maximum channel retains a value invariant to permutation but may discard information about multiple coexisting orientations. Keeping the regular field for more layers allows use of that information before summarizing; where to reduce is an architecture decision.
Layer budget
Consider 32 input and 32 output regular fields in p4, each with four orientations: there are 128 effective channels on each side. A 3×3 group kernel has weights without biases. An ordinary convolution with 128 input and output channels has weights.
At each position the p4 layer computes four output orientations and performs products. The ordinary CNN also performs 147456 products per position. Counting each multiplication and addition as two operations gives approximately 294912 FLOPs per position in both cases. Parameter reduction does not automatically mean four times less compute: transformed versions of the kernel are evaluated. Counts omit biases, padding and filter-materialization cost; implementation and hardware affect actual time.
If “32 channels” instead means 32 effective channels rather than 32 regular fields, there are eight fields per side. The same reasoning yields 2304 p4 weights versus 9216 in the ordinary CNN. Specify what is counted when comparing architectures.
Operation count does not capture all cost. A model may expand transformed filters once for inference or rebuild them during training. Intermediate map size depends on field and orientation counts, and a library kernel may use different implementations depending on tensor shape. Compare trainable parameters, memory and actual time separately.
Steerable kernels
A steerable CNN assigns each channel a transformation law. Its steerable kernels must satisfy
The constraint links spatial kernel rotation with input and output representations. Decomposing fields into irreps allows solving it by blocks and combining a fixed basis with learned coefficients. Generality and cost depend on representations and the number of frequencies included.
In the one-dimensional complex example, and . A solution has angular dependence multiplied by a radial function. The figure uses an explicit radial basis vanishing at the origin when angular frequency is nonzero. For real two-dimensional representations, combinations of sum and difference frequencies can appear; a universal “subtract frequencies” rule does not suffice for all real blocks.
A complex frequency-one channel can be represented by two real coordinates rotating together. Changing the complex coefficient phase combines sine and cosine without violating the constraint. Radius transforms trivially under rotations, so a multiplicative radial function does not change angular frequency. At the center, where angle is undefined, nonconstant angular dependence needs a continuity-compatible definition.
The figure’s analytic basis is one example, not a library’s complete basis. A practical kernel may combine multiple radial functions, frequencies and irrep pairs and restrict support. Layer capacity depends on those choices. Increasing frequency order can represent faster angular variation but increases sampling requirements to avoid aliasing.
An exact continuous kernel identity need not remain exact after sampling on a grid. A square image’s 90-degree rotation can be implemented as a pixel permutation. A 45-degree rotation normally needs interpolation and may crop corners. Even with circular-support filters, interpolation and sampling introduce errors that must be measured.
Equivariance discretization error depends on operation, interpolator, support, boundary and data. A C₄ network does not promise exact 45-degree invariance; C₈ includes that rotation in the abstract group, but a pixel-sampled image does not admit 45 degrees as a simple permutation. A continuous SO(2) model can also have numerical residual when sampled. A small minimum does not demonstrate generalization or diagnostic accuracy.
To measure error, transform output according to its type. In a vector field both spatial image and components rotate; in a regular representation orientation channels are also permuted. After pooling to scalar logits, output action is trivial and equivariance residual becomes an invariance difference. The plot uses that last case so all five models share comparable output.
Normalization scale matters. Dividing a difference by a very small norm can amplify residual; code fixes a denominator floor and reports the formula. A nearly constant output may show small error without solving the task, so the experiment also publishes accuracy. Curves are measured on 16 specific images and do not describe a complete error distribution.
Boundaries deserve separate inspection. Rotation about the center of a square image preserves the grid at 90 degrees, but at intermediate angles corners may leave the field and interpolated or padding values appear. Comparing only interior pixels reduces some boundary differences but answers another question. If an application needs to retain corner information, it can enlarge the canvas before rotating and declare that change.
Lab: p4 in NumPy
The next two cells implement lifting and group convolution through exact filter rotations and periodic boundary. Four rotations, three translations and pooling are checked. Group-convolution kernels and a linear head are then trained; lifting filters remain fixed. Kernel gradients are checked by finite differences.
The included sample contains the first 40 train and 20 test examples of each MNIST class 0, 1 and 2. The 28×28 images were reduced to 7×7 by averaging 4×4 blocks and rotated by multiples of 90 degrees with a fixed seed. Compressed JSON includes original indices and is SHA-256 verified before use. In the measured run the network got 89/120 train and 41/60 test correct; maximum feature difference after a 90-degree rotation was less than . This is a tiny three-class sample, not a full MNIST test score.
The official compressed image files used for extraction had SHA-256 440fcabf73cc546fa21475e81ea370265605f56be210a4024d2ca8f203523609 for train and 8d422c7b0a1c1c79245a5bcf07fe86e33eeafee792b84584aec276f5a2dbc4e6 for test. Torchvision distributes original splits; the lab need not download them because it includes only the reduced sample.
import numpy as np
def correlate_periodic(x,kernel):
# Correlación en un toro impar: y(t)=sum_u x(t+u) kernel(u).
assert kernel.shape==(3,3)
out=np.zeros_like(x,dtype=float)
for i in range(3):
for j in range(3):out+=kernel[i,j]*np.roll(x,shift=(1-i,1-j),axis=(-2,-1))
return out
def lift_p4(image,kernel):
return np.stack([correlate_periodic(image,np.rot90(kernel,k)) for k in range(4)],axis=-3)
def group_conv_p4(f,psi):
# f tiene forma (...,4,H,W); psi tiene forma (4,3,3).
if f.shape[-3]!=4 or psi.shape!=(4,3,3):raise ValueError('formas esperadas (...,4,H,W) y (4,3,3)')
out=[]
for k in range(4):
y=np.zeros_like(f[...,0,:,:],dtype=float)
for s in range(4):y+=correlate_periodic(f[...,s,:,:],np.rot90(psi[(s-k)%4],k))
out.append(y)
return np.stack(out,axis=-3)
def act_image(image,k,shift):
return np.roll(np.rot90(image,k,axes=(-2,-1)),shift,axis=(-2,-1))
def act_field(field,k,shift):
rotated=np.rot90(field,k,axes=(-2,-1))
return np.roll(np.roll(rotated,k,axis=-3),shift,axis=(-2,-1))
rng=np.random.default_rng(23)
image=rng.normal(size=(9,9));kernel=rng.normal(size=(3,3));psi=rng.normal(size=(4,3,3))
features=lift_p4(image,kernel);out=group_conv_p4(features,psi)
errors=[]
for k in range(4):
for shift in [(0,0),(1,-2),(-3,2)]:
a=lift_p4(act_image(image,k,shift),kernel);b=act_field(features,k,shift)
c=group_conv_p4(a,psi);d=act_field(out,k,shift)
errors.append(max(np.max(np.abs(a-b)),np.max(np.abs(c-d))))
assert np.allclose(a,b,atol=1e-10) and np.allclose(c,d,atol=1e-10)
assert np.isclose(np.mean(c),np.mean(out))
print('p4: giros, traslaciones y pooling comprobados; error máximo',max(errors))
import base64,gzip,json,hashlib
import numpy as np
# Extraído de MNIST: clases 0, 1 y 2, primeras 40 imágenes train y 20 test por clase.
# Cada imagen 28×28 se redujo a 7×7 promediando bloques 4×4.
encoded=(
'H4sIAAAAAAACCq1dybLkyHH8lznjgIzc+Ss0HmQSD7zwIPIgm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RhZftCvY7Kpkgbh1eANIL/CDuk/LsD7bYwHbJoK9XdFHsJLATiLQ9SYGZjsLl3VgXIe6gjWNNwqZc+34vHUQK1lv193D'
'vNBL9jY5V97h4ME6oueo5ThoYVYqZYOteKKvtWztwLlB/oaiGa30TcLoDXXmrG9cRzYSZ9Tjdu3m4JId2d61o/WW4dbErYfj0L9E'
'm3f4fp88o1De4TJ02MX4zOy013kMvtG/hT9PfuUa1SYpBgGaeocgeSyyM5TWj+HY8HGCqmeXnPhb2l2xDf/sk+y2LL/NnPkN38t2'
'kqCR/o7D0f5dHssfzDvZ+CTeWHONMYHJ7MpshP/KQLJUlwMujXFVDNu2Q8ejkUXAwuBhqEye+A8MaGSzQarIczstgajtn3kgLykb'
'sQBoPv9BBxtFCoTnjDfSx8Fcm9YLdmAUO+btvGASQ6im1Ja//Otf/w9i9qy3S2UAAA=='
)
raw=gzip.decompress(base64.b64decode(encoded))
assert hashlib.sha256(raw).hexdigest()=='59ca7f2ffbe7939e572572cd2f89e153c3eeabea1ad0238db97736d8cb404516'
dataset=json.loads(raw);rng=np.random.default_rng(44)
def images(split):
x=np.asarray(dataset[split]['x'],float)/255;y=np.asarray(dataset[split]['y'],int)
turns=rng.integers(0,4,size=len(x))
return np.stack([np.rot90(image,int(k)) for image,k in zip(x,turns)]),y
train_x,train_y=images('train');test_x,test_y=images('test')
# La elevación es fija; se entrenan los kernels de grupo y la cabeza lineal.
filters=rng.normal(size=(6,3,3));kernels=rng.normal(size=(6,4,3,3))/6
def group_kernel_grad(h,upstream):
gradient=np.zeros((4,3,3))
for k in range(4):
for s in range(4):
rotated_grad=np.zeros((3,3))
for i in range(3):
for j in range(3):
rotated_grad[i,j]=np.sum(upstream[:,k]*np.roll(h[:,s],(1-i,1-j),axis=(-2,-1)))
gradient[(s-k)%4]+=np.rot90(rotated_grad,-k)
return gradient
# Diferencias finitas del gradiente del kernel en dos coordenadas.
f=rng.normal(size=(2,4,7,7));psi=rng.normal(size=(4,3,3));up=rng.normal(size=(2,4,7,7))
analytic=group_kernel_grad(f,up)
for idx in [(0,0,0),(1,1,2)]:
delta=np.zeros_like(psi);delta[idx]=1e-5
numerical=np.sum((group_conv_p4(f,psi+delta)-group_conv_p4(f,psi-delta))*up)/(2e-5)
assert np.isclose(numerical,analytic[idx],rtol=1e-7,atol=1e-7)
print('Gradiente del kernel: diferencias finitas comprobadas')
def lifted(x):return [np.maximum(lift_p4(x,a),0) for a in filters]
def features(activations):
pre=[group_conv_p4(h,b) for h,b in zip(activations,kernels)]
return np.stack([np.maximum(v,0).mean(axis=(-3,-2,-1)) for v in pre],axis=1),pre
train_h=lifted(train_x);test_h=lifted(test_x);initial,_=features(train_h)
mean=initial.mean(0);std=initial.std(0)+1e-6
w=rng.normal(scale=.05,size=(6,3));bias=np.zeros(3);onehot=np.eye(3)[train_y]
for epoch in range(60):
raw,pre=features(train_h);X=(raw-mean)/std;logits=X@w+bias;logits-=logits.max(1,keepdims=True)
probabilities=np.exp(logits);probabilities/=probabilities.sum(1,keepdims=True)
grad=(probabilities-onehot)/len(X);grad_features=(grad@w.T)/std
dw=X.T@grad;db=grad.sum(0)
kernel_grads=[]
for j in range(len(kernels)):
up=(pre[j]>0)*grad_features[:,j,None,None,None]/(4*7*7)
kernel_grads.append(group_kernel_grad(train_h[j],up))
w-=.1*dw;bias-=.1*db;kernels-=.02*np.stack(kernel_grads)
X,_=features(train_h);Xt,_=features(test_h);X=(X-mean)/std;Xt=(Xt-mean)/std
train_acc=np.mean((X@w+bias).argmax(1)==train_y);test_acc=np.mean((Xt@w+bias).argmax(1)==test_y)
rotated_features,_=features(lifted(np.rot90(test_x,1,axes=(-2,-1))))
original_features,_=features(test_h);residual=np.max(np.abs(rotated_features-original_features))
print('MNIST 0/1/2 train/test:',len(train_y),len(test_y))
print('exactitud train:',round(float(train_acc),4),'test:',round(float(test_acc),4))
print('error máximo de invariancia de rasgos a 90°:',float(residual))Local lab: escnn and real data
escnn and steerable kernel theory use field types and representation constraints. Here that construction is compared with an ordinary CNN. PathMNIST is a histopathology dataset reduced to 28×28; its use here is educational, not a clinical evaluation. Install PyTorch, torchvision and escnn 1.0.11 in a compatible local environment. The trial used CPU, torch 2.5.1, NumPy 1.26.4 and escnn’s numerical fallback. The first run downloads MNIST and PathMNIST; code checks the latter’s official MD5 and displays its SHA-256.
One seed selects 64 or 256 training images and 128 test images from index 128 of the official test split. Uniform rotations are applied during 20 training epochs and an independent fixed rotation to test. All five models have exactly 701 parameters on MNIST and 807 on PathMNIST, but not the same computational cost or architecture. The table shows correct predictions out of 128, not a robust sample-efficiency estimate:
| Dataset | Train | CNN | C4 | C8 | D8 | SO(2) |
|---|---|---|---|---|---|---|
| MNIST | 64 | 17 | 18 | 16 | 14 | 19 |
| MNIST | 256 | 31 | 31 | 34 | 34 | 31 |
| PathMNIST | 64 | 13 | 7 | 13 | 13 | 13 |
| PathMNIST | 256 | 49 | 35 | 33 | 36 | 19 |
In this small test no architecture dominates both datasets. More data or repeated seeds may change the ordering; it is not extrapolated to full datasets. Figure residuals were computed on the first 16 test images and normalized by original logit norm with minimum 1e-8. Interpolation and cropping affect all models, and a low value can also come from nearly constant logits. Output records local training times and parameter count alongside accuracy and residuals.
import os,math,time,json,hashlib,urllib.request
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from torchvision.datasets import MNIST
from escnn import gspaces
from escnn import nn as enn
torch.set_num_threads(2)
root=Path(os.environ.get('STEER_DATA','dataset/oryon-steerable'));root.mkdir(parents=True,exist_ok=True)
mnist_root=Path(os.environ.get('MNIST_ROOT',str(root/'mnist')))
path_file=Path(os.environ.get('PATHMNIST_FILE',str(root/'pathmnist.npz')))
sizes=[int(v) for v in os.environ.get('STEER_SIZES','64,256').split(',')]
test_n=int(os.environ.get('STEER_TEST','128'));test_offset=int(os.environ.get('STEER_TEST_OFFSET','128'));epochs=int(os.environ.get('STEER_EPOCHS','20'));batch=int(os.environ.get('STEER_BATCH','16'))
datasets=os.environ.get('STEER_DATASETS','MNIST,PathMNIST').split(',')
output=Path(os.environ.get('STEER_OUTPUT',str(root/'results.json')))
def read_data(name):
if name=='MNIST':
train=MNIST(str(mnist_root),train=True,download=True);test=MNIST(str(mnist_root),train=False,download=True)
x=train.data.numpy()[...,None];y=train.targets.numpy();xt=test.data.numpy()[...,None];yt=test.targets.numpy();C,K=1,10
elif name=='PathMNIST':
if not path_file.exists():
path_file.parent.mkdir(parents=True,exist_ok=True)
urllib.request.urlretrieve('https://zenodo.org/records/10519652/files/pathmnist.npz?download=1',path_file)
contents=path_file.read_bytes();assert hashlib.md5(contents).hexdigest()=='a8b06965200029087d5bd730944a56c1'
print('PathMNIST bytes',len(contents),'SHA-256',hashlib.sha256(contents).hexdigest(),flush=True)
with np.load(path_file,allow_pickle=False) as d:
x=d['train_images'];y=d['train_labels'].reshape(-1);xt=d['test_images'];yt=d['test_labels'].reshape(-1)
C,K=3,9
else:raise ValueError('Dataset desconocido')
rng=np.random.default_rng(17);chosen=rng.permutation(len(y))[:max(sizes)];test_indices=np.arange(test_offset,min(test_offset+test_n,len(yt)))
if len(chosen)<max(sizes) or len(test_indices)==0:raise ValueError('Tamaño o desplazamiento fuera de la partición')
train_x=torch.from_numpy(x[chosen].copy()).permute(0,3,1,2).float()/255;train_y=torch.tensor(y[chosen].copy(),dtype=torch.long)
test_x=torch.from_numpy(xt[test_indices].copy()).permute(0,3,1,2).float()/255;test_y=torch.tensor(yt[test_indices].copy(),dtype=torch.long)
print(name,'splits completos',len(y),len(yt),'selección',len(chosen),len(test_indices),'clases train',torch.bincount(train_y,minlength=K).tolist(),'clases test',torch.bincount(test_y,minlength=K).tolist(),flush=True)
return train_x,train_y,test_x,test_y,C,K
def rotate(x,angle):
if not torch.is_tensor(angle):angle=torch.full((len(x),),float(angle))
c,s=angle.cos(),angle.sin();z=torch.zeros_like(c)
theta=torch.stack([c,-s,z,s,c,z],dim=1).reshape(-1,2,3)
return F.grid_sample(x,F.affine_grid(theta,x.size(),align_corners=False),mode='bilinear',padding_mode='zeros',align_corners=False)
class Model(nn.Module):
def __init__(self,kind,C,K):
super().__init__();self.kind=kind
if C==1:config={'CNN':(12,17),'C4':(17,18),'C8':(17,18),'D8':(17,18),'SO2':(24,17)};target=701
else:config={'CNN':(8,11),'C4':(14,14),'C8':(14,14),'D8':(14,14),'SO2':(17,22)};target=807
width,hidden=config[kind]
if kind=='CNN':self.conv=nn.Conv2d(C,width,5,padding=2,bias=False)
else:
self.space=gspaces.rot2dOnR2(N=4) if kind=='C4' else gspaces.rot2dOnR2(N=8) if kind=='C8' else gspaces.flipRot2dOnR2(N=8) if kind=='D8' else gspaces.rot2dOnR2(N=-1,maximum_frequency=3)
self.in_type=enn.FieldType(self.space,[self.space.trivial_repr]*C)
rep=self.space.irrep(1) if kind=='SO2' else self.space.regular_repr
self.out_type=enn.FieldType(self.space,[rep]*width)
self.conv=enn.R2Conv(self.in_type,self.out_type,5,padding=2,bias=False)
self.activation=enn.NormNonLinearity(self.out_type,bias=False) if kind=='SO2' else enn.ReLU(self.out_type,inplace=False)
self.pool=enn.NormPool(self.out_type) if kind=='SO2' else enn.GroupPooling(self.out_type)
self.head=nn.Sequential(nn.Linear(width,hidden),nn.ReLU(),nn.Linear(hidden,K))
count=sum(p.numel() for p in self.parameters() if p.requires_grad);assert count==target,(kind,C,K,count,target)
def forward(self,x):
if self.kind=='CNN':h=F.relu(self.conv(x))
else:h=self.pool(self.activation(self.conv(enn.GeometricTensor(x,self.in_type)))).tensor
return self.head(h.mean(dim=(-2,-1)))
results={};curves={}
for name in datasets:
train_x,train_y,test_x,test_y,C,K=read_data(name);results[name]={}
test_angles=(torch.rand(len(test_x),generator=torch.Generator().manual_seed(19))*2-1)*math.pi
rotated_test=rotate(test_x,test_angles)
for n in sizes:
results[name][n]={}
for kind in ('CNN','C4','C8','D8','SO2'):
torch.manual_seed(7);rng=torch.Generator().manual_seed(21);model=Model(kind,C,K);optimizer=torch.optim.Adam(model.parameters(),lr=.003)
start=time.perf_counter();model.train()
for epoch in range(epochs):
perm=torch.randperm(n,generator=rng)
for j in range(0,n,batch):
idx=perm[j:j+batch];angle=(torch.rand(len(idx),generator=rng)*2-1)*math.pi
logits=model(rotate(train_x[idx],angle));loss=F.cross_entropy(logits,train_y[idx])
optimizer.zero_grad();loss.backward();optimizer.step()
seconds=time.perf_counter()-start;model.eval()
with torch.no_grad():
predicted=torch.cat([model(rotated_test[j:j+batch]) for j in range(0,len(test_y),batch)])
acc=float((predicted.argmax(1)==test_y).float().mean())
sample=test_x[:min(16,len(test_x))];base=model(sample);den=base.norm(dim=1).clamp_min(1e-8)
series=[]
for deg in (0,15,30,45,60,75,90):
rotated=torch.rot90(sample,1,(-2,-1)) if deg==90 else rotate(sample,deg*math.pi/180)
score=model(rotated);series.append(float(((score-base).norm(dim=1)/den).mean()))
record={'accuracy':acc,'train_seconds':round(seconds,2),'parameters':sum(p.numel() for p in model.parameters() if p.requires_grad),'class_counts_train':torch.bincount(train_y[:n],minlength=K).tolist(),'class_counts_test':torch.bincount(test_y,minlength=K).tolist(),'angles':[0,15,30,45,60,75,90],'residual':series}
results[name][n][kind]=record
if n==max(sizes):curves[name]=curves.get(name,{})|{kind:series}
print(name,n,kind,record,flush=True)
output.parent.mkdir(parents=True,exist_ok=True)
output.write_text(json.dumps({'results':results,'curves':curves,'sizes':sizes,'epochs':epochs,'test_n':test_n,'test_offset':test_offset},indent=2),encoding='utf8')
npm run lab and open the connection link.Exercises
Step 1 of 3. What substitution simplifies the sum for (Lu f)⋆ψ?
Step 1 of 3. What change of variable is used in the sum?
def group_conv_p4(f, psi):
pass