CodeBlanks Logo Icon CodeBlanks

The fit method

The fit() method learns the model from training data.

fit: the moment of learning

fit(X, y) changes the estimator's state and returns self. Unsupervised estimators take only X. Some models also accept sample_weight for weighted learning:

m = LogisticRegression().fit(X, y)
KMeans(n_clusters=3, n_init=10).fit(X)          # no y
m.fit(X, y, sample_weight=agirliklar)          # some examples matter more

fit validates its inputs: a shape mismatch, NaN or text values produce understandable errors.

fit_transform and n_features_in_

For transformers, fit_transform does fit + transform in one step (often faster). After fit, n_features_in_ stores the expected number of features; calling predict with a different number of columns raises an error:

sc = StandardScaler()
Z = sc.fit_transform(X_train)
print(sc.n_features_in_)   # 4
# sc.transform(X_train[:, :3])  ValueError: 4 features expected

fit_transform is only used on training data; transform is always applied to test data.

Practice Weighted training

Train a LinearRegression on the same data first without weights, then giving the last example a weight of 100. Print the two slopes (coef_[0]) with round(..., 3) on separate lines.

Starter code

model.py
import numpy as np
from sklearn.linear_model import LinearRegression

X = np.array([[1], [2], [3], [4]])
y = np.array([1, 2, 3, 10])
w = np.array([1, 1, 1, 100])

# buraya yaz

Sample solution

model.py
import numpy as np
from sklearn.linear_model import LinearRegression

X = np.array([[1], [2], [3], [4]])
y = np.array([1, 2, 3, 10])
w = np.array([1, 1, 1, 100])

a = LinearRegression().fit(X, y)
b = LinearRegression().fit(X, y, sample_weight=w)
print(round(a.coef_[0], 3))
print(round(b.coef_[0], 3))

Expected output

2.8
3.56

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a <code>fit</code> call return?

  • None
  • The estimator itself Correct answer
  • The predictions
  • The score

Explanation: That is why the chain m = Model().fit(X, y) can be written.

2 Train while weighting the examples.

Question
m.fit(X, y, ____=w)
Answer
m.fit(X, y, sample_weight=w)

Explanation: sample_weight scales each example's contribution to the loss.

3 Match the attributes and methods.

Term Meaning
fit Learns, returns self
fit_transform Learn and transform
n_features_in_ Expected column count
sample_weight Example weights

All lessons in Intermediate