Menu
CoddyTech

Fit and Predict

Part of the Supervised Learning section of Coddy's Machine Learning journey. Lesson 3 of 58.

Every scikit-learn model works in two calls. fit studies the training rows with their labels; predict labels rows the model has never seen:

A diagram: six pets, X_train with weight and ear length beside y_train, three cats and three dogs, go through fit into a model. Two new pets, X_new, go through predict, using the model, and come out as cat and dog

The model from this journey's first lesson is k-nearest neighbors: it labels a row like the training rows closest to it. Pets by weight (kg) and ear length (cm):

from sklearn.neighbors import KNeighborsClassifier

X_train = np.array([[4, 6], [5, 7], [3, 5], [30, 10], [25, 12], [35, 11]])
y_train = np.array(["cat", "cat", "cat", "dog", "dog", "dog"])
model = KNeighborsClassifier()
model.fit(X_train, y_train)
print(model.predict([[6, 6], [28, 11]]))

This prints ['cat' 'dog']. New rows go in as a table, one row per pet.

Make, fit, predict: every model in this section follows these three steps.

challenge icon

Challenge

Easy

A birdwatching club's app names birds from wingspan and weight. The starter splits the club's birds.csv and reads tonight's birds into the table spotted.

  1. Make a k-nearest neighbors model and fit it on the training birds.
  2. Predict every spotted bird in one call.
  3. Print one line per bird, as below.

For three birds on another walk:

Bird 1: sparrow
Bird 2: blackbird
Bird 3: robin

Try it yourself

import pandas as pd
from sklearn.model_selection import train_test_split

# One row per bird the club has named: wingspan in cm, weight in grams
birds = pd.read_csv("birds.csv")
X = birds[["wingspan_cm", "weight_g"]]
y = birds["species"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

# Tonight's walk: how many birds, then each one's wingspan and weight
count = int(input())
spans = []
weights = []
for i in range(count):
    spans.append(float(input()))
    weights.append(float(input()))
spotted = pd.DataFrame({"wingspan_cm": spans, "weight_g": weights})

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Supervised Learning

Practice on your own: Online Python compiler