Several Classes
Part of the Supervised Learning section of Coddy's Machine Learning journey. Lesson 19 of 58.
Lemon, lime or orange? Logistic regression handles three classes too. Here a new fruit lands between the lemons and the oranges:
model = LogisticRegression(max_iter=1000)
model.fit(X, kind) # X: diameter, weight; kind: lemon, lime or orange
print(model.classes_)
print(np.round(model.predict_proba([[6.7, 144]]), 2))
print(model.predict([[6.7, 144]]))This prints:
['lemon' 'lime' 'orange']
[[0.61 0. 0.39]]
['lemon']Each row holds one chance per class, in classes_ order, and they add up to 1. predict picks the largest.
So the model says how sure it is: 61% lemon is a close call, worth a second look.
Challenge
MediumA podcast app files new episodes under comedy, news or true crime. The starter fits a LogisticRegression on episodes.csv (length, speakers, laughs per minute) and reads a new episode into episode, a one-row table.
Complete describe(episode):
- Print each show type's chance, in
model.classes_order, to a whole percent. - Return the most likely type.
For another app's episode:
comedy: 12%
news: 70%
true crime: 18%
Best guess: newsTry it yourself
import pandas as pd
from sklearn.linear_model import LogisticRegression
episodes = pd.read_csv("episodes.csv")
features = ["length_min", "speakers", "laughs_per_min"]
model = LogisticRegression(max_iter=1000)
model.fit(episodes[features], episodes["show_type"])
# Prints each show type's chance for one episode (a one-row table), then returns the most likely type
def describe(episode):
# Write your code here
return "unknown"
# Don't change the lines below: a new episode, from the input
length = float(input())
speakers = int(input())
laughs = float(input())
episode = pd.DataFrame({"length_min": [length], "speakers": [speakers], "laughs_per_min": [laughs]})
best = describe(episode)
print(f"Best guess: {best}")
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 Sorter4Logistic Regression
Yes-or-No PredictionsThe Decision ThresholdWeights as EvidenceSeveral ClassesRecap: Spam Filter2Nearest 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