Sparse autoencoders: constrain activity, not just code width
稀疏自编码器
Train an overcomplete sigmoid code with a KL activity penalty, verify all gradients and separate unit averages from per-example sparsity.
sparse-autoencodersStart with the problem
A code can have more coordinates than its input and still be useful if its activity is constrained. Sparse autoencoders add a code penalty to reconstruction, but different penalties mean different things. A small average activation for each unit is not the same requirement as exactly a few active units in every example.
Andrew Ng’s sparse-autoencoder notes give a sigmoid-unit average-activity KL penalty. Deep Learning Section 14.2.1 discusses code sparsity more broadly. We implement the KL version with three hidden units for two input coordinates and derive its gradient directly from the objective.
Definitions and derivation
The encoder is sigmoid, the decoder is linear, and their weights are untied. Define the mean activity of hidden unit j over the training batch:
We choose desired mean ρ=0.1. The Bernoulli KL term is zero when the observed mean equals ρ and diverges as the mean approaches zero or one. It does not ask every activation to be 0.1. The full objective includes reconstruction, activity regularization and a small weight penalty:
Our λ is 0.001 and biases are not weight-decayed. There are seventeen parameters: six encoder weights, three hidden biases, six decoder weights and two output biases. Sigmoid outputs stay strictly between zero and one mathematically, so this is approximate activity sparsity, not exact zeros. ReLU with an L1 or other activation penalty gives a different model.
The mean couples examples in the sparsity gradient. Differentiating the stated loss gives:
Both the reconstruction contribution and the sparsity contribution pass through the sigmoid derivative when differentiating preactivation z. The linked notes’ printed page 16 places its added sparsity term outside the activation-derivative factor. For the objective on page 15, the chain rule requires the factor shown above. We use the objective as the definition, rederive the gradient and check all seventeen parameters by finite differences rather than copying that displayed update.
Compute the mean over the declared batch before backpropagating. Using per-example activities in its place changes the penalty, and averaging minibatch KL values is generally not the same as the KL of a full-dataset mean. The code deliberately uses the entire four-row training table, so no estimate of the global mean is hidden.
Two activation tables can have identical unit means and different per-example patterns. Rows (0.2,0),(0,0.2) and two identical rows (0.1,0.1) both give mean (0.1,0.1), so their KL penalties match. The first concentrates activity differently from the second. Mean activity alone cannot certify a particular support size or interpretability.
Run the calculation
Complete Python 3.12 / NumPy 1.26.4 program:
import numpy as np
X=np.array([[0.,0],[0,1],[1,0],[1,1]])
def initial():return np.r_[np.array([[.2,-.3,.1],[.4,.2,-.2]]).ravel(),np.zeros(3),np.array([[.3,-.2],[-.1,.4],[.2,.1]]).ravel(),np.zeros(2)]
def objective(theta,beta=.1,rho=.1,decay=.001):
t=np.asarray(theta,dtype=float)
if t.shape!=(17,) or not np.isfinite(t).all() or beta<0 or not 0<rho<1 or decay<0:raise ValueError('Use 17 finite parameters and valid sparsity controls.')
w=t[:6].reshape(2,3);b=t[6:9];v=t[9:15].reshape(3,2);c=t[15:17];h=np.exp(-np.logaddexp(0,-(X@w+b)));mean=h.mean(axis=0)
if np.any((mean<=0)|(mean>=1)):raise ValueError('Saturated means make the KL objective singular.')
error=h@v+c-X;reconstruction=.5*np.sum(error**2)/len(X);kl=np.sum(rho*np.log(rho/mean)+(1-rho)*np.log((1-rho)/(1-mean)))
gh=error@v.T/len(X)+beta*(-rho/mean+(1-rho)/(1-mean))/len(X);gz=gh*h*(1-h)
grad=np.r_[(X.T@gz+decay*w).ravel(),gz.sum(axis=0),(h.T@error/len(X)+decay*v).ravel(),error.mean(axis=0)]
return float(reconstruction+beta*kl+.5*decay*(np.sum(w*w)+np.sum(v*v))),grad,mean,float(reconstruction)
def train(beta):
t=initial()
for _ in range(4000):t-=.1*objective(t,beta)[1]
return t,objective(t,beta)
if __name__=='__main__':
for beta in (0.,.1,1.):
t,(loss,g,mean,reconstruction)=train(beta);print('beta',beta,'mean activations',mean.round(9).tolist(),'reconstruction',round(reconstruction,9),'objective',round(loss,9))
rho=.1;balanced=np.array([[.2,0],[0,.2]]);same=np.full((2,2),.1);print('same unit means',balanced.mean(axis=0).tolist(),same.mean(axis=0).tolist(),'different per-example patterns')
Actual output:
beta 0.0 mean activations [0.511370683, 0.512504153, 0.559290653] reconstruction 9.9437e-05 objective 0.008738911
beta 0.1 mean activations [0.215873907, 0.170150612, 0.150842948] reconstruction 0.003394808 objective 0.027186362
beta 1.0 mean activations [0.107450454, 0.118584392, 0.109246005] reconstruction 0.002681658 objective 0.031137862
same unit means [0.1, 0.1] [0.1, 0.1] different per-example patterns
Each run starts from the same parameters and uses 4,000 full-batch updates. At β=0, mean activities remain around 0.51–0.56. At β=1, they approach 0.107–0.119 rather than exactly 0.1, because reconstruction and weight decay compete with the penalty. Reconstruction is worse than the unpenalized run here; it is not monotone between every two tested β values after finite nonconvex training.
The program is a small overcomplete reconstruction model, not a demonstration of discovered human concepts or a dictionary extracted from a large language model. With n examples, d inputs and k hidden units, dense forward/backward work is O(ndk); storing activations costs O(nk). Estimating dataset-level mean activity may require an additional pass or an explicitly approximate running statistic.
When the method fails
A weak decoder can make sparsity look expensive, while a flexible decoder can compensate by rescaling weights. The weight penalty limits one such escape route but does not identify unique features. Duplicate units can share activity and produce redundant codes.
Choose sparsity targets using an evaluation protocol, not by repeatedly inspecting the final test set. Report reconstruction, activity distribution, inactive or duplicate units and downstream utility separately. A small mean alone is neither a causal explanation nor evidence that individual units have stable semantic meanings.
Exercises with answers
- Does the KL penalty force exact zeros?
Answer 1: No. Sigmoid activations are positive; it encourages a low unit mean.
- Why must the sparsity gradient include h(1−h)?
Answer 2: The KL depends on activations through their average, and activations depend on preactivations through sigmoid.
- Can equal unit means hide different per-example patterns?
Answer 3: Yes. The two explicit tables in the example share means but allocate activity differently.
- Why do trained means not equal the requested 0.1 exactly?
Answer 4: The finite optimization balances reconstruction, activity penalty and weight decay; the KL target is not a hard constraint.
Sources and next steps
Ng’s printed pages 14–16 define mean activity, Bernoulli KL and the batch dependence; page 16 was also visually inspected to resolve the derivative placement. Chapter 14.2.1 contrasts code penalties with parameter penalties. The gradient correction follows the stated objective and is independently tested. Continue with contractive autoencoders, which penalize input sensitivity, and autoencoders for reconstruction and latent ambiguity.
Make a prediction, then check
What quantity does this KL penalty constrain?
Learning objectives
- Differentiate a batch-mean activity penalty correctly.
- Separate unit-average sparsity from per-example support and interpretability.
Prerequisites & connections
Explore related knowledge →References
- CS294A Lecture Notes: Sparse Autoencoder
Andrew Ng - Deep Learning — Chapter 14: Autoencoders
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 checks passed per chapter: independent finite differences, exact covariance/binomial references, queue transitions, stopped versus full gradients, batch-normalization derivatives and collapse/rank counterexamples as applicable. All ten programs use NumPy 1.26.4. This scoped final record supersedes the generic carried-over checklist in the frozen metadata; original drafts are retained.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- CS294A Lecture Notes: Sparse Autoencoder · Printed pages 14–16: mean activity, Bernoulli KL, batch dependence; page 16 visually inspected, derivative independently rederived from page-15 objective.
- Deep Learning — Chapter 14: Autoencoders · Section 14.2.1: code sparsity penalties, reconstruction and distinction from parameter regularization.
Related topics