Menu
CoddyTech

Drawing the Fit

Part of the Statistics for ML section of Coddy's Machine Learning journey. Lesson 37 of 64.

Two numbers describe a fit; only a chart shows if it follows the data. A kitchen timed six kettle boils. Draw the line on the same ax as the scatter:

liters = np.array([0.5, 0.8, 1.0, 1.2, 1.5, 1.7])
minutes = np.array([1.6, 2.4, 2.7, 3.3, 3.9, 4.5])
slope, intercept = np.polyfit(liters, minutes, 1)
xs = np.linspace(liters.min(), liters.max(), 50)
fig, ax = plt.subplots()
ax.scatter(liters, minutes, label="Boils")
ax.plot(xs, slope * xs + intercept, color="C1", label="Fit")
ax.legend()
plt.show()

xs runs from the smallest x to the largest, so the line starts and ends where the data does:

Six kettle boils as dots, minutes to boil against liters of water, rising from 1.6 to 4.5 minutes, with an orange fitted line running through them from 0.5 to 1.7 liters

Drawing a model's predictions over its data is the quickest check that it learned something sensible. A line that misses the dots means a broken fit.

challenge icon

Challenge

Medium

A building manager timed 12 elevator rides: floors traveled and seconds taken. The starter sets up the titled, labelled chart.

  1. Fit the line that predicts seconds from floors.
  2. Draw the rides as a scatter labelled Rides, and the line labelled Fit, from the fewest floors to the most.
  3. Add a legend and show the chart.

It prints nothing; Coddy describes your chart. Another building's looks like this:

A chart titled Elevator Rides: eight dots rising from 14 seconds at 2 floors to 51 seconds at 20 floors, a fitted line from the first dot's floor to the last, and a legend naming Rides and Fit

Try it yourself

import numpy as np
import matplotlib.pyplot as plt

floors = np.array([3, 7, 1, 12, 5, 9, 15, 2, 10, 6, 13, 8])
seconds = np.array([15.3, 27.0, 12.4, 36.0, 19.5, 28.8, 44.9, 12.7, 33.2, 19.4, 41.7, 27.0])
# Don't change the lines below
fig, ax = plt.subplots()
ax.set_title("Elevator Rides")
ax.set_xlabel("Floors")
ax.set_ylabel("Seconds")

# 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 Statistics for ML

Practice on your own: Online Python compiler