CodeBlanks Logo Icon CodeBlanks

Summary - scikit-learn

In this group you learned the scikit-learn estimator API.

Summary: scikit-learn

In this group:

  • The shared interface: fit, predict, transform, score; models swap with one line.
  • Estimator roles: predictor, transformer; hyperparameters in the constructor, learned values with _.
  • clone, get_params, set_params.
  • predict_proba, decision_function; reshape(1, -1) for a single example.
  • The default score; custom scorers with get_scorer and make_scorer.

Practice Comparison on synthetic data

Generate data with make_moons(n_samples=300, noise=0.25, random_state=0) and split it with test_size=0.3, random_state=0. Train LogisticRegression() and SVC(); on each line print the class name and the test accuracy with round(..., 3).

Starter code

model.py
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC

# buraya yaz

Sample solution

model.py
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC

X, y = make_moons(n_samples=300, noise=0.25, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
for m in [LogisticRegression(), SVC()]:
    m.fit(X_train, y_train)
    print(type(m).__name__, round(m.score(X_test, y_test), 3))

Expected output

LogisticRegression 0.844
SVC 0.967

Questions and answers

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

1 Why does cross-validation use <code>clone</code> in every fold?

  • To share the weights
  • It doesn't
  • So every fold starts with a clean, untrained model Correct answer
  • Because it is fast

Explanation: What was learned in the previous fold must not affect the next fold's score.

2 Get the F1 scorer by name.

Question
olcut = ____("f1_macro")
Answer
olcut = get_scorer("f1_macro")

Explanation: get_scorer returns the same scorer as the names in the scoring parameter.

3 Match the tools.

Term Meaning
make_classification Synthetic data
clone Clean copy
decision_function Raw score
make_scorer Custom metric

All lessons in Intermediate