Module contents
Lesson 6 of 30Core 105 min

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 xix_i to node ii; the graph supplies relationships that make variation between neighbors comparable. We use a finite undirected graph with nonnegative weights. Its symmetric combinatorial Laplacian L=D−AL=D-A satisfies

x⊤Lx=∑{i,j}∈Ewij(xi−xj)2.x\T Lx=\sum_{\{i,j\}\in E}w_{ij}(x_i-x_j)^2.

This energy measures squared differences, not absolute total variation ∑wij∣xi−xj∣\sum w_{ij}|x_i-x_j|. 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 L=UΛU⊤L=U\Lambda U\T with orthogonal UU and 0=λ1≤⋯≤λn0=\lambda_1\le\cdots\le\lambda_n. The graph Fourier transform is x^=U⊤x\hat x=U\T x and its inverse is x=Ux^x=U\hat x. Parseval gives ∥x∥22=∥x^∥22\norm{x}_2^2=\norm{\hat x}_2^2 and energy decomposes as x⊤Lx=∑kλkx^k2x\T Lx=\sum_k\lambda_k\hat x_k^2. Eigenvalues order modes by quadratic variation. The number of sign changes need not increase strictly with every eigenvalue on every graph.

InteractiveModes on two graphs
12345678910
  • Positive
  • Negative
  • Zero
u = [0.316, 0.316, 0.316, 0.316, 0.316, 0.316, 0.316, 0.316, 0.316, 0.316]
Graph
0
Eigenvalue λ0.0000
Edges with opposite signs0
The cycle uses an explicit sine and cosine basis. The rail network is a fictional topology described below, not city data. Colors show sign and radius magnitude. An eigenvector's global sign is arbitrary.

On an nn-node cycle, complex vectors uk(j)=e2πikj/n/nu_k(j)=e^{2\pi\mathrm{i}kj/n}/\sqrt n are eigenvectors with λk=2−2cos⁡(2πk/n)\lambda_k=2-2\cos(2\pi k/n). The GFT is the DFT up to sign and order conventions. Modes kk and n−kn-k 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 j=0,…,13j=0,\ldots,13 has weight 1+0.07j1+0.07j. 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:

g(L)x=U g(Λ) U⊤x,g(Λ)=diag⁡(g(λk)).g(L)x=U\,g(\Lambda)\,U\T x,\qquad g(\Lambda)=\operatorname{diag}(g(\lambda_k)).

Examples include heat g(λ)=e−tλg(\lambda)=e^{-t\lambda}, Tikhonov g(λ)=1/(1+μλ)g(\lambda)=1/(1+\mu\lambda) for μ>0\mu>0, high-pass 1−e−tλ1-e^{-t\lambda} 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 ∥z−x∥22+μz⊤Lz\norm{z-x}_2^2+\mu z\T Lz: differentiation and setting the result to zero gives (I+μL)z=x(I+\mu L)z=x.

A dense decomposition generally costs O(n3)O(n^3) and storing UU costs O(n2)O(n^2). 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.

InteractiveDesign a response
0λmax1
  • Target response
  • Chebyshev
12345678

Azul y rosa son signos de la señal exacta. La cota de error en norma es el error máximo espectral multiplicado por la norma de la entrada; el soporte de un impulso no rebasa K saltos.

1.0
0.4
0.0
4
1
Signal L2 error0.00584
Maximum spectral error0.00445
Impulse radius2
Three controls define a piecewise-linear response; the dashed line is its Chebyshev approximation. Axis points are eigenvalues. The network shows the exactly filtered signal, while radius is calculated separately for an impulse using the polynomial.

A filter given by the same function g(λ)g(\lambda) 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 (1,0)(1,0) in one basis. Their componentwise product is (1,0)(1,0). 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 (1,0)(1,0). Multiplying the entire eigenspace by the same scalar g(λ)g(\lambda) commutes with any rotation. That invariance distinguishes a matrix function g(L)g(L) from an arbitrary table of coefficients per eigenvector.

Polynomials and locality

A local polynomial filter pK(L)=∑k=0KckLkp_K(L)=\sum_{k=0}^K c_k L^k uses at most KK hops. To prove this, note that a nonzero off-diagonal entry of LL corresponds to an edge; a diagonal entry permits remaining at the node. Each term of (Lk)ij(L^k)_{ij} is a product of kk entries and, if nonzero, describes a sequence of at most kk edges between ii and jj. If dist⁡(i,j)>k\operatorname{dist}(i,j)>k, no such sequence exists and the entry is zero. Summing degrees up to KK likewise introduces no dependency beyond KK hops.

InteractiveAn impulse and K hops
12345678
  • Positive
  • Negative
  • Zero
L^K δ = [1.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00]
1
0
Nonzero nodes1
Maximum nonzero distance0
Exactly L raised to K is applied to an impulse. The dashed border marks nodes at distance at most K; color indicates nonzero support. Locality gives an inclusion and does not promise every node inside the radius remains nonzero after possible cancellations.

The converse does not automatically hold for every local operator: a matrix with limited support need not be a polynomial in LL. Nor is a heat filter generally strictly KK-local for finite KK: its exponential contains powers of every degree, although distant contributions may be small.

Chebyshev without eigenvectors

The Chebyshev approximation rescales the spectrum to [−1,1][-1,1]. With a safe bound λmax⁡≥λn>0\lambda_{\max}\ge\lambda_n>0, define L~=2L/λmax⁡−I\widetilde L=2L/\lambda_{\max}-I. For T0(z)=1T_0(z)=1, T1(z)=zT_1(z)=z and Tk(z)=2zTk−1(z)−Tk−2(z)T_k(z)=2zT_{k-1}(z)-T_{k-2}(z),

pK(L)x=∑k=0KckTk(L~)x,t0=x,t1=L~x,tk=2L~tk−1−tk−2.p_K(L)x=\sum_{k=0}^K c_k T_k(\widetilde L)x, \quad t_0=x,\quad t_1=\widetilde Lx,\quad t_k=2\widetilde L t_{k-1}-t_{k-2}.

Under this convention c0c_0 already includes half the constant coefficient used by some libraries. Applying degree K≥1K\ge1 requires KK sparse matrix-vector products and memory for a few vectors of length nn. If λn\lambda_n is underestimated, the rescaled spectrum can leave [−1,1][-1,1] and TkT_k 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, 2dmax⁡2d_{\max} is a simple upper bound: each Gershgorin disc is centered at did_i with radius did_i. It is not always tight. The recurrence preserves locality because Tk(L~)T_k(\widetilde L) is a degree-kk polynomial in LL; 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 sup⁡λ∈[0,λmax⁡]∣g(λ)−pK(λ)∣≤ϵ\sup_{\lambda\in[0,\lambda_{\max}]}|g(\lambda)-p_K(\lambda)|\le\epsilon, then ∥g(L)x−pK(L)x∥2≤ϵ∥x∥2\norm{g(L)x-p_K(L)x}_2\le\epsilon\norm{x}_2. 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 KK approximates every function equally well.

Wavelets and sampling

A family of spectral wavelets can use ψt,i=g(tL)δi\psi_{t,i}=g(tL)\delta_i, with a window gg that vanishes at zero frequency. For example g(s)=se−sg(s)=s e^{-s} responds to differences at a given scale. Coefficients ⟨ψt,i,x⟩\langle \psi_{t,i},x\rangle 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 x=UBax=U_B a is restricted to a band subspace of dimension rr, observing xx on a set SS permits unique reconstruction exactly when UB[S,:]U_B[S,:] has rank rr. At least rr 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.

[ ]Chebyshev and the heat boundBrowser
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 z=tλmax⁡/2z=t\lambda_{\max}/2, exact heat coefficients are c0=e−zI0(z)c_0=e^{-z}I_0(z) and ck=2e−z(−1)kIk(z)c_k=2e^{-z}(-1)^k I_k(z) for k≥1k\ge1. The Bessel series gives Ik(z)≤ez2/4(z/2)k/k!I_k(z)\le e^{z^2/4}(z/2)^k/k! for z≥0z\ge0. If z/[2(K+2)]<1z/[2(K+2)]<1, the tail from K+1K+1 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.

[ ]Filtering and cost comparisonBrowser
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 L2L^2 error was approximately 1.6×10−71.6\times10^{-7} and the calculated bound 5.5×10−75.5\times10^{-7}. 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.

[ ]Wavelet on an injected anomalyBrowser
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.

[ ]Reconstruction from samplesBrowser
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 c0/2c_0/2; before comparing with this lesson’s convention, divide that coefficient by two. The spectral bound must be the same in both paths.

[ ]Coefficients and filters versus PyGSPLocal GPU
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)))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In one local execution with PyGSP 0.6.1, the maximum coefficient difference was 5.6×10−175.6\times10^{-17} and the recurrence difference 2.2×10−162.2\times10^{-16}. The L2L^2 error against the exact filter was approximately 2.3×10−72.3\times10^{-7}. This check compares conventions on this grid and these parameters; it does not imply degree 8 suffices for every filter.

Exercises

Proof
Prove: If the distance between i and j exceeds k, then (L^k)_ij = 0.
0
L is an undirected graph Laplacian; its off-diagonal entries can be nonzero only for edges.

Step 1 of 2. What does a nonzero product in the expansion of (L^k)_ij represent?

Proof
Prove: The GFT of a cycle matches the DFT up to basis choice in repeated eigenspaces.
0
On C_n the neighbors of j are j−1 and j+1, with indices modulo n.

Step 1 of 2. How does a shift transform mode exp(2πikj/n)?

Numeric
In an undirected graph with one million edges stored in both directions, how many multiplications by off-diagonal entries are performed when applying a degree-20 Chebyshev polynomial to a vector? Ignore diagonal and vector operations.
Numeric
For n = 10 000, what is n³, the cubic scale of general dense diagonalization?
Quiz
Why can't one simply copy a separate parameter per eigenvector from one graph to another?
Code
Implement cheb_filter(L, x, coeffs, lmax) for lmax > 0 and a nonempty list of coefficients, with c0 already halved if appropriate. Apply the recurrence using K products by L without diagonalizing; L may be dense or sparse.
import numpy as np
def cheb_filter(L, x, coeffs, lmax):
  pass
Shift+Enter to run

Key ideas

Key idea
The GFT expresses a signal in Laplacian modes, and a scalar function of the spectrum defines a filter independent of the basis within each eigenspace.

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.