Menu
CoddyTech

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:

Left: 45 fruits by diameter and weight, limes small, lemons in the middle, oranges large, and a black star for a new fruit between lemons and oranges. Right: its chances as bars, lemon 0.61, lime 0.00, orange 0.39

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 icon

Challenge

Medium

A 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):

  1. Print each show type's chance, in model.classes_ order, to a whole percent.
  2. Return the most likely type.

For another app's episode:

comedy: 12%
news: 70%
true crime: 18%
Best guess: news

Try 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}")
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