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:
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
MediumA candle was measured every hour as it burned, from hour 0 to hour 6: hours and height in cm. The program reads new_hours.
- Fit the line that predicts
heightfromhours. - Print its prediction for
new_hours, rounded to 2 decimals. - Print whether
new_hourslies inside the data's hours, both ends included.
For the input 4.5:
Predicted height: 13.07 cm
Inside the data: yesTry 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Statistics for ML
1Center and Spread
Mean and MedianPercentiles and QuartilesVariance and StdSample or Population?The Most Common ValueRecap: Delivery Times4Samples and Populations
Population and SampleSample Means VaryThe Sampling DistributionBigger Samples, Less NoiseRecap: Polling a Town7Trend Lines
ResidualsLeast Squares FitDrawing the FitPredicting with a LineHow Good Is the Fit?Recap: Practice Hours2Distributions
Density HistogramsShapes of DataThe Normal CurveThe 68-95-99.7 RuleZ-ScoresRecap: Battery Life3Probability by Simulation
Probability as FrequencyThe Law of Large NumbersSums of DiceExpected ValueConditional ProbabilityRecap: Dice Stall Odds6Relationships
Reading Scatter PlotsCorrelationCorrelation MatrixCorrelation HeatmapsCorrelation Is Not CauseRecap: Ice Cream and SunPractice on your own: Online Python compiler