Independent component analysis
Independent component analysis, identifiability, whitening and separation algorithms.
After this lesson you can
- Explain blind source separation and its unavoidable ambiguities.
- Derive ICA identifiability and the role of non-Gaussianity.
- Apply whitening and independent-component algorithms.
- Evaluate separation and understand practical limitations.
Before you start
- 12Principal component analysisFactor rotationLinear Gaussian latent variable model
- 04WhiteningMoment generating functionCumulant generating functionCentral limit theoremChange of variables for densities
- 07Differential entropyMaximum entropy property of the Gaussian
- 03Jacobian determinant
- 06Newton's method
Motivation: signals arriving mixed together
At a party three people speak and three microphones are placed around the room. Each microphone records a weighted sum of the voices, with weights depending on distance. You want the voices, not sums, and know neither weights nor voices. This is the cocktail party problem, and surprisingly one assumption about the voices makes it solvable.
The same setup appears in very different places:
- EEG and MEG. Each scalp electrode records a linear, instantaneous superposition (at EEG frequencies tissue conduction is almost static) of brain sources and artifacts: blinks, eye movements, muscle activity, electrical mains. Makeig, Bell, Jung and Sejnowski (1996) applied this method to EEG, and Jung et al. (2000) proposed artifact removal, now its most common use: separate components, discard blink components and reconstruct without them.
- Markets. Many assets’ returns move together because they respond to a few common shocks. If shocks are independent and heavy-tailed, one can try to recover them as independent components; Back and Weigend (1997) were among the first to apply this to stock returns. In causality, LiNGAM uses the same idea to orient causal graph arrows when noise is non-Gaussian (see the causality module).
The previous lesson ended at an impasse: factor analysis identifies the factors’ subspace, but not the factors, because every rotation gives the same likelihood. Independent component analysis (ICA) escapes through one idea: require components to be independent and non-Gaussian. Before formalizing anything, listen.
All three outputs return almost perfectly (correlation above 0.99 with sources), but in a different order and with some signs flipped. This is not an algorithm defect: no method can know which voice was “first.” When two microphones record the same thing, however, nothing can be done: three sources do not fit into two distinct mixtures. These observations form the theory’s skeleton.
The model and its ambiguities
Three comments on assumptions. First, mean is no problem: is subtracted initially and restored at the end, so data are centered. Second, the model treats observations as an iid sample of : time order plays no role, and shuffling instants does not change the solution (hence the widget estimates from permuted instants). Third, there is no noise: is exactly . Variants with noise, more sources than sensors or temporal structure appear at the end.
On data orientation: the course convention is one observation per row, , making the model . Cells use the ICA literature orientation, one row per sensor and one column per time (), stated in each.
What the model cannot know
If is invertible diagonal and a permutation matrix,
and also has independent components: the same sources reordered and rescaled. Both pairs and generate exactly the same distribution of , so no method, with any amount of data, can distinguish them. At best, the global matrix is a scaled permutation:
This gives three ambiguities:
- Scale. Multiplying a source by and dividing its column of by changes nothing. Fix it by convention: .
- Sign. What remains of scaling after that convention (). If useful, fix it by another convention: for example the largest absolute entry in each column of is positive, or each source has positive skewness.
- Order. Sources have no natural order. Unlike PCA, where variance orders components, here all have variance 1 by convention. They can be ordered afterward by any criterion (non-Gaussianity, column norm of before normalization), but the model prefers none.
Conventions resolve scale and sign as presentation issues; permutation requires external information (knowing whose voice a source is). None prevents practical use: removing a blink from EEG only requires identifying which component is the blink.
Measuring success: the Amari index
If the goal is shaped like a scaled permutation, error should measure how far is from that form without penalizing unavoidable ambiguities. The Amari index (Amari, Cichocki and Yang, 1996) does so row by row and column by column:
Each parenthesis is 0 if its row (or column) has one nonzero entry, and if all are equal in absolute value. Hence:
- , with if and only if each row and column of has exactly one nonzero entry, namely ; and if all entries have the same absolute value.
- It is invariant to permuting rows of or changing their signs, likewise columns of : order and sign are not penalized. Scale needs care: zero is preserved by row rescaling (a remains one), but outside perfect solutions, rescaling a row changes column ratios and the index. Thus calculate with unit-variance normalized outputs, the scale convention.
- In two dimensions it has a geometric reading: for rotation angle , because each row and column contributes , four terms divided by . Index 0.026 is an error of .
Normalization by , placing the index in , is common; other works use the unnormalized sum or squared entries. Always compare using the same convention.
amari_index(W, A), accepting estimated separation matrix W and mixing matrix A (both ) and returning the normalized Amari index of , a float in . Tests check it is 0 for perfect separation in any order and scale, invariant to permutations and sign changes of rows of and columns of , equals for a plane rotation of , and equals 1 when all entries are equal.import numpy as np
def amari_index(W, A):
P = np.abs(np.asarray(W, float) @ np.asarray(A, float))
d = P.shape[0]
# tu código: cociente de cada |p_ij| por el máximo de su fila y de su columna,
# sumas menos 1 y normalización por 2 d (d - 1)
return 0.0Why uncorrelated is not enough
Almost every ICA algorithm first whitens data: linearly transforms them to identity covariance. With , common choices are PCA whitening and symmetric (ZCA) whitening . Any with works, and all differ by left multiplication by an orthogonal matrix.
Proof
. If must also have identity covariance, . Orthogonal group has dimension .
∎Whitening therefore solves half the problem: in two dimensions four unknown numbers become one angle. But that angle cannot be fixed by second-order moments: for any orthogonal , retains identity covariance, uncorrelated unit-variance components. Uncorrelatedness is all PCA and Gaussian factor analysis know to require, and here it distinguishes nothing.
What does independence add? It examines higher-order moments. If are independent, ; uncorrelated but dependent variables can violate this. For two iid unit-variance sources with excess kurtosis (defined below) rotated by angle , expanding the product gives
which equals 1 only at angles aligning with sources (or if ). The cell checks this with two uniform sources whose cloud is a square:
import numpy as np
rng = np.random.default_rng(1)
n = 20_000
S = rng.uniform(-np.sqrt(3), np.sqrt(3), size=(2, n)) # dos fuentes uniformes de varianza 1
A = np.array([[1.0, 0.8], [0.3, 1.0]])
X = A @ S # una fila por sensor
Xc = X - X.mean(axis=1, keepdims=True)
C = Xc @ Xc.T / n
lam, E = np.linalg.eigh(C)
V = E @ np.diag(lam ** -0.5) @ E.T # blanqueado simétrico C^(-1/2)
Z = V @ Xc
Q = V @ A
th = np.degrees(np.arctan2(Q[1, 0], Q[0, 0]))
print("Cov(z):\n", np.round(Z @ Z.T / n, 4))
print("Q Q^T:\n", np.round(Q @ Q.T, 3))
print(f"la primera columna de Q forma {th:.1f} grados con el eje: los datos blanqueados son el cuadrado de las fuentes girado")
print(f"E[z1² z2²] = {np.mean(Z[0]**2 * Z[1]**2):.3f} frente a E[s1² s2²] = {np.mean(S[0]**2 * S[1]**2):.3f}")
for ang in (0, 15, 30, 45):
c, s = np.cos(np.radians(ang)), np.sin(np.radians(ang))
Y = np.array([[c, s], [-s, c]]) @ S # fuentes giradas ang grados
print(f"giro de {ang:2d}°: corr(y1, y2) = {np.corrcoef(Y)[0, 1]:+.3f} E[y1² y2²] = {np.mean(Y[0]**2 * Y[1]**2):.3f}")Output tells the whole story. Covariance of is identity and so is , up to sampling error in covariance of . Rotated sources remain uncorrelated at any angle, but falls from 1 to 0.4 between and : rotated projections depend on one another, detected by the fourth-order statistic. ICA searches for the rotation where dependence disappears.
Identifiability: at most one Gaussian source
There is a case where rotation can never be found: Gaussian sources. If , its density depends only on norm, so has the same distribution for every orthogonal (you prove this step by step in the first exercise). Then with also standard Gaussian, and every explains the data equally well. The whitened cloud is a disk, and a disk has no preferred axes.
This is exactly factor analysis’s rotational ambiguity, not coincidentally: the linear Gaussian latent-variable model assumes Gaussian factors. Viewed this way, ICA is noiseless factor analysis with non-Gaussian factors, and non-Gaussianity breaks the symmetry. The precise result is due to Comon (1994), based on a classical normal-characterization theorem.
That is, two linear combinations of independent variables sharing a non-Gaussian variable are never independent. This gives a short identifiability proof.
Proof
Let be invertible, so . Call the Gaussian source’s index, if any.
- If two rows had nonzero entries in the same column , independence of and and Darmois-Skitovich would force to be Gaussian, contrary to assumption. Thus each column has at most one nonzero entry, and invertibility of makes it exactly one.
- These columns have their nonzero entries in different rows: if two shared a row, they would be proportional to the same canonical vector and singular. They occupy rows, leaving row zero outside column ; since it cannot be zero, .
- It remains to show column has no other nonzero entries. If for some , then because other sources do not appear in ; correlated variables are not independent. Contradiction.
Each row and column of has exactly one nonzero entry: . If there is no Gaussian source, step 1 applies to every column and the rest is the same.
∎Notice what this says and does not say. Pairwise independence of outputs suffices for full independence: the algorithm can optimize a pairwise measure. “At most one Gaussian” is necessary and precise: with two or more Gaussian sources, non-Gaussian sources remain identifiable and so does the subspace spanned by Gaussian ones, but not a basis inside it. The theorem concerns the distribution: the solution is unique with unlimited data, not how much data is needed to find it.
import numpy as np
import warnings
from sklearn.decomposition import FastICA
def amari(P):
P = np.abs(np.asarray(P, float))
d = P.shape[0]
filas = (P / P.max(axis=1, keepdims=True)).sum(axis=1) - 1
columnas = (P / P.max(axis=0, keepdims=True)).sum(axis=0) - 1
return (filas.sum() + columnas.sum()) / (2 * d * (d - 1))
n = 5000
A = np.array([[1.0, 0.8], [0.3, 1.0]])
res = {"Laplace": [], "gaussianas": []}
for r in range(6):
g = np.random.default_rng(10 + r) # una muestra nueva del mismo modelo en cada vuelta
for nombre, S in (("Laplace", g.laplace(size=(2, n)) / np.sqrt(2)), ("gaussianas", g.normal(size=(2, n)))):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
ica = FastICA(n_components=2, whiten="unit-variance", random_state=0, max_iter=1000).fit((A @ S).T)
res[nombre].append(amari(ica.components_ @ A)) # components_ es la W completa (incluye el blanqueado)
for nombre, v in res.items():
print(f"{nombre:10s} índice de Amari:", " ".join(f"{a:.3f}" for a in v),
" error angular:", " ".join(f"{np.degrees(np.arctan(a)):4.1f}°" for a in v))(Scikit-learn uses one row per observation, hence the transpose.) With Laplace sources, six samples give Amari indices between 0.002 and 0.016, errors under one degree due to finite sample size that shrink with more data. With Gaussian sources each sample leads to a different rotation, with errors between and unrelated to : finite-sample contrast has spurious extrema from sampling noise, and the algorithm stops at one. More data flatten these extrema but reveal no good one: the estimate converges to nothing.
Mixing makes distributions more Gaussian
What criterion finds the right rotation? Intuition comes from the central limit theorem: a sum of many independent variables is approximately Gaussian. A mixture (with ) sums independent sources and is more Gaussian than each one, except when has one nonzero entry, meaning is a source. Maximizing non-Gaussianity of retraces the path.
This can be made exact with cumulants. The cumulant-generating function of an independent sum is additive, , so order- cumulant satisfies . With , variance of is 1 and its fourth cumulant is excess kurtosis:
Proof
The formula is cumulant additivity. For the bound, and , with equality in the last inequality only if at most one is nonzero (cross products must vanish).
∎In two dimensions, with two sources of equal kurtosis , a projection at angle from the first has kurtosis : source kurtosis at and , half at . You will see this in the second widget. First, inspect the many-source limit:
Kurtosis falls as and skewness as , so Gaussianization is slower for asymmetric sources. Read the theorem carefully: mixture kurtosis does not exceed the largest source kurtosis, not that every mixture has less kurtosis than each source. Mix a highly non-Gaussian source with an almost Gaussian one and the mixture is less Gaussian than the latter. The bound guarantees the maximum occurs at a source. Entropy rather than kurtosis gives the same conclusion for any law with a density: the entropy power inequality in Lieb’s (1978) form says if , hence the negentropy below satisfies .
Measures of non-Gaussianity
We need a number expressing distance from Gaussianity. Two families dominate practice, a choice between simplicity and robustness. All are non-Gaussianity measures of standardized (mean 0, variance 1), what projection produces with .
Kurtosis
It is 0 for a Gaussian. Laws with are sub-Gaussian: light tails, spread-out mass, such as uniform or sinusoidal. Those with are super-Gaussian: sharp peak and heavy tails, like Laplace () or a sparse signal almost always zero, such as voice or cocktail-party impulsive noise. Jensen’s inequality gives , so , equality only for symmetric binary . As a cumulant it is additive for mixtures, enabling the theorem, and its sample version costs one pass.
Its drawback is serious: dependence on . One observation five standard deviations out contributes to the sum of fourth powers, as much as hundreds of normal observations. Sample kurtosis measures outliers more than distribution shape, and its variance depends on the eighth moment.
Negentropy
The “correct” measure comes from information theory. Among densities with fixed variance, Gaussian has maximum differential entropy (maximum entropy principle). Negentropy
is therefore nonnegative, zero only when is Gaussian, and unchanged if the variable is rescaled. It is optimal in a precise sense (soon you will see minimizing mutual information is equivalent to maximizing summed negentropies), but estimating requires estimating a density.
Practical approximations replace density with a few moments. The classic Gram-Charlier expansion (Jones and Sibson, 1987) is
inheriting kurtosis fragility. Hyvärinen (1998) proposed replacing polynomials with slowly growing functions: for nonquadratic ,
with two recommended choices (Hyvärinen and Oja, 2000):
The approximation fits the maximum-entropy density compatible with , and is good when is not too far from Gaussian. behaves as near 0 and far away: an outlier weighs linearly, not to the fourth power. Two rigor warnings. is an approximation, not a characterization: non-Gaussian laws can have for a particular , invisible to that . And constant must be calculated: for it is exactly , while has no simple closed form, so the cell integrates it.
import numpy as np
from scipy import integrate, stats
def logcosh(u):
a = np.abs(u)
return a + np.log1p(np.exp(-2 * a)) - np.log(2) # log cosh estable para |u| grande
E_G_nu = integrate.quad(lambda u: logcosh(u) * stats.norm.pdf(u), -40, 40)[0]
print(f"E[log cosh(nu)], nu ~ N(0, 1): {E_G_nu:.6f}\n")
def estandariza(y):
return (y - y.mean()) / y.std()
def curtosis(y):
return np.mean(estandariza(y) ** 4) - 3
def J_G(y):
return (np.mean(logcosh(estandariza(y))) - E_G_nu) ** 2
rng = np.random.default_rng(0)
n = 200_000
leyes = {
"gaussiana": rng.normal(size=n),
"Laplace": rng.laplace(size=n),
"binaria ±1": rng.choice([-1.0, 1.0], n),
"seno, fase al azar": np.sin(2 * np.pi * rng.uniform(size=n)),
"impulsiva, p = 0.03": rng.normal(size=n) * (rng.uniform(size=n) < 0.03),
}
for nombre, y in leyes.items():
print(f"{nombre:20s} curtosis {curtosis(y):7.3f} J_G x 1000 {1e3 * J_G(y):7.3f}")
y = rng.laplace(size=1000)
y_atipico = y.copy()
y_atipico[0] = 12 * y.std() # un único dato a 12 desviaciones típicas
print()
for nombre, v in [("1000 datos de Laplace", y), ("los mismos con un atípico", y_atipico)]:
print(f"{nombre:26s} curtosis {curtosis(v):7.3f} J_G x 1000 {1e3 * J_G(v):7.3f}")The table confirms theoretical values (kurtosis 0, 3, and for Gaussian, Laplace, binary and sinusoidal; the last because and ) and shows impulsive noise, almost always zero, is extremely super-Gaussian. Note orders differently from kurtosis: binary has over twice Laplace’s with smaller absolute kurtosis (2 versus 3), while sinusoid and Laplace, with opposite kurtosis signs, have nearly equal . These measure different distances from Gaussianity; either works for ICA if nonzero on sources. The last part shows kurtosis fragility twice. With 1000 Laplace observations, sample kurtosis is 1.7, far from theoretical 3: its estimate is highly variable because it depends on tails. One observation twelve standard deviations out multiplies it almost tenfold (to 16.6), while grows less than fourfold: it also changes because non-Gaussian signal is small with a thousand observations, but the outlier enters by absolute value rather than fourth power. Ultimately what matters is whether it changes the estimated direction, measured in the lab.
With these two measures you can search for rotation by hand.
With uniform sources the whitened cloud is a rotated square, whose axes project to the sources: kurtosis reaches its minimum there (they are sub-Gaussian) and its maximum. At kurtosis halves as predicted by , and the histogram looks more bell-shaped. With Laplace sources kurtosis changes sign but the story is the same, and , a square, peaks in the same place without knowing the sign. With one Gaussian, the maximum still marks the non-Gaussian source and the Gaussian is the orthogonal direction. With two Gaussians both curves are flat except for sample noise: no direction exists to find.
FastICA: a Newton method without a step size
To estimate one component, optimize on the unit sphere: maximize if the target has , minimize otherwise (maximizing does both). Projected gradient ascent is possible, but requires choosing step size, knowing the sign and waiting. FastICA (Hyvärinen and Oja, 1997; Hyvärinen, 1999) uses whitening for something better.
At an optimum with constraint , Lagrange conditions are
with . Solving by Newton’s method requires Jacobian , a matrix to invert each step. The key observation: since is whitened, approximate that Jacobian by a multiple of identity; Newton’s step then simplifies to fixed-point iteration
which is one-unit FastICA. Derivation details (what is approximated and why the Newton factor disappears) are in exercise 2. Iterate until is within tolerance of 1: absolute value handles sign oscillation of without direction change.
With (kurtosis), iteration is ; with , and ; with , and . Hyvärinen and Oja (2000) summarize its properties under the ICA model: convergence is cubic, or at least quadratic (proof in Hyvärinen, 1999), versus linear convergence of gradient methods; no step size needs choosing; and any nonquadratic finds sources of almost any non-Gaussian law, sub- or super-Gaussian, without specifying which.
With uniform sources and , fixed point drops from about to below degrees in four steps and continues to rounding; gradient with remains over two degrees away after thirty. Raising does not always fix gradient: with Laplace and , or kurtosis and any for uniform sources, it overshoots and ends in the intermediate direction, from sources, also a stationary contrast point. Fixed point has no such problem in any case. The plot shows a detail absent from asymptotic theory: after the first step, fixed-point error is neither squared nor cubed, but multiplied by an almost constant factor each step (about 0.025 for uniform with , and 0.13 for Laplace with kurtosis; the widget calculates it). The convergence proof uses exact expectations under the model, where cross moments of independent sources such as vanish along with the first-order error term. In finite samples those averages are not zero but sampling fluctuations, so final convergence becomes linear with a factor expected to shrink as grows. The cell measures this by numerically differentiating the fixed-point map at its fixed point, giving exactly that factor:
import numpy as np
def factor_lineal(n, rep):
rng = np.random.default_rng(rep)
S = rng.uniform(-np.sqrt(3), np.sqrt(3), (2, n)) # dos uniformes, como en el widget
X = np.array([[1.0, 0.6], [0.2, 1.0]]) @ S
X -= X.mean(axis=1, keepdims=True)
lam, E = np.linalg.eigh(X @ X.T / n)
Z = E @ np.diag(lam ** -0.5) @ E.T @ X
def paso(a): # punto fijo con log cosh, en ángulos
w = np.array([np.cos(a), np.sin(a)])
t = np.tanh(w @ Z)
w2 = (Z * t).mean(axis=1) - (1 - t * t).mean() * w
return np.arctan2(w2[1], w2[0])
a = 1.2
for _ in range(20):
a = paso(a)
h = 1e-4
d = (paso(a + h) - paso(a - h) + np.pi) % (2 * np.pi) - np.pi # diferencia de ángulos módulo 2 pi
d = (d + np.pi / 2) % np.pi - np.pi / 2 # módulo pi: el signo de w no importa
return abs(d / (2 * h))
for n in (1000, 10_000, 100_000):
f = [factor_lineal(n, r) for r in range(4)]
print(f"n = {n:6d}: factor por paso en 4 muestras = {np.round(f, 4)} mediana {np.median(f):.4f}")The factor is small and decreases with sample size, although it varies greatly between samples: its median falls from 0.017 with 1000 observations to 0.004 with 100000. In practice the difference from asymptotic convergence is one or two extra steps.
Multiple components: deflation and symmetric orthogonalization
To estimate multiple rows of , prevent all from converging to the same source. Since is orthogonal, target directions are orthonormal, enforced in two ways:
- Deflation: estimate one by one; after every fixed-point step for unit , subtract projection onto previous ones, (Gram-Schmidt), and normalize. This is classical projection pursuit. Its drawback is inheriting earlier estimation errors: each new component is sought in the orthogonal complement of previous, already slightly deviated ones.
- Symmetric orthogonalization: take a fixed-point step for all rows together, then replace by
the orthogonal factor of ‘s polar decomposition and therefore the closest orthogonal matrix to in Frobenius norm. No component is privileged, errors do not accumulate, and the step parallelizes.
With whitened data, full separation matrix is and estimated mixture is its inverse .
Lab: FastICA from scratch
The following cells implement the full algorithm in NumPy and compare with scikit-learn. Signals are the cocktail-party sources, regenerated here in NumPy (not the widget’s samples, which use its own generator). Matrices use orientation: one row per sensor.
import numpy as np
fs = 8000
t = np.arange(12_000) / fs
rng = np.random.default_rng(7)
s1 = np.sin(2 * np.pi * 330 * t) # tono
s2 = 2 * ((110 * t + 0.25) % 1) - 1 # diente de sierra
s3 = rng.normal(size=t.size) * (rng.uniform(size=t.size) < 0.03) # ruido impulsivo
S = np.vstack([s1, s2, s3])
S = (S - S.mean(axis=1, keepdims=True)) / S.std(axis=1, keepdims=True)
A = np.array([[1.0, 0.5, 0.4], [0.6, 1.0, -0.3], [-0.4, 0.5, 1.0]])
X = A @ S
def curt(Y):
Yc = Y - Y.mean(axis=1, keepdims=True)
return (Yc ** 4).mean(axis=1) / Yc.var(axis=1) ** 2 - 3
def blanquear(X):
"""Centra y blanquea con PCA: z = Lambda^(-1/2) E^T (x - mu). Devuelve z, V y mu."""
mu = X.mean(axis=1, keepdims=True)
Xc = X - mu
lam, E = np.linalg.eigh(Xc @ Xc.T / Xc.shape[1])
V = np.diag(lam ** -0.5) @ E.T
return V @ Xc, V, mu
def amari(P):
P = np.abs(np.asarray(P, float))
d = P.shape[0]
filas = (P / P.max(axis=1, keepdims=True)).sum(axis=1) - 1
columnas = (P / P.max(axis=0, keepdims=True)).sum(axis=0) - 1
return (filas.sum() + columnas.sum()) / (2 * d * (d - 1))
Z, V, mu = blanquear(X)
print("curtosis de las fuentes:", np.round(curt(S), 2))
print("curtosis de las mezclas:", np.round(curt(X), 2))
print("covarianza de z:\n", np.round(Z @ Z.T / Z.shape[1], 6))Source kurtoses are (tone), (sawtooth) and almost 100 (impulses); mixtures are , and . The impulse-dominated mixture halves, and the other two are closer to zero than tone and sawtooth, one with positive sign from received impulsive noise. No mixture exceeds the largest absolute source kurtosis: the mixture-kurtosis theorem in action.
TANH = (np.tanh, lambda u: 1 - np.tanh(u) ** 2) # g y g' para G = log cosh
def fastica_deflacion(Z, G=TANH, max_iter=200, tol=1e-10, semilla=0):
g, gp = G
d, n = Z.shape
rng = np.random.default_rng(semilla)
W = np.zeros((d, d))
iteraciones = []
for p in range(d):
w = rng.normal(size=d)
w -= W[:p].T @ (W[:p] @ w)
w /= np.linalg.norm(w)
for it in range(1, max_iter + 1):
y = w @ Z
w_nuevo = (Z * g(y)).mean(axis=1) - gp(y).mean() * w # paso de punto fijo
w_nuevo -= W[:p].T @ (W[:p] @ w_nuevo) # Gram-Schmidt contra las ya halladas
w_nuevo /= np.linalg.norm(w_nuevo)
cambio = abs(abs(w_nuevo @ w) - 1)
w = w_nuevo
if cambio < tol:
break
W[p] = w
iteraciones.append(it)
return W, iteraciones
W_def, it_def = fastica_deflacion(Z)
print("iteraciones por componente:", it_def)
print(f"índice de Amari de W V A: {amari(W_def @ V @ A):.4f}")
print("P = W V A:\n", np.round(W_def @ V @ A, 3))Three components in a handful of iterations each (the last needs almost none: in three dimensions, after fixing two orthonormal directions the third is determined up to sign). Matrix is a signed permutation, with misplaced entries of order : exactly the form allowed by the identifiability theorem, with under the unit-variance convention.
from sklearn.decomposition import FastICA
def orto_simetrica(W):
lam, E = np.linalg.eigh(W @ W.T)
return E @ np.diag(lam ** -0.5) @ E.T @ W # (W W^T)^(-1/2) W
def fastica_simetrica(Z, G=TANH, max_iter=200, tol=1e-10, semilla=0):
g, gp = G
d, n = Z.shape
W = orto_simetrica(np.random.default_rng(semilla).normal(size=(d, d)))
for it in range(1, max_iter + 1):
Y = W @ Z
W_nuevo = orto_simetrica(g(Y) @ Z.T / n - np.diag(gp(Y).mean(axis=1)) @ W)
cambio = np.max(np.abs(np.abs(np.sum(W_nuevo * W, axis=1)) - 1))
W = W_nuevo
if cambio < tol:
break
return W, it
W_sim, it_sim = fastica_simetrica(Z)
print(f"simétrica: {it_sim} iteraciones, índice de Amari {amari(W_sim @ V @ A):.4f}")
ica = FastICA(n_components=3, algorithm="parallel", fun="logcosh", whiten="unit-variance",
random_state=0, tol=1e-10, max_iter=1000)
S_sk = ica.fit_transform(X.T).T # scikit-learn: una fila por observación
print(f"scikit-learn: {ica.n_iter_} iteraciones, índice de Amari {amari(ica.components_ @ A):.4f}")
Y_sim = W_sim @ Z
C = np.corrcoef(np.vstack([Y_sim, S_sk]))[:3, 3:]
print("|corr| entre nuestras salidas y las de scikit-learn:\n", np.round(np.abs(C), 4))The symmetric version and scikit-learn reach the same point: identical Amari index to four digits and outputs with absolute correlation 1 in a different order (the table is a permutation). This is no accident: with algorithm="parallel" scikit-learn executes the same symmetric iteration, and both reach the same sample fixed point from different starts.
How much data is needed, and how much does deflation lose? The next two cells measure it. The first repeats separation on random signal subsets; the second compares deflation and symmetric methods on 20 six-source problems (three uniform and three Laplace, with random Gaussian mixtures and 1000 samples).
for m in [100, 200, 500, 1000, 3000, 12_000]:
errores = []
for r in range(20):
idx = np.random.default_rng(100 + r).choice(X.shape[1], m, replace=False)
Zm, Vm, _ = blanquear(X[:, idx])
Wm, _ = fastica_simetrica(Zm, semilla=r)
errores.append(amari(Wm @ Vm @ A))
print(f"n = {m:6d}: índice de Amari mediano {np.median(errores):.4f}")res = {"deflación": [], "simétrica": []}
for r in range(20):
g = np.random.default_rng(1000 + r)
S6 = np.vstack([g.laplace(size=1000) / np.sqrt(2) if i % 2 else g.uniform(-np.sqrt(3), np.sqrt(3), 1000)
for i in range(6)])
A6 = g.normal(size=(6, 6))
Z6, V6, _ = blanquear(A6 @ S6)
res["deflación"].append(amari(fastica_deflacion(Z6, semilla=r)[0] @ V6 @ A6))
res["simétrica"].append(amari(fastica_simetrica(Z6, semilla=r)[0] @ V6 @ A6))
for k, v in res.items():
print(f"{k:10s} índice de Amari medio {np.mean(v):.4f} mediano {np.median(v):.4f}")
print(f"la simétrica es mejor en {sum(a > b for a, b in zip(res['deflación'], res['simétrica']))} de 20 problemas")Error decreases steadily with : at 100 samples the index is about 0.04, and at 12000 below 0.002. With sources this non-Gaussian, a hundred samples already permit usable separation; nearly Gaussian sources need many more because the algorithm’s signal is small relative to moment-sampling error. Symmetric orthogonalization yields lower mean error than deflation on these problems, as error accumulation predicts.
A robust contrast
The lab’s last cell tests the kurtosis warning. Two uniform sources, 2000 samples and a few outliers at six times the data standard deviation in random directions; separate with symmetric FastICA and three contrasts: kurtosis (), and .
CUBO = (lambda u: u ** 3, lambda u: 3 * u ** 2) # G = u^4/4 (curtosis)
GAUSS = (lambda u: u * np.exp(-u ** 2 / 2), lambda u: (1 - u ** 2) * np.exp(-u ** 2 / 2))
A2 = np.array([[1.0, 0.8], [0.3, 1.0]])
print("atípicos curtosis log cosh G2 (índice de Amari mediano en 10 repeticiones)")
for k in [0, 1, 3, 10]:
res = []
for r in range(10):
g = np.random.default_rng(50 + r)
X2 = A2 @ g.uniform(-np.sqrt(3), np.sqrt(3), (2, 2000))
ang = g.uniform(0, 2 * np.pi, k)
X2[:, :k] = 6 * X2.std() * np.vstack([np.cos(ang), np.sin(ang)])
Z2, V2, _ = blanquear(X2)
res.append([amari(fastica_simetrica(Z2, G)[0] @ V2 @ A2) for G in (CUBO, TANH, GAUSS)])
m = np.median(res, axis=0)
print(f"{k:5d} {m[0]:.3f} {m[1]:.3f} {m[2]:.3f}")Without outliers all three contrasts separate well. With one outlier among 2000 observations, kurtosis already fails (index 0.45, about error in two dimensions), while and remain below 0.02. With ten such extreme outliers, also yields and only , which almost ignores large values because , holds up (0.088, about ). This is Hyvärinen and Oja’s (2000) recommendation: for general use, with outliers or very super-Gaussian sources, kurtosis only for sub-Gaussian sources and clean data.
Maximum likelihood, Infomax and mutual information
FastICA was motivated by non-Gaussianity. Two other classic routes lead to ICA, and all three are the same objective viewed from different sides.
Maximum likelihood
If source densities were known, model with would give, by change of variables (the Jacobian of is ),
with row of . Mean sample log-likelihood is
The term prevents trivial solution and forces rows not to repeat. With a large sample, tends to its expectation, which decomposes revealingly.
The last line (Cardoso, 1998) says three things. With exact models , maximizing likelihood exactly minimizes output mutual information. Otherwise a marginal-mismatch term is added, potentially moving the maximum. And the absolute mutual-information minimum (zero) is attained only at separation, by identifiability.
Mutual information and negentropy
Mutual information can also be written with entropies: , and since , . With whitened data and orthogonal , and each has variance 1, so :
Minimizing mutual information between whitened outputs equals maximizing their summed negentropies. This is Comon’s (1994) contrast and FastICA’s justification: each unit maximizes (an approximation of) its negentropy, with orthogonality doing the rest.
Infomax
Bell and Sejnowski (1995) reached the same point from neuroscience. They proposed a one-layer network followed by increasing nonlinearities in , trained to maximize output entropy , which in a noiseless network maximizes transmitted information (hence Infomax). By change of variables,
which is expected ICA log-likelihood with , plus a constant. Infomax is maximum likelihood with the source model fixed by the nonlinearity (Cardoso, 1997; Pearlmutter and Parra, 1997): logistic sigmoid corresponds to a super-Gaussian logistic density with excess kurtosis 1.2.
The gradient of is , with the score function. Right multiplication by gives the natural or relative gradient (Amari, Cichocki and Yang, 1996; Cardoso and Laheld, 1996),
which needs no inverse of and is equivariant: its behavior depends on global matrix , not , so ill-conditioned mixing does not slow it. FastICA after whitening shares this property, visible in the cocktail: “nearly singular” mixing with gives the same Amari index as the original.
When the source model has the wrong sign
Likelihood decomposition warns: wrong can move the maximum. The serious error is not exact density shape, but its type. With whitened data and orthogonal , a super-Gaussian model such as makes likelihood maximization minimize (the quadratic term is constant over rotations), favoring projections with more mass near zero. If sources are sub-Gaussian, the most “peaked” projections are mixtures, not sources. Extended Infomax (Lee, Girolami and Sejnowski, 1999) resolves this by choosing per component between (super-Gaussian) and (sub-Gaussian), based on the sign of .
def logcosh_(u):
a = np.abs(u)
return a + np.log1p(np.exp(-2 * a)) - np.log(2)
def infomax(Z, modo, iters=400, eta=0.3):
"""Gradiente natural de la verosimilitud con phi(u) = u + k tanh(u), k = +1 (super) o elegido por Infomax extendido."""
d, n = Z.shape
W = np.eye(d)
for _ in range(iters):
Y = W @ Z
th = np.tanh(Y)
if modo == "fijo":
k = np.ones(d)
else:
k = np.sign((1 - th ** 2).mean(axis=1) * (Y ** 2).mean(axis=1) - (th * Y).mean(axis=1))
Phi = Y + k[:, None] * th
W = W + eta * (np.eye(d) - Phi @ Y.T / n) @ W
return W, k
A2 = np.array([[1.0, 0.8], [0.3, 1.0]])
for nombre in ["Laplace", "uniformes"]:
g = np.random.default_rng(3)
S2 = g.laplace(size=(2, 5000)) / np.sqrt(2) if nombre == "Laplace" else g.uniform(-np.sqrt(3), np.sqrt(3), (2, 5000))
Z2, V2, _ = blanquear(A2 @ S2)
for modo in ["fijo", "extendido"]:
W2, k = infomax(Z2, modo)
print(f"fuentes {nombre:9s} Infomax {modo:9s}: índice de Amari {amari(W2 @ V2 @ A2):.3f} tipo elegido {k}")
Qs = V2 @ A2
U, _, Vt = np.linalg.svd(Qs)
R0 = (U @ Vt).T # rotación que alinea z con las fuentes
valores = []
for ang in (0, 15, 30, 45):
c, s = np.cos(np.radians(ang)), np.sin(np.radians(ang))
Y = np.array([[c, -s], [s, c]]) @ R0 @ Z2
valores.append(-logcosh_(Y).sum(axis=0).mean())
print(f" log-verosimilitud del modelo supergaussiano (sin constantes) a 0, 15, 30 y 45 grados de las fuentes: "
+ ", ".join(f"{v:.4f}" for v in valores))With Laplace sources both versions separate, and super-Gaussian model likelihood decreases away from sources: its maximum is where it should be. With uniform sources fixed-model Infomax ends near index 1, almost rotation in two dimensions, the worst possible: the wrong model’s likelihood increases away from sources and peaks at the most complete mixture. Extended Infomax detects the correct type ( for both uniform) and separates. Note cost: natural gradient received 400 iterations with a manually chosen step, while FastICA solved the cocktail in fewer than ten. FastICA avoids this sign issue because its iteration converges to extrema of , maxima or minima.
Lab: ICA on natural-image patches
What “sources” exist in an image? Cut a photo into small patches and treat each patch as a linear mixture of “basis functions” with independent coefficients; ICA estimates those functions. Bell and Sejnowski (1997) did this with natural-scene patches and found localized, oriented filters like edge detectors; van Hateren and van der Schaaf (1998) showed quantitative similarity to receptive fields of primary visual cortex simple cells. PCA on the same data gives global functions resembling a Fourier basis.
The lab uses scikit-learn’s two example photos (a Chinese temple and a flower), extracts 6000 grayscale pixel patches, subtracts each patch’s mean (average brightness is irrelevant), reduces to 48 dimensions with whitened PCA, and applies FastICA to whitened data. Data use scikit-learn orientation, one row per patch.
import numpy as np
from sklearn.datasets import load_sample_images
from sklearn.decomposition import FastICA, PCA
grises = [im.astype(float).mean(axis=2) for im in load_sample_images().images]
rng = np.random.default_rng(0)
p, N = 12, 6000
parches = []
for k in range(N):
g = grises[k % 2]
i = rng.integers(0, g.shape[0] - p + 1)
j = rng.integers(0, g.shape[1] - p + 1)
parches.append(g[i:i + p, j:j + p].ravel())
Xp = np.array(parches)
Xp -= Xp.mean(axis=1, keepdims=True) # quita el brillo medio de cada parche
pca = PCA(n_components=48, whiten=True, random_state=0).fit(Xp)
Zp = pca.transform(Xp) # 6000 x 48, covarianza identidad
print("tamaño de las imágenes:", [g.shape for g in grises])
print(f"varianza explicada por 48 de las {p * p} componentes: {pca.explained_variance_ratio_.sum():.3f}")ica_p = FastICA(whiten=False, fun="logcosh", max_iter=400, tol=1e-4, random_state=0)
Sp = ica_p.fit_transform(Zp) # coeficientes independientes, 6000 x 48
print("iteraciones de FastICA:", ica_p.n_iter_)
E_p = pca.components_ # 48 x 144, direcciones de PCA
escala = np.sqrt(pca.explained_variance_)
base_pca = E_p.T * escala # columnas: componentes de PCA en píxeles
base_ica = base_pca @ ica_p.components_.T # columnas: funciones base de ICA en píxeles
def participacion(B):
"""Fracción de píxeles que usa cada función base: (sum b^2)^2 / sum b^4 / número de píxeles."""
return (B ** 2).sum(axis=0) ** 2 / (B ** 4).sum(axis=0) / B.shape[0]
def curt_cols(Y):
Y = (Y - Y.mean(axis=0)) / Y.std(axis=0)
return (Y ** 4).mean(axis=0) - 3
print(f"fracción de píxeles usados (mediana): ICA {np.median(participacion(base_ica)):.3f} PCA {np.median(participacion(base_pca)):.3f}")
print(f"curtosis de los coeficientes (mediana): ICA {np.median(curt_cols(Sp)):.1f} PCA {np.median(curt_cols(Zp)):.1f}")import matplotlib.pyplot as plt
fig, ejes = plt.subplots(6, 16, figsize=(10, 4.4))
for k in range(48):
for fila0, B in ((0, base_ica), (3, base_pca)):
ax = ejes[fila0 + k // 16, k % 16]
b = B[:, k].reshape(p, p)
m = np.abs(b).max()
ax.imshow(b, cmap="gray", vmin=-m, vmax=m)
ax.set_xticks([]); ax.set_yticks([])
fig.text(0.5, 0.97, "ICA: 48 funciones base, en el orden arbitrario en que salen", ha="center")
fig.text(0.5, 0.48, "PCA: 48 primeras componentes, por varianza decreciente", ha="center")
plt.subplots_adjust(hspace=0.15, wspace=0.08, top=0.94, bottom=0.02)
plt.show()The figure shows ICA basis functions above and PCA below. PCA functions are global: they occupy the whole patch with increasing two-dimensional frequency patterns, like a Fourier basis, because natural images are approximately stationary and their covariance depends only on pixel displacement. ICA functions are largely localized and oriented: an edge or bar at a specific position and angle; others are oriented grids, mostly from the temple roof’s repetitive texture, showing the bias of only two photos. Two cell statistics quantify it: ICA functions use a smaller pixel fraction (median 0.31 versus 0.38 for PCA), and their coefficients are much more super-Gaussian (median kurtosis 20.8 versus 10.9), hence sparser: usually near zero and occasionally large. Arbitrary ICA component order is no oversight: the model does not order sources.
The deep-learning connection is direct. Olshausen and Field’s (1996) sparse coding, in the next lesson, reaches similar functions from another objective, and first-layer filters of convolutional networks trained on natural images (Krizhevsky, Sutskever and Hinton, 2012, show them in figure 3) look like the same oriented edges and grids.
Limits: delays, more sources than sensors and nonlinear ICA
Model is instantaneous, square, noiseless and linear. Each assumption has a limit.
Convolutive mixtures. In a real room, each source’s sound reaches each microphone with delay and echoes: . For instantaneous ICA, a delayed source is another source: if samples are independent in time, and are independent variables, making the problem have more sources than sensors.
import warnings
rng = np.random.default_rng(9)
n = 20_000
Sc = rng.laplace(size=(2, n)) / np.sqrt(2)
def retrasa(s, k):
return np.concatenate([np.zeros(k), s[:-k]]) if k else s
for k in [0, 1, 3, 10]:
Xc_ = np.vstack([Sc[0] + 0.7 * retrasa(Sc[1], k), Sc[1] + 0.7 * retrasa(Sc[0], k)])
with warnings.catch_warnings():
warnings.simplefilter("ignore")
Yc = FastICA(n_components=2, whiten="unit-variance", random_state=0, max_iter=1000).fit_transform(Xc_.T).T
Cc = np.abs(np.corrcoef(np.vstack([Yc, Sc]))[:2, 2:])
print(f"retardo de {k:2d} muestras: |corr| de cada salida con su mejor fuente = {np.round(Cc.max(axis=1), 3)}")Without delay, outputs reproduce sources with correlation essentially 1. A delay of one sample already makes separation incomplete, and increasing it does not worsen matters further because with memoryless sources any delay creates the same number of “new” sources. The standard solution is frequency domain: short-time Fourier transform converts convolution into a product per band; apply complex ICA band by band (Smaragdis, 1998), then solve a problem absent from the instantaneous model: permutation and scale may differ by band, and must be aligned. The short-time transform also analyzes audio in the multimodal AI module, where neural speech and music separators generalize this approach.
More sources than sensors. If is with , no linear recovers sources (as in the cocktail with two identical microphones). Mixing can still be estimated under suitable conditions, but recovery requires an additional assumption, typically sparsity, and nonlinear inference: sparse coding in the next lesson.
Temporal structure and noise. ICA ignores sample order. If sources have distinct autocorrelations, they can be separated using only second-order statistics, jointly diagonalizing covariances at several lags (AMUSE, Tong et al., 1991; SOBI, Belouchrani et al., 1997), even if Gaussian. With additive noise, , whitening is biased and sources cannot be exactly recovered even with known ; Gaussian-noise-corrected FastICA versions exist.
Nonlinear ICA. If with invertible nonlinear , the problem is no longer identified: Hyvärinen and Pajunen (1999) showed that any random vector admits infinitely many nonlinear transformations producing independent components, most unrelated to sources. Independence, sufficient linearly, is insufficient nonlinearly. The solution almost twenty years later adds auxiliary information (time index, segment label, related observation) and estimates with contrastive learning: Hyvärinen and Morioka (2016) and Hyvärinen, Sasaki and Turner (2019) showed nonlinear ICA becomes identifiable again. This bridges to contrastive learning identifiability at the module’s end.
Causality. If with the matrix of an acyclic graph and independent non-Gaussian noise , then is an ICA model. ICA estimates up to permutation and scale, and acyclicity fixes the permutation: LiNGAM (Shimizu et al., 2006) identifies causal direction where Gaussian methods only see correlations.
Common mistakes
Exercises
Step 1 of 4. Which property of 's density is key?
Step 1 of 4. What condition does an extremum of on the sphere satisfy?
More than one answer may be correct.
More than one answer may be correct.
More than one answer may be correct.
Summary
- Model and ambiguities. with independent sources and invertible . At best ; scale and sign are fixed by convention, order has no natural choice. The Amari index measures distance from that form without penalizing ambiguities (in 2D, ).
- Whitening. with leaves with orthogonal : from unknowns to . Uncorrelatedness cannot distinguish rotations; independence can.
- Identifiability. Gaussian sources: rotational invariance, the same ambiguity as factor analysis. At most one Gaussian: identifiable (Comon, using Darmois-Skitovich), and pairwise independence suffices.
- Non-Gaussianity. Kurtosis is additive and cheap but fragile to outliers. Negentropy is natural; with or is its robust approximation.
- FastICA. and normalize: Newton with Jacobian approximated by an identity multiple, cubic or quadratic convergence under the model, no step size. Multiple components via deflation (errors accumulate) or symmetric orthogonalization .
- Three faces of one objective. Expected likelihood is ; Infomax is maximum likelihood with ; on whitened data minimum mutual information is maximum summed negentropy. A wrong source-model type (sub- or super-Gaussian) makes the maximum a mixture.
- Limits. Delays (frequency ICA), more sources than sensors (sparsity, next lesson), temporal structure (SOBI), noise and nonlinear ICA, unidentifiable without auxiliary information: contrastive learning rescues it at the module’s end.