Menu
CoddyTech

Predicting with a Line

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

A fitted line is a small prediction machine: put in a new x, get back a y. A puppy was weighed from week 8 to week 20:

weeks = np.array([8, 10, 12, 14, 16, 18, 20])
kg = np.array([3.1, 4.0, 5.2, 6.1, 7.0, 8.2, 9.1])
slope, intercept = np.polyfit(weeks, kg, 1)
new_weeks = np.array([15, 52])
print(np.round(slope * new_weeks + intercept, 1))

This prints [ 6.6 25.2]. Week 15 sits inside the data. Week 52 does not, and the line keeps climbing long after the dog stops:

Seven weighings from week 8 to 20 on a fitted line. The line continues dashed into a shaded zone marked outside the data, reaching 25.2 kg at week 52, while a dotted curve of a real dog levels off near 13 kg

Predicting outside the data's range is extrapolation, and risky: a model is trustworthy only on inputs like the ones it learned from. Check first:

week = 52
print(week >= weeks.min() and week <= weeks.max())

This prints False.

challenge icon

Challenge

Medium

A candle was measured every hour as it burned, from hour 0 to hour 6: hours and height in cm. The program reads new_hours.

  1. Fit the line that predicts height from hours.
  2. Print its prediction for new_hours, rounded to 2 decimals.
  3. Print whether new_hours lies inside the data's hours, both ends included.

For the input 4.5:

Predicted height: 13.07 cm
Inside the data: yes

Try it yourself

import numpy as np

hours = np.array([0, 1, 2, 3, 4, 5, 6])
height = np.array([20.0, 18.4, 17.1, 15.3, 13.9, 12.2, 10.8])
new_hours = float(input())

# 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