Propose · evaluate · learn
Bayesian optimization:
settings and architecture
Understand what a search can choose, what training learns, and what a small trial history actually proves.
The search can include architecture
Bayesian optimization chooses the next configuration to evaluate using a model of previous evaluation results and an acquisition rule. What it can choose depends on the search space you define. Learning rate and regularization are possible choices; so are neural-network layer counts, widths and activations when the trial builder exposes them.
This corrects the blanket claim in the short original conclusion, preserved in full below. The useful distinction is between an outer search over configurations and an inner procedure that trains a model. A search can rebuild a differently configured architecture for another trial without directly editing a trained network’s layers in the middle of a fit.
| Quantity | How it is chosen | Important distinction |
|---|---|---|
| SVC C, gamma, kernel | Settings supplied to the estimator | Kernel choice changes the function family |
| Neural depth, width, activation | Builder uses selected settings | Architecture may differ between trials |
| Neural weights | Learned by the inner training procedure | Not the same as choosing layer count |
| Next trial | Search rule uses previous validation results | It does not guarantee a global optimum |
The saved original says “in this code,” but contains no code, data, image or experiment result. The executable procedure added here is a new example, not a reconstruction of an unseen historical run. All original wording and list items remain intact.
Read the original conclusion with these qualifications
Architecture is not automatically excluded
The original statements that Bayesian optimization cannot change layer count or activation and that hyperparameters are never architectural are too broad. A trial can select a depth or activation and build a corresponding network. Conversely, if the builder fixes those choices and only exposes C or learning rate, that particular search will keep architecture fixed. Search-space design determines the scope.
The search method does not itself provide the training gradient update for a chosen neural network. It receives a measured validation objective after training or evaluation and decides another configuration to try. Searching an activation function as a categorical choice is different from differentiating through that choice during standard backpropagation.
C is a regularization trade-off, not a guarantee
For SVC, C controls the penalty on margin violations; smaller C corresponds to stronger regularization. It can help or hurt validation performance depending on the task. The original suggestion that lower C necessarily generalizes better must therefore be treated as intuition, not a promise. Feature scaling also changes distances and should be included consistently in the experiment.
Gamma depends on the kernel
The original gamma explanation is relevant to kernels such as the radial basis function. Gamma is not used by the linear SVC kernel. In the added search, gamma is active only when kernel is rbf. Changing a parameter that the selected model ignores cannot test the intended effect.
At squared distance 4, gamma 0.1 gives exp(−0.4) ≈ 0.670320, while gamma 1 gives exp(−4) ≈ 0.018316. These are checked kernel-similarity values, not classification probabilities or measured accuracies. A larger gamma makes similarity decay more rapidly with distance for this kernel; it does not guarantee better boundaries for unseen data.
Understand what the search is selecting
This denotes the best observed trial under the chosen score and data protocol. It does not certify the best possible model over every configuration. If the validation set guides many choices, its best score can become optimistic; keep a final test set outside selection, and use repeated or nested evaluations when uncertainty matters.
A small acquisition-rule illustration
A surrogate can estimate a mean score μ and uncertainty σ. One illustrative maximum-score upper-confidence rule is:
With β = 2, invented candidate A has μ = 0.80 and σ = 0.10, giving acquisition 1.00. Candidate B has μ = 0.83 and σ = 0.01, giving 0.85. The rule can prefer A because it is more uncertain. These are hypothetical acquisition values, not measured accuracy or calibrated probabilities. The installed KerasTuner implementation handles objective direction through a minimization convention; these illustrative numbers are not a reconstruction of its internal posterior or trial choices.
Initial random trials are often needed before a surrogate can be fitted. KerasTuner’s default initial-point count scales with the search-space dimension. Merely naming a tuner Bayesian does not show that a tiny run reached the model-based phase. Our added procedure explicitly requests two initial points and instruments actual Gaussian-process fits in installed KerasTuner 1.4.8.
What the actual six-trial run showed
All six SVC trials completed on training cross-validation. The Gaussian process was fitted four times using 2, 3, 4 and 5 completed trial records. The best observed three-fold mean accuracy was 0.952381. Later trials tied the second, initially random trial rather than improving it, and three records repeated the same linear-kernel C = 10 setting. There were four unique configuration dictionaries across six trial records.

A fresh estimator built from the selected settings was refitted on all 105 training rows and evaluated once on the 45 held-aside test rows, scoring 41/45. That single-split result is not a generalization guarantee, timing study, comparison with random search or proof that six trials are sufficient for another task.
A builder can produce different neural networks
The separate builder at the end of the executed procedure uses two input features and one output. A selected depth of zero produces a direct linear layer with three parameters: two weights and one bias. A selected depth of one adds a ReLU hidden layer, with width four or eight.
Width four therefore gives 17 parameters and width eight gives 33. The actual Keras models were built and called on a three-row input, each yielding shape (3, 1) with finite values and the checked parameter count. Width is conditional on a hidden layer being present; it is inactive for depth zero.
Execution boundary: these neural models were not trained or Bayesian-searched. Their forward calls and parameter counts demonstrate that a builder can map selected hyperparameters to different architectures. The Bayesian search in this lesson is the distinct SVC cross-validation experiment. Do not read an untrained forward call as a model-quality result.
Executed procedure: conditional Bayesian search
The example uses Iris, a stratified 105/45 training/test split and three deterministic folds within training. Scaling is fitted inside each fold’s pipeline. The Oracle maximizes score; SklearnTuner performs the cross-validation. Gamma is conditionally active for rbf, while C is searched logarithmically for both kernels.
Executed with NumPy 2.5.5, scikit-learn 1.8.0, Keras 3.15.1 and KerasTuner 1.4.8 in the recorded TensorFlow-backed environment. The GP-fit wrapper is verification instrumentation for that installed implementation, not a stable public tuning API. It may need adjustment if library internals change. It confirms actual fitting, not surrogate calibration or global search quality.
Run from a writable directory containing a day19 folder for the JSON report and the listed libraries installed. Trial artifacts go into a new temporary directory. The separate neural builder uses ordinary forward inference only and does not download or train a large dataset.
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
from pathlib import Path
import tempfile,json
import numpy as np
import sklearn,keras,keras_tuner as kt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split,StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import make_scorer,accuracy_score
X,y=load_iris(return_X_y=True)
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,stratify=y,random_state=42)
cv=StratifiedKFold(3,shuffle=True,random_state=42)
def build_sklearn(hp):
kernel=hp.Choice('kernel',['linear','rbf'])
C=hp.Float('C',0.1,10.0,sampling='log')
gamma=hp.Float('gamma',0.001,1.0,sampling='log',parent_name='kernel',parent_values=['rbf'])
return make_pipeline(StandardScaler(),SVC(C=C,kernel=kernel,gamma=gamma if kernel=='rbf'else'scale'))
root=Path(tempfile.mkdtemp(prefix='day19-bayesian-'))
oracle=kt.oracles.BayesianOptimizationOracle(objective=kt.Objective('score','max'),max_trials=6,num_initial_points=2,seed=42)
# Verification instrumentation for the installed KerasTuner 1.4.8 implementation.
gp_fit_rows=[]
original_gp_fit=oracle.gpr.fit
def tracked_gp_fit(*args,**kwargs):
gp_fit_rows.append(len(args[0]))
return original_gp_fit(*args,**kwargs)
oracle.gpr.fit=tracked_gp_fit
tuner=kt.SklearnTuner(oracle=oracle,hypermodel=build_sklearn,scoring=make_scorer(accuracy_score),cv=cv,directory=str(root),project_name='iris')
tuner.search(X_train,y_train)
trials=list(tuner.oracle.trials.values())
assert len(trials)==6 and all(t.status=='COMPLETED'for t in trials)
assert gp_fit_rows, 'No Gaussian-process fit was observed'
best=tuner.oracle.get_best_trials(1)[0]
assert np.isclose(best.score,max(t.score for t in trials))
# Fresh refit after selection; the held-aside test never selects trials.
chosen=build_sklearn(tuner.get_best_hyperparameters(1)[0])
chosen.fit(X_train,y_train)
test_accuracy=float(chosen.score(X_test,y_test))
# Separate architecture-builder demonstration: inference only, no training/search.
def build_network(hp):
depth=hp.Int('depth',0,1)
width=hp.Choice('width',[4,8],parent_name='depth',parent_values=[1])
inputs=keras.Input(shape=(2,));z=inputs
if depth:z=keras.layers.Dense(width,activation='relu')(z)
return keras.Model(inputs,keras.layers.Dense(1)(z))
architectures=[]
for depth,width,expected in [(0,4,3),(1,4,17),(1,8,33)]:
hp=kt.HyperParameters();hp.Fixed('depth',depth)
if depth:hp.Fixed('width',width)
model=build_network(hp)
output=model(np.ones((3,2),dtype='float32'),training=False).numpy()
assert output.shape==(3,1)and np.isfinite(output).all()
assert model.count_params()==expected
architectures.append({'depth':depth,'width':width if depth else None,'parameters':model.count_params(),'output_shape':list(output.shape)})
result={'numpy':np.__version__,'sklearn':sklearn.__version__,'keras':keras.__version__,'keras_tuner':kt.__version__,'trials':[{'id':t.trial_id,'score':float(t.score),'status':t.status,'values':t.hyperparameters.values}for t in trials],'gp_fit_training_rows':gp_fit_rows,'initial_random_points':2,'best_trial':best.trial_id,'best_cv_score':float(best.score),'best_values':best.hyperparameters.values,'final_test_accuracy':test_accuracy,'architectures':architectures,'scope':'Actual six-trial Bayesian SVC search on105Iris training rows with3-foldCV and scaler inside folds; two initial random points, observed GPfits. Fresh refit evaluated once on45held-aside rows. Tiny neural architectures built/called but not trained or Bayesian-searched; no general superiority/timing/global optimum claimed.'}
Path('day19/runtime-result.json').write_text(json.dumps(result,indent=2));print(json.dumps(result,indent=2))
Practice: first write down which choices the builder exposes and which quantities are learned during training. Then inspect trial status, active conditional parameters, seed, preprocessing and validation objective. If you change the search space or budget, treat that as another experiment; do not keep selecting against the final test results.
Primary references
- KerasTuner: model architecture and search-space examples
- BayesianOptimization: Gaussian process, initial points and budget
- Conditional hyperparameters
- SklearnTuner cross-validation interface
- SVC regularization, gamma and kernel reference
- Snoek, Larochelle and Adams: Practical Bayesian Optimization of Machine Learning Algorithms
References checked 17 November 2026. Added equations are selectable HTML with local scrolling when needed, without a new rendering library. Outcomes describe the recorded small experiment only; no ranking, global-optimum or future-performance guarantee is made.
Complete original conclusion
The full original wording follows unchanged, including its broad architecture statements. Read the separate qualifications above. The saved original has no accompanying code or experiment record; the added example is explicitly new.
In conclusion, Bayesian optimization does not change the internal structure of the model—things like the number of layers, the activation functions, or the gradients. Instead, it focuses on external hyperparameters. These are settings that control how the model behaves during training and how it processes the data, but they are not part of the model’s architecture itself.
For instance, in this code, Bayesian optimization adjusts:
- C (Regularization Parameter): This determines how much the model tries to fit the training data exactly versus how much it tries to keep things simple. A higher C means the model will try harder to match the training data, while a lower C encourages simpler solutions that generalize better to unseen data.
- Gamma (Kernel Coefficient): This affects how much influence each individual data point has on the decision boundary. A small gamma means each point has a broad influence, leading to simpler decision boundaries. A larger gamma focuses the model more on specific data points, creating more complex boundaries.
- Kernel Type: This controls the type of mathematical function used to separate the data. For example, a “linear” kernel creates a flat plane or straight line to divide the data, while an “rbf” (radial basis function) kernel allows for curved, more flexible boundaries.
So, while the model’s internal structure—like layers and activations—remains unchanged, Bayesian optimization helps you choose the best external hyperparameters. This results in a better-performing model without needing to re-architect or directly modify the model’s components.
Questions about Bayesian search and architecture
Can Bayesian optimization choose a neural-network architecture?
Yes, if the search space exposes architecture choices such as layer count, width or activation. A builder creates the configured model for a trial. That is different from automatically changing layers during an ordinary training run.
Does Bayesian optimization train model weights itself?
The search method proposes configurations and uses evaluation results. An inner training procedure fits the model for each configuration. For a neural network, that procedure may use gradient-based optimization.
Does lower C always generalize better?
No. Lower C means stronger regularization for SVC, but validation performance depends on the data, preprocessing, kernel and other settings. Choose it through a suitable validation protocol.
Does gamma change a linear SVC?
No. SVC uses gamma for rbf, polynomial and sigmoid kernels, not the linear kernel. Conditional search parameters avoid spending effort on an inactive setting.
Did the six-trial example prove Bayesian search is better than random search?
No. Gaussian-process fitting was observed, but later trials tied the initial best and repeated a configuration. The run is a small workflow check, not a comparative benchmark or global-optimum proof.
Were the tiny neural networks trained or Bayesian-searched?
No. Three architecture settings were built and called for forward inference, with parameter counts verified. The actual Bayesian search in the added procedure trained and cross-validated SVC models, not those neural networks.
