高斯方程
函数有三个输入
σ 标准差决定曲线的扁平度
μ 它实际上是钟形曲线的中心点。
x
符号 μ表示总体均值。符号 σ 则是分布标准差,能表示分布状况。如果你还记得统计学里的内容,总体的均值和标准差都是恒定的。对于特定的总体, x 是唯一的变量
python实现高斯概率密度函数
首先,我们将使用自定义的密度函数。 然后,我们将使用SciPy库的实现对结果进行比较
from scipy.stats import norm
import numpy as np
# our solution to calculate the probability density function
def gaussian_density(x, mu, sigma):
return (1/np.sqrt(2*np.pi*np.power(sigma, 2.))) * np.exp(-np.power(x - mu, 2.) / (2 * np.power(sigma, 2.)))
print("Probability density function our solution: mu = 50, sigma = 10, x = 50")
print(gaussian_density(50, 50, 10))
print("\nProbability density function SciPy: mu = 50, sigma = 10, x = 50")
print(norm(loc = 50, scale = 10).pdf(50))
计算概率密度函数下面的面积
norm(loc = 50, scale = 10).cdf(50)
结果是0.5,通过cdf方法,你可以根据输入值,得出从x = 负无穷大到曲线下方的面积,在这种情况下,输入值是50。曲线下方面积为0.5,表示气温介于负无穷大到50度之间的概率为50%。
面积可视化
import matplotlib.pyplot as plt
%matplotlib inline
###
# The plot_fill function plots a probability density function and also
# shades the area under the curve between x_prob_min and x_prob_max.
# INPUTS:
# x: x-axis values for plotting
# x_prob_min: minimum x-value for shading the visualization
# x_prob_max: maximum x-value for shading the visualization
# y_lim: the highest y-value to show on the y-axis
# title: visualization title
#
# OUTPUTS:
# prints out a visualization
###
def plot_fill(x, x_prob_min, x_prob_max, y_lim, title):
# Calculate y values of the probability density function
# Note that the pdf method can accept an array of values from numpy linspace.
y = norm(loc = 50, scale = 10).pdf(x)
# Calculate values for filling the area under the curve
x_fill = np.linspace(x_prob_min, x_prob_max, 1000)
y_fill = norm(loc = 50, scale = 10).pdf(x_fill)
# Plot the results
plt.plot(x, y)
plt.fill_between(x_fill, y_fill)
plt.title(title)
plt.ylim(0, y_lim)
plt.xticks(np.linspace(0, 100, 21))
plt.xlabel('Temperature (Fahrenheit)')
plt.ylabel('probability density function')
plt.show()
average = 50
stdev = 10
y_lim = 0.05
x = np.linspace(0, 100, 1000)
plot_fill(x, 0, 50, y_lim,
'Gaussian Distribution, Average = ' + str(average) + ', Stdev ' + str(stdev))
中心极限定理
如果你从总体中选取足够多的样本,并计算这些样本的均值,这些均值将呈正态分布。只要样本数量足够多,并且问题中的变量是独立和随机的,那么这条定理便能成立
想一想是否要收集现实世界中的数据。如果你想找到世界各地人口的身高分布,你可以测量每个人的身高并分析结果。如果使用该结果的均值,那么你将获得真实的人体高度平均值;然而,要使用这个办法去衡量整个世界人口是不可行的。
相反,你可以使用身高的一个样本。如果只测量了三十人,你的抽样均值可能会与人口平均值相差较大。但是,如果测量了20亿个随机选择的人,那么样本均值可能更接近人口均值。你的样本越大,样本均值就越可能与真实的人口均值相匹配