Sub topic 2
Estimators and the `fit` Method
This chapter assumes basic Python, NumPy shapes, pandas DataFrames, and the idea of supervised learning. In scikit-learn, an estimator is an object that learns from data. Its constructor sets options, and its fit method learns from examples.
Estimators and the `fit` method
A supervised-learning dataset usually has a feature matrix X and a target vector y. X contains the inputs, while y contains the answers. Calling fit(X_train, y_train) trains an estimator.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
print(model.predict(X_test[:5]))
print(model.score(X_test, y_test))predict returns a prediction for each row. For a classifier, score usually returns accuracy. For a regressor, it commonly returns the coefficient of determination, or R². The exact scoring behavior depends on the estimator.
Hyperparameters and fitted attributes
A hyperparameter is a setting chosen before training. For example, max_iter=200 limits the number of optimization iterations. Fitted attributes are values learned during fit; scikit-learn commonly names them with a trailing underscore, such as coef_.
print(model.get_params()["max_iter"]) # constructor setting
print(model.coef_.shape) # learned after fitTransformers
A transformer changes data. fit learns transformation values, transform applies them, and fit_transform performs both on the same data.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)The scaler learns means and variances from X_train only. Reusing those values for X_test keeps the evaluation independent.
Exercise
Why should you call transform, rather than fit_transform, on test data?
Show answer
transform reuses values learned from the training data, while fit_transform would learn from the test data and cause leakage.