Graph signal processing: Fourier transform and spectral filters
Use Laplacian eigenvectors as graph Fourier modes, define spectral filters and polynomial locality, approximate filters with Chebyshev recurrences, and explore wavelets and sampling.
After this lesson you can
- Define the graph Fourier transform and explain the absence of a canonical Euclidean translation.
- Apply low-pass, high-pass and band-pass spectral filters.
- Prove locality of Laplacian powers and polynomial filters.
- Implement a Chebyshev recurrence with sparse products and bound approximation error.
- Construct spectral graph wavelets and use them to explore localized anomalies.
Before you start
A signal lives on the nodes
A sensor network can measure one temperature per station. The reading is a vector, but its numeric order does not reveal which stations are connected. A signal on a graph assigns to node ; the graph supplies relationships that make variation between neighbors comparable. We use a finite undirected graph with nonnegative weights. Its symmetric combinatorial Laplacian satisfies
This energy measures squared differences, not absolute total variation . A signal constant on each component has zero energy. Independent noise can increase energy, but so can a real boundary: smoothing every difference is not necessarily a good decision.
Fourier without a regular grid
Diagonalize with orthogonal and . The graph Fourier transform is and its inverse is . Parseval gives and energy decomposes as . Eigenvalues order modes by quadratic variation. The number of sign changes need not increase strictly with every eigenvalue on every graph.
On an -node cycle, complex vectors are eigenvectors with . The GFT is the DFT up to sign and order conventions. Modes and share an eigenvalue; sine and cosine are a real basis for the same eigenspace. If an eigenvalue repeats in another graph, any orthogonal rotation within its eigenspace is valid: individual coefficients change, but the norm of the projection onto the whole eigenspace remains unchanged.
The fictional network has a path through nodes 1, 2, 3, 4, 5, 6 and 7; branches through 3, 8, 9, 10, 5 and through 4, 11, 12, 6; and an additional link between 2 and 9. Its 14 edges are enumerated along those paths followed by the additional link. Edge index has weight . This definition reproduces its Laplacian without attributing it to a real network.
Frequency here is an eigenvalue, not necessarily an oscillation with uniform wavelength in physical space. A mode can concentrate in one region of the graph, and energy ordering does not universally order the number of sign crossings. When stations form disconnected components there are several zero-frequency modes; each can be constant on one component and zero elsewhere. State which Laplacian, weights and graph were used before comparing spectra.
Filter by frequency
A spectral filter applies a scalar function to the eigenvalues:
Examples include heat , Tikhonov for , high-pass and a band window. An ideal low-pass with a sharp cutoff is frequency-selective, but its matrix is usually dense. The Tikhonov filter solves the minimization of : differentiation and setting the result to zero gives .
A dense decomposition generally costs and storing costs . On a large graph there is no need to diagonalize when applying a function approximated by a sparse polynomial. Partial spectra and special structures have different algorithms and costs; the cubic bound describes the general dense approach.
A filter given by the same function on each eigenspace is independent of the basis chosen within a repeated eigenvalue. Assigning different coefficients to arbitrary vectors in that eigenspace does depend on the basis. Convolution defined as componentwise multiplication of two GFTs can depend on that choice; there is no canonical translation that shifts an identical template around an irregular network. Some constructions define translation-like operators, but their properties differ from Euclidean shifts. See the review by Shuman and colleagues.
To see the difference, imagine a two-dimensional eigenspace and two signals with coordinates in one basis. Their componentwise product is . After rotating the basis by 45 degrees, both signals have two coordinate components; multiplying them and returning to the original basis generally does not yield . Multiplying the entire eigenspace by the same scalar commutes with any rotation. That invariance distinguishes a matrix function from an arbitrary table of coefficients per eigenvector.
Polynomials and locality
A local polynomial filter uses at most hops. To prove this, note that a nonzero off-diagonal entry of corresponds to an edge; a diagonal entry permits remaining at the node. Each term of is a product of entries and, if nonzero, describes a sequence of at most edges between and . If , no such sequence exists and the entry is zero. Summing degrees up to likewise introduces no dependency beyond hops.
The converse does not automatically hold for every local operator: a matrix with limited support need not be a polynomial in . Nor is a heat filter generally strictly -local for finite : its exponential contains powers of every degree, although distant contributions may be small.
Chebyshev without eigenvectors
The Chebyshev approximation rescales the spectrum to . With a safe bound , define . For , and ,
Under this convention already includes half the constant coefficient used by some libraries. Applying degree requires sparse matrix-vector products and memory for a few vectors of length . If is underestimated, the rescaled spectrum can leave and can grow rapidly. A conservative upper bound is safe but can worsen approximation by using a wider interval.
For an undirected combinatorial Laplacian with nonnegative weights, is a simple upper bound: each Gershgorin disc is centered at with radius . It is not always tight. The recurrence preserves locality because is a degree- polynomial in ; rescaling introduces a diagonal, not a new edge. The product count excludes the cost of computing coefficients, handling indices or adding vectors.
By the spectral theorem, if , then . On a particular graph the maximum over its eigenvalues suffices, although knowing them all removes part of the computational advantage. An approximation to a discontinuous jump can oscillate near the cutoff; the bound does not promise that small approximates every function equally well.
Wavelets and sampling
A family of spectral wavelets can use , with a window that vanishes at zero frequency. For example responds to differences at a given scale. Coefficients indicate localized variation but do not by themselves identify an anomaly’s cause. A family of scales plus a low-frequency component can form a reconstructible system if frame conditions hold; one wavelet does not automatically reconstruct every signal. The construction and polynomial approximation are developed by Hammond, Vandergheynst and Gribonval.
If is restricted to a band subspace of dimension , observing on a set permits unique reconstruction exactly when has rank . At least samples are needed, but their count alone does not guarantee rank. Conditioning determines sensitivity to noise and model error.
Lab: synthetic sensors
The network is a 12-by-12 grid of fictional stations; positions, edges, clean signal and noise are defined in the code. These are not weather measurements. The next routine calculates coefficients by cosine quadrature and applies the recurrence to a sparse matrix. For heat it also calculates an explicit bound for the series remainder, plus the discrepancy between numerical and analytical coefficients.
import time
import math
import numpy as np
import networkx as nx
from scipy import sparse
from scipy.linalg import qr
from scipy.sparse.linalg import spsolve
from scipy.special import iv
def cheb_coeff(g,K,lmax,N=256):
theta=np.pi*(np.arange(N)+.5)/N
values=g(.5*lmax*(1+np.cos(theta)))
c=np.array([2*np.mean(values*np.cos(k*theta)) for k in range(K+1)])
c[0]/=2
return c
def cheb_filter(L,x,coeffs,lmax):
if lmax<=0: raise ValueError('lmax debe ser positiva')
x=np.asarray(x,dtype=float); coeffs=np.asarray(coeffs,dtype=float)
def scaled(v): return 2*(L@v)/lmax-v
t0=x.copy(); out=coeffs[0]*t0
if len(coeffs)==1: return out
t1=scaled(t0); out=out+coeffs[1]*t1
for k in range(2,len(coeffs)):
t2=2*scaled(t1)-t0
out=out+coeffs[k]*t2; t0,t1=t1,t2
return out
def heat_tail_bound(z,K):
# I_k(z) <= (z/2)^k/k! exp(z²/4); geometric bound for the remaining tail.
ratio=z/(2*(K+2))
if ratio>=1: raise ValueError('K demasiado pequeño para esta cota')
return 2*np.exp(z*z/4-z)*(z/2)**(K+1)/math.factorial(K+1)/(1-ratio)For , exact heat coefficients are and for . The Bessel series gives for . If , the tail from is bounded by a geometric series with that ratio. Quadrature error of retained coefficients is added to the bound before multiplying by input norm. The check includes a small rounding tolerance.
G=nx.grid_2d_graph(12,12); nodes=sorted(G.nodes()); n=len(nodes)
A=nx.to_scipy_sparse_array(G,nodelist=nodes,dtype=float,format='csr')
L=sparse.diags(np.asarray(A.sum(axis=1)).ravel())-A
start=time.perf_counter(); eigen,U=np.linalg.eigh(L.toarray()); dense_secs=time.perf_counter()-start
lmax=float(eigen[-1]); coords=np.array(nodes)
clean=np.sin(np.pi*(coords[:,0]+1)/13)*np.cos(np.pi*(coords[:,1]+1)/13)
observed=clean+np.random.default_rng(7).normal(0,.3,size=n)
t=.35; mu=.6; K=8
heat=lambda w:np.exp(-t*w)
exact=U@(heat(eigen)*(U.T@observed))
start=time.perf_counter(); coeffs=cheb_coeff(heat,K,lmax); approx=cheb_filter(L,observed,coeffs,lmax); cheb_secs=time.perf_counter()-start
regularized=spsolve((sparse.eye(n)+mu*L).tocsc(),observed)
z=t*lmax/2
analytic=np.array([np.exp(-z)*iv(0,z)]+[2*np.exp(-z)*(-1)**k*iv(k,z) for k in range(1,K+1)])
bound=(heat_tail_bound(z,K)+np.abs(coeffs-analytic).sum())*np.linalg.norm(observed)
error=np.linalg.norm(exact-approx)
assert error <= bound+1e-12
print('n, aristas, λmax:',n,G.number_of_edges(),round(lmax,6))
print('MSE observado/calor/Tikhonov:',*[round(float(np.mean((v-clean)**2)),6) for v in (observed,exact,regularized)])
print('error Chebyshev L2/cota:',round(float(error),8),round(float(bound),8))
print('tiempos segundos diagonalización / coeficientes y recurrencia:',round(dense_secs,6),round(cheb_secs,6))One execution is measured: the first figure includes dense diagonalization and the second includes coefficients and one polynomial application. Times depend on the machine and whether the basis is amortized over many signals; they do not evaluate scalability. MSE uses the clean signal known by construction and reveals the tradeoff between removing noise and erasing genuine variation.
In the Pyodide execution with the stated seed, MSE was 0.073075 for the observed signal, 0.014550 after heat and 0.015831 with Tikhonov. Chebyshev error was approximately and the calculated bound . This improvement describes one synthetic smooth signal and two parameters chosen beforehand; it does not predict results on other networks or prove that either filter dominates the other.
anomaly_node=65; anomaly=clean.copy(); anomaly[anomaly_node]+=2.5
for scale in (.2,.5,1.,2.):
wavelet=U@((scale*eigen*np.exp(-scale*eigen))*(U.T@anomaly))
rank=np.argsort(-np.abs(wavelet)); position=int(np.flatnonzero(rank==anomaly_node)[0])+1
print('escala:',scale,'anomalía:',anomaly_node,'posición por |wavelet|:',position,'máximo:',int(rank[0]))A spike of amplitude 2.5 was added to a known node and absolute wavelet values were ranked at four scales. The resulting positions describe this signal without additional noise, not a general detection rate. Real data require threshold calibration and study of false positives and background variation.
With that construction the injected node ranked first at scales 0.2, 0.5 and 1, and 19th at scale 2. The same spike can compete with legitimate background responses: compare several scales and retain neighbor context rather than treating every high value as a definitive label.
r=8; basis=U[:,:r]; _,_,pivots=qr(basis.T,pivoting=True,mode='economic')
samples=pivots[:r]; coeff=np.random.default_rng(5).normal(size=r); bandlimited=basis@coeff
[email protected](basis[samples],bandlimited[samples])
assert np.linalg.matrix_rank(basis[samples])==r
print('muestreo: rango',np.linalg.matrix_rank(basis[samples]),'error L2',float(np.linalg.norm(reconstructed-bandlimited)))Pivoted QR selection here produces eight full-rank rows for the first eight modes. Repeated eigenvalues are included completely in this particular band. Reconstruction uses a signal built exactly in that subspace and noise-free samples: outside these assumptions the matrix can amplify errors.
Local comparison with PyGSP
This standalone cell requires pygsp, SciPy and NetworkX in the local runtime. It creates its own grid, uses the combinatorial Laplacian and compares the exact heat filter and recurrence with the PyGSP API. PyGSP expresses the constant term as ; before comparing with this lesson’s convention, divide that coefficient by two. The spectral bound must be the same in both paths.
import numpy as np
import networkx as nx
from pygsp import graphs, filters
from pygsp.filters import approximations
G=nx.grid_2d_graph(8,8); nodes=sorted(G.nodes())
A=nx.to_scipy_sparse_array(G,nodelist=nodes,dtype=float,format='csr')
graph=graphs.Graph(A,lap_type='combinatorial')
graph.compute_fourier_basis()
lmax=float(graph.lmax); K=8; t=.35
x=np.random.default_rng(7).normal(size=graph.N)
kernel=lambda w: np.exp(-t*w)
filt=filters.Filter(graph,kernel)
library=np.asarray(approximations.compute_cheby_coeff(filt,m=K,N=256)).reshape(-1)
theta=np.pi*(np.arange(256)+.5)/256
values=kernel(.5*lmax*(1+np.cos(theta)))
own=np.array([2*np.mean(values*np.cos(k*theta)) for k in range(K+1)])
own[0]/=2
normalized=library.copy(); normalized[0]/=2
assert np.allclose(normalized,own,atol=1e-12)
def apply_cheb(L,x,c,lmax):
scaled=lambda v:2*(L@v)/lmax-v
t0=x.copy(); out=c[0]*t0
if len(c)==1: return out
t1=scaled(t0); out=out+c[1]*t1
for k in range(2,len(c)):
t2=2*scaled(t1)-t0; out=out+c[k]*t2; t0,t1=t1,t2
return out
own_result=apply_cheb(graph.L,x,own,lmax)
library_result=np.asarray(approximations.cheby_op(graph,library,x)).reshape(-1)
exact=np.asarray(filt.filter(x,method='exact')).reshape(-1)
assert np.allclose(own_result,library_result,atol=1e-10)
print('diferencia máxima de coeficientes:',float(np.max(np.abs(own-normalized))))
print('diferencia máxima de recorrencias:',float(np.max(np.abs(own_result-library_result))))
print('error L2 de aproximación frente a PyGSP exacto:',float(np.linalg.norm(own_result-exact)))npm run lab and open the connection link.In one local execution with PyGSP 0.6.1, the maximum coefficient difference was and the recurrence difference . The error against the exact filter was approximately . This check compares conventions on this grid and these parameters; it does not imply degree 8 suffices for every filter.
Exercises
Step 1 of 2. What does a nonzero product in the expansion of (L^k)_ij represent?
Step 1 of 2. How does a shift transform mode exp(2πikj/n)?
import numpy as np
def cheb_filter(L, x, coeffs, lmax):
passKey ideas
A degree-K polynomial combines information from up to K hops and can be applied without diagonalization. Approximation and wavelets connect spectral selectivity with computational cost and spatial locality.