经验分布
在数据科学中,“经验”一词意为“观察到的”。经验分布是观察数据的分布,例如随机样本中的数据。
在本节中,我们将生成数据并观察经验分布的样子。
我们的场景是一个简单的实验:多次掷一颗骰子并记录朝上的面。表格 die 包含骰子面上的点数。所有数字恰好出现一次,因为我们假设骰子是公平的。
from datascience import *
path_data = '../../../assets/data/'
import matplotlib
matplotlib.use('Agg')
%matplotlib inline
import matplotlib.pyplot as plots
plots.style.use('fivethirtyeight')
import numpy as np
die = Table().with_column('Face', np.arange(1, 7, 1))
die
Face
1
2
3
4
5
6概率分布
下面的直方图帮助我们直观地看到每个面出现的概率为 1/6。我们说这个直方图显示了概率在所有可能面上的“分布”。由于所有条形代表相同的概率百分比,该分布被称为“在整数 1 到 6 上的均匀分布”。
die_bins = np.arange(0.5, 6.6, 1)
die.hist(bins = die_bins)
Histogram with 'Face' on the x-axis with bars of width 1 centered on labels from 1 to 6 and 'Percent per unit' on the y-axis. All the bars are the same height between y-axis labels 15 and 17.5.连续值之间以相同固定间隔分隔的变量,例如掷骰子的值(连续值之间间隔 1),属于称为“离散”的一类变量。上面的直方图称为“离散”直方图。它的箱由数组 die_bins 指定,确保每个条形以相应的整数值为中心。
重要的是要记住,骰子不能显示 1.3 点或 5.2 点——它总是显示整数点数。但我们的可视化将每个值的概率分布在条形的面积上。虽然这在课程的现阶段可能看起来有些随意,但它将在以后当我们对离散直方图叠加平滑曲线时变得重要。
在继续之前,让我们确保轴上的数字是合理的。每个面的概率是 1/6,四舍五入到两位小数是 16.67%。每个箱的宽度为 1 个单位。因此每个条形的高度是每单位 16.67%。这与图形的水平和垂直标度一致。
经验分布
上面的分布由每个面的理论概率组成。它被称为“概率分布”,不基于观察数据。无需掷任何骰子即可研究和理解它。
另一方面,“经验分布”是观察数据的分布。它们可以通过“经验直方图”进行可视化。
让我们通过模拟掷骰子来获取一些数据。这可以通过从 1 到 6 的整数中随机放回地抽样来实现。我们之前曾使用 np.random.choice 进行过此类模拟。但现在我们将介绍一种实现此目的的 Table 方法。这将使我们更容易使用我们熟悉的 Table 方法进行可视化。
这个 Table 方法叫做 sample。它以随机放回的方式从表格的行中抽取。它的参数是样本大小,并返回一个由所选行组成的表格。可选参数 with_replacement=False 指定样本应该无放回地抽取。但这不适用于掷骰子。
以下是掷骰子 10 次的结果。
die.sample(10)
Face
2
4
5
5
1
6
1
4
6
5我们可以使用相同的方法模拟任意多次掷骰子,然后绘制结果的直方图。因为我们将反复这样做,我们定义一个函数 empirical_hist_die,它以样本大小为参数,掷骰子相应次数,然后绘制观察结果的直方图。
def empirical_hist_die(n):
die.sample(n).hist(bins = die_bins)
经验直方图
这是 10 次投掷的经验直方图。它看起来不太像上面的概率直方图。多次运行该单元格以查看它如何变化。
empirical_hist_die(10)
Histogram with 'Face' on the x-axis with bars of width 1 centered on labels from 1 to 6 and 'Percent per unit' on the y-axis. The tallest bar is at 40 and centered at 2. The bars centered at 3 and 6 each have height 20 and the bars centered at 4 and 5 have height of 10. There is no bar centered at 1.当样本量增加时,经验直方图开始看起来更像理论概率的直方图。
empirical_hist_die(100)
Histogram with 'Face' on the x-axis with bars of width 1 centered on labels from 1 to 6 and 'Percent per unit' on the y-axis. The height of the bars centered at 1 and 5 is the same and just below 20. The height of the bar centered at 2 is above 20. The height of the bar centered at 3 is just below 15. The height of the bar centered at 4 is just above 15. The height of the bar centered at 6 is just below 10.empirical_hist_die(1000)
Histogram with 'Face' on the x-axis with bars of width 1 centered on labels from 1 to 6 and 'Percent per unit' on the y-axis. The heights of the bars are variable, but all are between 15 and 18.随着我们增加模拟中的投掷次数,每个条形的面积越来越接近 16.67%,即概率直方图中每个条形的面积。
平均律
我们上面观察到的是一个被称为“平均律”的一般规则的一个实例:
如果一个随机实验在相同条件下独立重复,那么从长远来看,事件发生的频率会越来越接近该事件的理论概率。
例如,从长远来看,出现四点面的比例越来越接近 1/6。
这里“独立且条件相同”意味着每次重复都以相同的方式进行,无论所有其他重复的结果如何。
在这些条件下,上述定律意味着如果随机实验重复大量次数,那么事件发生的频率极有可能接近该事件的理论概率。