Sub topic 1
Parameters versus hyperparameters
Prerequisites
This chapter assumes you can read basic Python and have trained a supervised model with scikit-learn or a similar library. You should know what fitting a model and predicting with it mean. You should also have a rough idea of overfitting (a model that memorizes training data) and underfitting (a model too simple to capture the pattern). Later chapters treat these ideas in more detail.
Two kinds of numbers in a model
Every machine learning model contains numbers that determine its behavior. They fall into two groups, and the difference between them drives everything else in this tutorial.
- Parameters are values the model learns from the training data. The fitting algorithm sets them. Examples are the coefficients of a linear regression, the weights of a neural network, and the split thresholds inside a decision tree.
- Hyperparameters are settings you choose before training starts. The fitting algorithm does not change them. Examples are the regularization strength, the maximum depth of a tree, and the number of neighbors in k-nearest neighbors.
A short rule of thumb: if fit() computes it, it is a parameter. If you pass it to the constructor, it is usually a hyperparameter.
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_breast_cancer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
# C and max_iter are hyperparameters: we choose them before fitting.
model = make_pipeline(StandardScaler(), LogisticRegression(C=0.5, max_iter=1000))
model.fit(X, y)
# coef_ and intercept_ are parameters: fit() learned them.
clf = model.named_steps["logisticregression"]
print("Hyperparameter C:", clf.C)
print("Learned coefficients:", clf.coef_.shape)
print("Learned intercept:", clf.intercept_)In scikit-learn, learned attributes end with an underscore (coef_, intercept_, feature_importances_). Constructor arguments have no underscore. This naming convention is a quick way to tell the two groups apart.
Why the distinction matters
Parameters and hyperparameters are optimized differently, and that difference creates a trap.
Parameters are fitted by minimizing a loss function on the training data. The loss is usually differentiable or otherwise cheap to optimize, so algorithms such as gradient descent or closed-form solvers do the work.
Hyperparameters usually cannot be fitted that way. Suppose you let a tree choose its own depth by minimizing training error. It would pick the deepest tree possible, because a deeper tree always fits the training data at least as well. The result would be a model that memorizes the training set. Hyperparameters often control model flexibility, so the training loss is the wrong signal for choosing them.
This is why you evaluate hyperparameters on data the model was not trained on. The evaluation data stands in for future data, and the setting that scores best there is more likely to generalize.
flowchart TD
A[Choose hyperparameters] --> B[Fit model on training data]
B --> C[Learned parameters]
C --> D[Score on held-out data]
D --> E{Good enough or budget spent?}
E -- No --> A
E -- Yes --> F[Keep best hyperparameters]The diagram above is not in the required fenced format, so here it is again in the form this platform renders.
Comparing the two groups
| Aspect | Parameters | Hyperparameters |
|---|---|---|
| Who sets them | The training algorithm | You, or a tuning procedure |
| When they are set | During `fit()` | Before `fit()` |
| Chosen using | Training loss | Held-out score |
| Typical count | Thousands to billions | A handful to a few dozen |
| Stored in the fitted model | Yes | Yes, as configuration |
| Example | Neural network weights | Learning rate, number of layers |
Notice the count. A model can have millions of parameters but only a few hyperparameters. Tuning is a search over that small space, but each point in it requires a full training run, so the search is expensive.
Kinds of hyperparameters
Hyperparameters are not all alike. Grouping them helps you decide how to search them later.
- Model-capacity settings control how flexible the model can be. Examples are
max_depthfor trees, the polynomial degree, and the number of hidden units. - Regularization settings penalize complexity. Examples are
CinLogisticRegressionandSVC(smallerCmeans stronger regularization),alphain ridge regression, and dropout rate. - Optimization settings control how training proceeds. Examples are the learning rate, batch size, and number of epochs.
- Algorithm choices select a component. Examples are the kernel in an SVM, the
penaltytype, or the choice of solver.
Chapter 6 covers these in more detail. For now, notice that they differ in type. Some are integers, some are real numbers, and some are categories. Some only make sense when another hyperparameter takes a certain value. For example, gamma in SVC has no effect with a linear kernel.
Inspecting hyperparameters in scikit-learn
Every scikit-learn estimator exposes its hyperparameters through get_params() and changes them with set_params(). Tuning tools rely on this interface.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
pipe = make_pipeline(StandardScaler(), SVC())
# Hyperparameters of the whole pipeline, including nested ones.
for name, value in pipe.get_params().items():
if name.startswith("svc__"):
print(name, "=", value)
pipe.set_params(svc__C=10, svc__gamma=0.01)
print(pipe.get_params()["svc__C"])Names of nested settings use a double underscore: svc__C means "the C of the step named svc". You will use exactly this syntax when you define search spaces. Note that StandardScaler has its own parameters too. Its learned mean and scale are parameters. Its with_mean flag is a hyperparameter. A preprocessing step is part of the model, so its settings belong to the tuning problem too.
Defaults are choices too
Libraries ship with default hyperparameter values. Defaults are reasonable general-purpose guesses, and for some models they are strong. A random forest with default settings often performs well. For others, such as an SVM on unscaled data or a gradient boosting model on a hard problem, defaults can leave a lot of performance unused.
Treat the default as a baseline, not as a neutral starting point. Fit the model with defaults first and record its score. Any tuning run should beat that baseline by a margin that justifies the extra compute. If tuning gains only a small amount, the default may be the better engineering choice.
Common mistakes
- Confusing the two groups. Calling the weights "hyperparameters" or the learning rate a "parameter" makes it hard to reason about what gets tuned and what gets learned. Some people use "parameter" loosely for both. In scikit-learn the word
param_gridrefers to hyperparameters. Keep the strict meaning in your own notes. - Choosing hyperparameters by training score. Training score rewards memorization. Always pick settings with a score on data the fit did not see.
- Choosing hyperparameters by the final test score. If you try many settings and keep the one that scores best on the test set, the test set has become part of tuning. Its score is then optimistic. Later chapters show how to set up separate validation and test data.
- Tuning everything at once. Each additional hyperparameter multiplies the search space. Start with the few that influence the model most, such as regularization strength and capacity.
- Forgetting preprocessing. Scaling choices, imputation strategy, and feature selection thresholds are also settings. If they are fitted on all the data before splitting, they leak information. The leakage chapter handles this with pipelines.
What comes next
The rest of the tutorial builds on this split. The next chapters explain why settings change generalization, how to choose a metric, and how to split data so that tuning stays honest. After that, you will search over settings systematically with grid search, random search, Bayesian optimization, and early-stopping methods.
Exercise
A decision tree classifier is fitted with DecisionTreeClassifier(max_depth=4, min_samples_leaf=5). After fit(), you read tree.tree_.node_count and the split thresholds at each node. Which of these are hyperparameters and which are parameters? Also explain why you should not choose max_depth by picking the value with the lowest training error.
Show answer
max_depth and min_samples_leaf are hyperparameters, because you set them before fitting. The split features and thresholds at each node are parameters, because fit() learned them from the data. The node count is a result of fitting, so it is a learned property, not a setting. Training error generally decreases as max_depth grows, since a deeper tree can fit the training data more closely. Choosing the lowest training error would pick the deepest tree and overfit. You should compare depths on held-out data instead.
Exercise
In the pipeline make_pipeline(StandardScaler(), SVC()), write the keyword arguments you would pass to set_params to set the SVM's C to 5 and the scaler to skip centering. Which of these values are hyperparameters?
Show answer
pipe.set_params(svc__C=5, standardscaler__with_mean=False). Both C and with_mean are hyperparameters. The scaler's learned mean_ and scale_ attributes are parameters, and they exist only after fit().