Menu
CoddyTech

Population and Sample

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

Weighing the apples of 300 trees takes days; weighing 20 trees takes an hour. All the trees are the population, the 20 a sample:

An orchard of 300 apple trees drawn as a grid of pale cells, with 20 cells scattered at random shaded dark: the sample

rng.choice draws the sample. replace=False picks each tree at most once, like names from a hat:

rng = np.random.default_rng(4)
trees = np.round(rng.normal(40, 8, size=300), 1)  # kg of apples
sample = rng.choice(trees, size=20, replace=False)
print(np.round(trees.mean(), 2))
print(np.round(sample.mean(), 2))

This prints:

40.82
38.49

The sample mean estimates the population mean: close, not equal. Every ML dataset is a sample, and this chapter ends by polling a whole town.

challenge icon

Challenge

Medium

A wool farm wants its 3000 sheep's average fleece without weighing them all. In this simulation fleeces holds every sheep's fleece in grams, and the program reads a sample size.

  1. Draw a sample of that many different sheep with rng.choice.
  2. Print its mean, the mean of all the sheep, and how far off it is (sample minus all), to 2 decimals.

For another farm and 30:

Sample of 30 sheep: 4371.33 g
All 3000 sheep: 4311.47 g
Off by: 59.86 g

Try it yourself

import numpy as np

size = int(input())

# Don't change the lines below: the fleece weight in grams of every sheep on the farm
rng = np.random.default_rng(19)
fleeces = np.round(rng.normal(4500, 800, size=3000))

# 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