要绘制正态分布随机变量的 CDF 的 sigmoidal 结果,我不应该使用 matplotlib 的 hist() 函数。相反,我可以使用bar() 函数来绘制我的结果。
@Laaggan 和@dumbPy 的回答指出,使用正则化和有序的 x 值是推导 sigmoidal cdf 曲线的方法。虽然通常这样做,但在使用随机变量时不适用。我已经将他们提到的方法的解决方案与我所做的进行了比较,以表明两种方法都给出了相同的结果。但是,我的结果(见下图)确实表明,与使用随机变量相比,获取 cdf 值的常用方法会产生更多的正态分布极值。排除两个极端后,出现的事件似乎是均匀分布的。
我已经修改了我的脚本并提供了 cmets 来演示我如何比较这两种方法。我希望我的回答能对正在学习使用scipy.stats.norm 类的rvs()、pdf() 和cdf() 函数的其他人有所帮助。
import numpy as np
from numpy.random import default_rng
from scipy.stats import norm
import matplotlib.pyplot as plt
mu = 0
sigma = 1
samples = 1000
rg = default_rng( 12345 )
a = rg.random(size=samples) #Get a uniform distribution of numbers in the range of 0 to 1.
print( 'a = ', a)
# Get pdf and cdf values using normal random variates.
rg = default_rng( 12345 ) #Recreate Bit Generator to ensure a same starting point
b_pdf = norm.rvs( loc=mu, scale=sigma, size=samples, random_state=rg ) #Get pdf of normal distribution(mu=0, sigma=1 gives -3.26 to +3.26).
b_cdf = norm.cdf( b_pdf, loc=mu, scale=sigma ) #get cdf of normal distribution using pdf values (always gives between 0 to 1).
print( 'b_pdf = ', b_pdf)
print( 'b_cdf = ', b_cdf)
#To check b is normally distributed. Using the ordered x (commonly practiced):
c_x = np.linspace( mu - 3.26*sigma, mu + 3.26*sigma, samples )
c_pdf = norm.pdf( c_x, loc=mu, scale=sigma )
c_cdf = norm.cdf( c_x, loc=mu, scale=sigma )
print( 'c_x = ', c_x )
print( 'c_pdf = ', c_pdf )
print( 'c_cdf = ', c_cdf )
fig, ax = plt.subplots(3, 1)
bins=np.linspace( 0, 1, num=10 )
acount, abins, aignored = ax[0].hist( a, bins=50, histtype='bar', label='a', color='C0', alpha=0.2, density=True )
bcount, bbins, bignored = ax[0].hist( b_cdf, bins=50, histtype='bar', label='b_cdf', color='C1', alpha=0.2, density=True )
ccount, cbins, cignored = ax[0].hist( c_cdf, bins=50, histtype='bar', label='c_cdf', color='C2', alpha=0.2, density=True )
bcount, bbins, bignored = ax[1].hist( b_pdf, bins=20, histtype='bar', label='b_pdf', color='C1', alpha=0.4, density=True )
cpdf_line = ax[1].plot(c_x, c_pdf, label='c_pdf', color='C2')
bpdf_bar = ax[2].bar( b_pdf, b_cdf, label='b_cdf', color='C1', alpha=0.4, width=0.01)
ccdf_line = ax[2].plot(c_x, c_cdf, label='c_cdf', color='C2')
print( 'acount, abins, aignored = ', acount, abins, aignored)
print( 'bcount, bbins, bignored = ', bcount, bbins, bignored)
print( 'ccount, cbins, cignored = ', ccount, cbins, cignored)
ax[0].legend(loc='upper left')
ax[1].legend(loc='upper left')
ax[2].legend(loc='upper left')
plt.show()