Why One Interface Matters
scikit-learn has hundreds of models and transformers, and they all follow
one set of rules called the estimator contract. An estimator is an
object you create with settings, fit on data, and then use. Because the
rules are the same for a logistic regression, a random forest and a scaler,
the lessons that follow can swap one for another without changing the code
around it, and the searches and pipelines of later modules can drive any of
them. This lesson makes the rules explicit with one model, a
LogisticRegression on the bundled iris data, so that you can predict what
every later call does.
Hyperparameters and Learned Attributes
An estimator holds two kinds of thing, and the contract keeps them apart.
Hyperparameters are the settings you choose when you create the object:
LogisticRegression(C=0.5, max_iter=200) sets C, the strength of the
model's regularisation (smaller is stronger), and max_iter, how many
optimisation steps it may take. Everything not named keeps its default. The
constructor stores them and does nothing else: no data is seen, nothing is
computed. get_params() returns them all as a dictionary, and
set_params(C=10.0) changes one.
Learned attributes are what fit computes from data. Their names end
with an underscore: coef_ holds the learned weights, classes_ the class
labels seen, n_features_in_ the number of columns fit received. The
underscore is the contract's signal that an attribute exists only after
fit. Before fit, reading model.coef_ fails, and that is deliberate.

Read the diagram from the top: construction, then fit, then the two
operations that look similar but keep different things. A clone keeps
the hyperparameters and drops the learned attributes. set_params keeps
the learned attributes and changes a hyperparameter, so a fitted model with a
new C is still the old fit until fit runs again. That second case is the
one that surprises people.
The Methods
fit(X, y)learns from the rows ofXand the targetsy. It returns the estimator itself, somodel = LogisticRegression().fit(X, y)is the same as two lines. For a transformer,fit(X)takes no target.predict(X)returns one label per row. For a classifier the labels come fromclasses_; for a regressor they are numbers.predict_proba(X)returns one row per input row with one probability per class, in the order ofclasses_. Column 1 is the probability of the second class. Some classifiers offerdecision_function(X)instead of or as well as probabilities; the classification module uses both.score(X, y)predicts and compares withy: accuracy for a classifier, R squared for a regressor. A score on the rows the model was fitted on is a training score, which says how well it memorised, not how well it generalises. The next lessons hold rows out for that.
random_state is a hyperparameter of every estimator that uses randomness,
such as a random forest or a shuffled split. Setting it to an integer makes
the result repeatable. LogisticRegression with its default solver is
deterministic, so it ignores the setting; the data lesson shows what each
seed controls.
Exercise: Walk the Contract
You will fit a logistic regression on iris, list its attributes before and
after fit, clone it, break the contract twice on purpose and read the two
errors, then see what set_params keeps.
Starting state: the course environment from the setup lesson, active in your terminal.
-
Create the lesson folder. macOS and Linux:
mkdir -p ~/sklearn-practice/fit-predict-and-score cd ~/sklearn-practice/fit-predict-and-scoreWindows PowerShell:
mkdir $HOME\sklearn-practice\fit-predict-and-score cd $HOME\sklearn-practice\fit-predict-and-score -
Save this as
contract_check.py:"""Explore the estimator contract with a logistic regression on the iris data.""" from sklearn.base import clone from sklearn.datasets import load_iris from sklearn.exceptions import NotFittedError from sklearn.linear_model import LogisticRegression X, y = load_iris(return_X_y=True) model = LogisticRegression(C=0.5, max_iter=200) def learned(estimator): """Names of the attributes an estimator learned in fit: they end with an underscore.""" return sorted(name for name in vars(estimator) if name.endswith("_") and not name.startswith("_")) settings = model.get_params() print("Hyperparameters set at construction:", {key: settings[key] for key in ["C", "max_iter", "solver", "class_weight"]}) print("Learned attributes before fit:", learned(model)) result = model.fit(X, y) print("fit returned the same object:", result is model) print("Learned attributes after fit:", learned(model)) print("classes_:", model.classes_.tolist(), "| n_features_in_:", model.n_features_in_, "| coef_ shape:", model.coef_.shape) print("Prediction for the first row:", model.predict(X[:1]).tolist(), "| probabilities:", model.predict_proba(X[:1]).round(3).tolist()) print(f"Training accuracy: {model.score(X, y):.3f}") copy = clone(model) print("Clone has the same hyperparameters:", copy.get_params() == model.get_params()) print("Clone learned attributes:", learned(copy)) try: copy.predict(X[:1]) except NotFittedError as error: print("NotFittedError:", error) try: model.predict(X[:1, :3]) except ValueError as error: print("ValueError:", error) model.set_params(C=10.0) print("After set_params(C=10.0), C is", model.get_params()["C"], "and learned attributes are", "still present" if learned(model) else "gone") print("coef_ unchanged until fit runs again:", model.coef_[0, 0].round(4)) model.fit(X, y) print("coef_ after refitting with C=10.0:", model.coef_[0, 0].round(4)) -
Before running it, predict three things: which names the two
learnedlists hold, whatcopy.predictraises, and whetherset_paramsremovescoef_. Then run it:python contract_check.pyOutput (every value should match):
Hyperparameters set at construction: {'C': 0.5, 'max_iter': 200, 'solver': 'lbfgs', 'class_weight': None} Learned attributes before fit: [] fit returned the same object: True Learned attributes after fit: ['classes_', 'coef_', 'intercept_', 'n_features_in_', 'n_iter_'] classes_: [0, 1, 2] | n_features_in_: 4 | coef_ shape: (3, 4) Prediction for the first row: [0] | probabilities: [[0.97, 0.03, 0.0]] Training accuracy: 0.967 Clone has the same hyperparameters: True Clone learned attributes: [] NotFittedError: This LogisticRegression instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator. ValueError: X has 3 features, but LogisticRegression is expecting 4 features as input. After set_params(C=10.0), C is 10.0 and learned attributes are still present coef_ unchanged until fit runs again: -0.4083 coef_ after refitting with C=10.0: -0.4106
How the Script Works
load_iris(return_X_y=True) returns the 150 rows of four measurements as
X and the three species as y, coded 0, 1 and 2. The model is created
with two hyperparameters; get_params() returns all of them, and the script
prints four, including two defaults: the lbfgs solver and no class
weights.
The learned function lists the object's own attributes whose names end
with an underscore, which is how scikit-learn marks learned attributes.
Before fit the list is empty. fit returns the object it was called on,
so result is model is True; the point of returning it is that
LogisticRegression().fit(X, y) works as one expression. After fit there
are five learned attributes. coef_ has shape (3, 4): one row of four
weights per class, because a three-class logistic regression learns one
weight set per class. n_iter_ records how many optimisation steps the
solver took.
The first row is predicted as class 0 with probability 0.97, and the probabilities for the three classes sum to 1. The training accuracy of 0.967 is a score on the rows the model learned from; the splitting lesson explains why that number flatters.
clone makes a new object with the same hyperparameters and no learned
attributes, so get_params() matches and learned is empty. Calling
predict on it raises NotFittedError, whose message names the class and
tells you to call fit. Passing three columns to a model fitted on four
raises ValueError with the counts in the message: the model checks the
column count every time.
set_params(C=10.0) changes C and nothing else. The learned attributes
are still there and coef_[0, 0] is still -0.4083, the weight learned with
C=0.5. Only after fit runs again does it become -0.4106, the weight for
C=10.0. A fitted model whose hyperparameters you change is stale until you
refit it.
Success: both error lines appear, the clone's learned list is empty, and
the two coef_ values differ only after the second fit.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
ModuleNotFoundError: No module named 'sklearn' | The environment is not active | Activate it; python -c "import sys; print(sys.prefix)" should end in .venv |
AttributeError: ... has no attribute 'coef_' | coef_ read before fit | Fit first; learned attributes do not exist before fit |
ConvergenceWarning printed | max_iter too small for the solver to settle | Raise max_iter; the classification module explains the warning in full |
Learned attributes after fit lists an extra name | A different scikit-learn version | Check python check_setup.py from the setup lesson; the lesson values are for 1.9.1 |
Independent task: add two lines that make a clone, fit it on the first
100 rows only (X[:100], y[:100], which hold classes 0 and 1), and print
its classes_ and the shape of its coef_. Predict both before running.
Reset: if an edit goes wrong, save the file again from this lesson and run it again. Any file a script writes is replaced when it runs again, so nothing needs removing first.
Cleanup: when you have finished the independent task, remove the lesson folder. macOS and Linux:
cd ~/sklearn-practice
ls
rm -rf fit-predict-and-score
Windows PowerShell:
cd $HOME\sklearn-practice
ls
Remove-Item -Recurse fit-predict-and-score
Check that ls lists fit-predict-and-score before you remove it, and leave .venv
and requirements.txt in place for the next lesson.
Check Your Understanding
- Sort these six names into hyperparameters and learned attributes:
max_iter,n_iter_,classes_,C,intercept_,solver. What tells you, without reading the documentation? modelis fitted. You runmodel.set_params(max_iter=500)and thenmodel.predict(X). Does the prediction use the new setting? What do you have to do for it to matter?
Answer and Reasoning
Independent task
half = clone(model).fit(X[:100], y[:100])
print("Clone fitted on two classes:", half.classes_.tolist(), "| coef_ shape:", half.coef_.shape)
Clone fitted on two classes: [0, 1] | coef_ shape: (1, 4)
The clone starts with no learned attributes, so what it learns comes only
from the 100 rows it sees: two classes. A two-class logistic regression
learns one weight set, not one per class, so coef_ has one row of four
weights. The learned attributes describe the data a model was fitted on, not
the data that exists.
Understanding check
- Hyperparameters:
max_iter,C,solver. Learned attributes:n_iter_,classes_,intercept_. The trailing underscore is the signal: the contract reserves it for attributes thatfitcreates. - No.
set_paramschanges the hyperparameter and leaves every learned attribute as it was, sopredictuses the old weights. Callfitagain; only then is the model the one described by its hyperparameters.