← Machine learning with Gradio

A model behind an app

Put the penguin model behind a Gradio app: sliders for the measurements, and the app says the species and how sure it is.

Apps that identify plants, birds or songs are a trained model with a simple app in front. You can make one.

A model is only useful if people can use it. Here the model is trained on all the penguins (testing was done last lesson), then a Gradio app (from Apps with Gradio, or Data detective's dashboard) asks for the measurements and shows the guess. predict_proba says how the 5 nearest penguins voted: if 3 of 5 are Chinstrap, it is 60% sure.

PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

app.py
neighbours = ["Gentoo", "Gentoo", "Chinstrap", "Gentoo", "Chinstrap"]
print(neighbours.count("Gentoo") / len(neighbours))

count counts how many times something is in a list. What share of the five neighbours are Gentoo?

What does it print?

RunRun it and compare the result with your prediction.

Run

Run it (scikit-learn takes a few seconds the first time). Move the sliders and press Submit. Find a penguin it is 100% sure about, and one it is not sure about.

app.py
import gradio as gr
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier

penguins = pd.read_csv("penguins.csv")
columns = ["bill_length_mm", "flipper_length_mm"]
model = KNeighborsClassifier(n_neighbors=5)
model.fit(penguins[columns], penguins["species"])


def identify(bill, flipper):
    mystery = pd.DataFrame([[bill, flipper]], columns=columns)
    species = model.predict(mystery)[0]
    sure = round(max(model.predict_proba(mystery)[0]) * 100)
    return species, str(sure) + "% of the 5 nearest penguins are " + species


gr.Interface(
    fn=identify,
    inputs=[
        gr.Slider(30, 60, value=45, step=0.5, label="Bill length (mm)"),
        gr.Slider(170, 235, value=200, step=1, label="Flipper length (mm)"),
    ],
    outputs=[gr.Textbox(label="Species"), gr.Textbox(label="How sure")],
    title="Penguin identifier",
).launch()
Try it yourselfYour edits are saved in this browser.

InvestigateTrace how each line of code connects to what you see.

Investigate

app.py
import gradio as gr
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier

penguins = pd.read_csv("penguins.csv")
columns = ["bill_length_mm", "flipper_length_mm"]
model = KNeighborsClassifier(n_neighbors=5)
model.fit(penguins[columns], penguins["species"])


def identify(bill, flipper):
    mystery = pd.DataFrame([[bill, flipper]], columns=columns)
    species = model.predict(mystery)[0]
    sure = round(max(model.predict_proba(mystery)[0]) * 100)
    return species, str(sure) + "% of the 5 nearest penguins are " + species


gr.Interface(
    fn=identify,
    inputs=[
        gr.Slider(30, 60, value=45, step=0.5, label="Bill length (mm)"),
        gr.Slider(170, 235, value=200, step=1, label="Flipper length (mm)"),
    ],
    outputs=[gr.Textbox(label="Species"), gr.Textbox(label="How sure")],
    title="Penguin identifier",
).launch()

Why there is no test set here.

What the vote share says.

Numbers in the wrong places.

Why is this model trained on all 342 penguins, with no test set?

The app says 60% for some measurements. What does that mean?

A penguin with bill 47 and flipper 215 (very like a Gentoo) is identified as Chinstrap. Click the line that is wrong.

ModifyChange the code on purpose and check the result.

Modify

Add bill depth as a third measurement. Is the app surer now?

Need a hint?

Add "bill_depth_mm" to columns, a depth parameter to identify, and depth to the mystery row.

Another hint

Add a third slider: gr.Slider(13, 22, value=17, step=0.1, label="Bill depth (mm)").

When fewer than 80% of the neighbours agree, show Not sure instead of a species.

Need a hint?

If sure < 80, return "Not sure" as the species (and still show the vote).

Try it yourselfYour edits are saved in this browser.

Add bill depth as a third measurement: in the model, the function and a slider.

    Run your program. This ticks when your code does all of the above.

    Say Not sure when fewer than 80% of the neighbours agree.

      Run your program. This ticks when your code does all of the above.

      MakeBuild something new using what you have learned. Expect a few tries; that is normal.

      A model app of your own

      Build an app around a model of your own: predict a penguin's sex or island from measurements you choose. (Some penguins have no sex recorded: penguins.dropna() leaves them out.) Test it first, as in Lesson 4, and put the accuracy in the app's title.

      Try it yourselfYour edits are saved in this browser.

      Build an app around a model of your own: choose what it predicts and from which measurements.

        Run your program. This ticks when your code does all of the above.

        Info

        Where this leads

        On a computer, this file runs in real Gradio (pip install gradio scikit-learn pandas), and a teacher can host it as a Hugging Face Space for the class to try.

        Your app is 94% accurate. A user tries a penguin species that is not in the data. What happens?

        For teachers

        Students put a 5-nearest-neighbour penguin model behind a Gradio app with sliders, show how sure it is with predict_proba, then add bill depth, answer "Not sure" below 80%, and build an app around a model of their own (sex or island). About 45 minutes.

        Open the teacher guide: answers, solutions, slides and a worksheet.

        Students will be able to

        Before class

        Read the unit primer first. The model is trained on all 342 penguins (the method was tested fairly in Lesson 4; for use, a model should learn from all the data). The app's function turns the slider values into a one-row table with the training columns, then predict gives the species and predict_proba the share of the 5 neighbours voting for each species (the Predict works one out by hand). The bug task puts the numbers in the wrong order: the model reads by position, so it sees a 215 mm bill and answers wrongly without any error. In the Make, penguins.dropna() drops the penguins with no sex recorded. On a computer, pip install gradio scikit-learn pandas runs the same file; a teacher can host it as a Hugging Face Space (accounts need age 13+).

        Running the lesson

        1. Run: have students find the most and least certain measurements, and compare.
        2. Investigate: ask what a 60% answer should tell the user.
        3. Make: insist on a fair test (Lesson 4) before the app, and the accuracy in the title.

        The hard part (on purpose)

        Keeping columns, parameters and sliders in the same order. Ask them to read the three lists side by side.

        When students get stuck

        Stretch and support

        Stretch: Show the three species' vote shares as a bar chart (gr.BarPlot with a small DataFrame), or add a Dropdown to choose the model (neighbours or tree).

        Support: Give students the third slider line, and ask them to add the column and the parameter.

        Where it leads

        The optional last lesson looks at what models get wrong. The micro:bit and the computer course trains a model on movement with Teachable Machine.

        What each step is for

        Now you can
        Next lesson6. What models get wrongFind where the penguin model fails: a species it has never seen, impossible measurements and harder questions, and learn to say what a model cannot do.