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:
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
EasyA 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.
- Make a k-nearest neighbors model and fit it on the training birds.
- Predict every spotted bird in one call.
- Print one line per bird, as below.
For three birds on another walk:
Bird 1: sparrow
Bird 2: blackbird
Bird 3: robinTry 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Supervised Learning
1Your First Model
Learning from ExamplesTrain and Test SetsFit and PredictScoring a ModelRecap: Seed Sorter2Nearest Neighbors
How k-NN DecidesChoosing kDecision BoundariesScaling for NeighborsRecap: Wine Neighbors5Measuring Classifiers
The Confusion MatrixPrecision and RecallThe F1 ScoreImbalanced ClassesROC CurvesRecap: Screening Test11Project: Penguin Species
Meet the PenguinsPrepare the DataChoose a ModelTune the WinnerShip the ModelPractice on your own: Online Python compiler