TExcelTAD
Home › Machine Learning › ML Data Distribution

ML Data Distribution

Real data sets in machine learning often have thousands or millions of rows. You cannot read them value by value, so you summarise their distribution: which values occur, and how often. In this lesson you will generate larger data sets with NumPy and look at their shape with a histogram.

Generating random data — reproducibly

When you don't have real data, or you want to test an idea, you can create random data. NumPy's modern API uses a random generator object. Passing a seed makes the "random" numbers identical on every run — essential for reproducible experiments (and for this course, where every output must match):

python · try it yourself
import numpy as np

rng = np.random.default_rng(42)       # seeded generator
print(rng.uniform(0, 10, size=5))     # 5 floats between 0 and 10

rng = np.random.default_rng(42)       # same seed ...
print(rng.uniform(0, 10, size=5))     # ... same numbers

print(rng.integers(1, 7, size=10))    # 10 dice rolls (1..6)
[7.73956049 4.3887844  8.5859792  6.97368029 0.94177348]
[7.73956049 4.3887844  8.5859792  6.97368029 0.94177348]
[4 6 5 5 5 5 4 1 6 3]

uniform(low, high, size) draws numbers where every value in the range is equally likely. integers(low, high, size) does the same for whole numbers; note that high is excluded.

Counting values with a histogram

A histogram splits the range into bins and counts how many values fall into each. NumPy can compute the counts directly:

python · try it yourself
import numpy as np

rng = np.random.default_rng(7)
rolls = rng.integers(1, 7, size=600)       # 600 dice rolls

values, counts = np.unique(rolls, return_counts=True)
for v, c in zip(values, counts):
    print(v, "#" * (c // 5), c)
1 ################### 97
2 ################## 94
3 ################## 91
4 ##################### 107
5 #################### 102
6 ##################### 109

Each face comes up roughly 100 times: a fair die produces a uniform distribution.

Drawing a histogram

Matplotlib's hist() does the binning and the drawing in one step. Let's simulate the waiting time (in minutes) of 2 000 people at a bus stop where a bus comes every 15 minutes, so any waiting time from 0 to 15 is equally likely:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(0)
waits = rng.uniform(0, 15, size=2000)

counts, edges, _ = plt.hist(waits, bins=15, edgecolor="white")
plt.xlabel("Waiting time (minutes)")
plt.ylabel("Number of people")
plt.title("Uniform distribution of waiting times")
plt.show()

print("smallest bin count:", int(counts.min()))
print("largest bin count: ", int(counts.max()))
print("bin edges:", edges[:4].round(1), "...")
smallest bin count: 117
largest bin count:  154
bin edges: [0. 1. 2. 3.] ...

Every bar has a similar height — the signature of a uniform distribution. With more samples the bars would become even flatter.

Choosing the number of bins

The number of bins changes how a histogram looks. Too few bins hide the shape; too many make it noisy. Here is the same data with different bin counts:

python · try it yourself
import numpy as np

rng = np.random.default_rng(3)
data = rng.uniform(0, 1, size=200)

for bins in [2, 5, 20]:
    counts, _ = np.histogram(data, bins=bins)
    print(f"{bins:2} bins -> {counts.tolist()}")
 2 bins -> [95, 105]
 5 bins -> [34, 43, 44, 46, 33]
20 bins -> [5, 10, 9, 10, 10, 11, 10, 12, 9, 9, 12, 14, 7, 16, 13, 10, 9, 9, 8, 7]

A common starting point is bins="auto", which lets NumPy/Matplotlib pick a sensible number based on the data size.

Not every distribution is flat

Most real data is not uniform. Incomes, website visit lengths and file sizes have many small values and a long tail of large ones — a skewed distribution. The exponential distribution is a simple example:

python · try it yourself
import numpy as np

rng = np.random.default_rng(11)
visit_seconds = rng.exponential(scale=60, size=1000)   # average visit: about 60 s

counts, edges = np.histogram(visit_seconds, bins=[0, 30, 60, 120, 240, 600])
for lo, hi, c in zip(edges[:-1], edges[1:], counts):
    print(f"{lo:4.0f}-{hi:4.0f} s: {c}")
print(f"mean = {visit_seconds.mean():.1f} s, median = {np.median(visit_seconds):.1f} s")
   0-  30 s: 401
  30-  60 s: 242
  60- 120 s: 226
 120- 240 s: 112
 240- 600 s: 19
mean = 59.0 s, median = 40.9 s

The mean is noticeably larger than the median: the long tail pulls it upward, just like the outlier in the Mean Median Mode lesson.

Note: Knowing the shape of a feature's distribution helps you pick a model and a preprocessing step. Heavily skewed features are often transformed (for example with np.log1p) before training.

Test yourself

Why do we pass a seed such as np.random.default_rng(42)?

  1. To make the numbers more random
  2. To get the same random numbers on every run
  3. To speed up NumPy
  4. To limit numbers to 0..42

What does rng.integers(1, 7, size=3) produce?

  1. Three integers from 1 to 7 inclusive
  2. Three integers from 1 to 6
  3. Seven integers
  4. Three floats between 1 and 7

In a histogram, what does the height of a bar show?

  1. The value of one data point
  2. How many values fall into that bin
  3. The mean of the data
  4. The standard deviation