Neural architecture search: define the space before searching
神经架构搜索
Train six declared architectures, separate weight fitting from structure selection, and audit validation and compute budgets.
neural-architecture-searchStart with the problem
Should a small network use one hidden unit or four? Should its activation be tanh or ReLU? Neural architecture search, or NAS, treats such structural choices as variables in an experiment. It does not search all possible neural networks, and it cannot make an omitted architecture appear outside the declared search space.
Zoph and Le use a recurrent controller to generate architecture descriptions and learn from validation rewards. DARTS instead relaxes discrete operation choices into differentiable mixtures. Both separate architecture selection from ordinary weight training. An exhaustive six-candidate baseline lets us inspect that separation before adding a learned search controller.
Definitions and derivation
Let α describe an architecture and θ its trainable weights. The idealized nested objective is:
The inner problem uses training data; the outer problem uses validation data. Our finite-budget implementation replaces θ* with the actual result θT of 300 gradient steps. It does not claim that each candidate reached its globally optimal weights. Ranking partially trained candidates may differ from ranking fully trained ones.
A reinforcement-learning controller samples architectures from πφ. If R is a validation reward and b is a baseline independent of the sampled architecture, the score-function identity gives:
Differentiate the sampling probabilities and write their derivative as probability times the derivative of log probability. The baseline term has zero expectation because probabilities sum to one. A sequential controller expands log π into the sum of token log probabilities. This explains the original NAS policy-gradient approach, but the program below does not implement that controller.
DARTS uses another route: replace a discrete edge operation by a softmax-weighted mixture, learn mixture parameters, and then select a discrete operation:
The relaxed mixed network and the final discrete network need not have equal performance. Shared weights and the optimization approximation can affect rankings. A parameter-count constraint or a latency objective can also be part of search, but parameter count is only a proxy for actual device latency.
Run the calculation
The complete Python 3.12 / NumPy 1.26.4 program searches widths {1,2,4} and activations {tanh,ReLU}. Each of the six architectures gets seeds 7 and 11 and 300 updates on the same 16-row x² regression task. The selection metric is mean validation MSE across those two seeds, with parameter count and activation name breaking ties.
import numpy as np
def fit(width, activation, seed, steps=300):
if width not in (1, 2, 4) or activation not in ('tanh', 'relu') or type(steps) is not int or not 0 <= steps <= 500:
raise ValueError('Choose a declared width, activation and bounded training budget.')
rng = np.random.default_rng(seed)
a, w, b, c = rng.normal(0, 0.5, width), rng.normal(0, 0.5, width), rng.normal(0, 0.2, width), 0.0
x = np.linspace(-1, 1, 16); y = x ** 2
for _ in range(steps):
pre = x[:, None] * w + b
hidden = np.tanh(pre) if activation == 'tanh' else np.maximum(pre, 0)
derivative = 1 - hidden ** 2 if activation == 'tanh' else (pre > 0)
residual = (hidden @ a + c - y) / len(x)
local = residual[:, None] * a * derivative
ga, gw, gb, gc = hidden.T @ residual, (local * x[:, None]).sum(axis=0), local.sum(axis=0), residual.sum()
a -= 0.1 * ga; w -= 0.1 * gw; b -= 0.1 * gb; c -= 0.1 * gc
return (a, w, b, c, activation)
def predict(model, x):
a, w, b, c, activation = model
pre = np.asarray(x)[:, None] * w + b
hidden = np.tanh(pre) if activation == 'tanh' else np.maximum(pre, 0)
return hidden @ a + c
def search():
valid_x = np.array([-0.9, -0.6, -0.3, 0.1, 0.4, 0.7, 0.95])
records = []
for width in (1, 2, 4):
for activation in ('tanh', 'relu'):
models = [fit(width, activation, seed) for seed in (7, 11)]
scores = [float(np.mean((predict(model, valid_x) - valid_x ** 2) ** 2)) for model in models]
records.append(dict(width=width, activation=activation, parameters=3*width+1,
validation_mean=float(np.mean(scores)), scores=scores, model=models[0]))
winner = min(records, key=lambda r: (r['validation_mean'], r['parameters'], r['activation']))
return winner, records
if __name__ == '__main__':
winner, records = search()
for row in records:
print(row['width'], row['activation'], 'parameters', row['parameters'],
'two-seed validation MSE', round(row['validation_mean'], 9))
# Evaluate the selected architecture's predeclared seed-7 model once.
test_x = np.linspace(-0.97, 0.97, 31)
print('winner', winner['width'], winner['activation'], 'locked test MSE',
round(float(np.mean((predict(winner['model'], test_x) - test_x**2)**2)), 9))
train_x = np.linspace(-1, 1, 16)
baseline = np.linalg.lstsq(np.column_stack((train_x, np.ones(16))), train_x**2, rcond=None)[0]
print('linear baseline validation MSE', round(float(np.mean((baseline[0]*np.array([-0.9,-0.6,-0.3,0.1,0.4,0.7,0.95])+baseline[1]-np.array([-0.9,-0.6,-0.3,0.1,0.4,0.7,0.95])**2)**2)), 9))
print('search cost: 6 architectures × 2 seeds × 300 updates = 3600 updates; per-update costs differ')
Actual output:
1 tanh parameters 4 two-seed validation MSE 0.106418432
1 relu parameters 4 two-seed validation MSE 0.085701992
2 tanh parameters 7 two-seed validation MSE 0.104968806
2 relu parameters 7 two-seed validation MSE 0.050045662
4 tanh parameters 13 two-seed validation MSE 0.104941221
4 relu parameters 13 two-seed validation MSE 0.066569282
winner 2 relu locked test MSE 0.067002642
linear baseline validation MSE 0.10579472
search cost: 6 architectures × 2 seeds × 300 updates = 3600 updates; per-update costs differ
Width 2 with ReLU wins this declared validation comparison. Its already-trained seed-7 model is the predeclared representative used for one final test calculation; the program does not select the better seed using test scores. A fitted linear regression supplies a simple baseline. These tiny synthetic scores do not rank architectures for other datasets.
A width-h model has h input weights, h hidden biases, h output weights and one output bias: 3h+1 parameters. The search spends 6×2×300=3600 parameter updates, but larger widths do more arithmetic per update. For n scalar-input examples, each forward/backward pass costs O(nh); a wall-time comparison would additionally need actual timing. No weights are shared between candidates in this program.
When the method fails
A narrow search space can make a sophisticated controller look successful while excluding useful alternatives. A training recipe tuned for one architecture can handicap another. Noisy validation estimates and repeated search can overfit the validation set, even if every candidate’s weights use only training rows.
Report the space, candidate budget, seeds, training schedule, selection metric, failures and final evaluation protocol. Random or exhaustive search is an important baseline before attributing an improvement to the search algorithm. If using a supernet, evaluate whether shared-weight rankings predict independently trained performance. Hardware-aware search needs the intended device and workload. This example demonstrates actual architecture selection, not the original papers’ large-scale search systems or benchmark records.
Exercises with answers
- How many architectures and training runs are in the declared search?
Answer 1: Six architectures and twelve runs, because each architecture uses two seeds.
- Why does a width-4 model have thirteen parameters?
Answer 2: Four input weights, four hidden biases, four output weights and one output bias.
- Does choosing the largest DARTS mixture weight preserve the mixed model’s output exactly?
Answer 3: Generally not. Replacing a weighted sum of operations with one operation changes the function.
- Why is the validation winner not a universal best architecture?
Answer 4: The ranking depends on this space, dataset, seeds, optimization budget and scoring rule, and the validation set participated in selection.
Sources and next steps
Zoph and Le’s physical page 3, Sections 3.1–3.2, explains architecture tokens, validation reward and REINFORCE. DARTS physical page 3, Equations 2–4, explains relaxed operations and bilevel optimization. The six-model baseline and its reproducible CPU training are original. Continue with hyperparameter search for selection discipline and lottery ticket hypothesis for structure discovery through pruning.
Make a prediction, then check
Which data chooses the architecture in this experiment?
Learning objectives
- Separate architecture selection from finite-budget weight training.
- Audit the search space, seed policy and total search cost.
Prerequisites & connections
Explore related knowledge →References
- Neural Architecture Search with Reinforcement Learning — arXiv v2
Barret Zoph; Quoc V. Le · 2017 - DARTS: Differentiable Architecture Search — arXiv v2
Hanxiao Liu; Karen Simonyan; Yiming Yang · 2019
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · 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 tests passed per chapter, including independent derivatives, integrals, normal equations or exact/literal trajectory references as appropriate. All eight programs use NumPy 1.26.4. Tests include augmentation geometry, exact quadratic certificates, finite differences, spectral solutions, conditional risk decompositions and masked neural-network training. CPU teaching calculations, not framework or GPU benchmarks.
- 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:
- Neural Architecture Search with Reinforcement Learning — arXiv v2 · Physical page 3, Sections 3.1–3.2: recurrent architecture controller, validation rewards and score-function policy gradients.
- DARTS: Differentiable Architecture Search — arXiv v2 · Physical page 3, Section 2.2 Equations 2–4: mixed operations, discretization and bilevel optimization.
Related topics