CodeBlanks Logo Icon CodeBlanks

Summary - ML fundamentals

In this group you learned the definition, types, and core concepts of ML.

Summary: the ML workflow

In this section you saw the basic machine learning loop:

  1. Prepare the data as X (two-dimensional) and y (one-dimensional).
  2. Split it into training and test sets with train_test_split.
  3. Train the model with fit(X_train, y_train).
  4. Predict with predict and measure on the test set with score.
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0)
model = KNeighborsClassifier().fit(X_tr, y_tr)
print(model.score(X_te, y_te))

Practice End to end

Split the data with test_size=0.25, random_state=0, train a KNeighborsClassifier(n_neighbors=3) and print the test accuracy.

Starter code

model.py
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

X = [[i] for i in range(40)]
y = [0 if i < 20 else 1 for i in range(40)]

# buraya yaz

Sample solution

model.py
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

X = [[i] for i in range(40)]
y = [0 if i < 20 else 1 for i in range(40)]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
model = KNeighborsClassifier(n_neighbors=3)
model.fit(X_train, y_train)
print(model.score(X_test, y_test))

Expected output

1.0

Questions and answers

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

1 With which data should the model's success be measured?

  • There's no need to measure
  • With test data not used in training Correct answer
  • With the training data
  • With all the data

Explanation: Real success is success on examples the model has never seen.

2 Measure success on the test set.

Question
print(model.____(X_test, y_test))
Answer
print(model.score(X_test, y_test))

Explanation: score gives accuracy for classifiers and the R² value for regression models.

3 Match the steps with their methods.

Term Meaning
Splitting train_test_split
Training fit
Prediction predict
Measuring score

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation