• 正态分布,二维正态分布,卡方分布,学生t分布——概率分布学习 python


    目录

    基本概念

    概率密度函数(PDF: Probability Density Function)

    累积分布函数(CDF: Cumulative Distribution Function)

    核密度估计((kernel density estimation)

    1.正态分布

    概率密度函数(pdf)

    正态分布累积分布函数(CDF)

    正态分布核密度估计(kde)

    正态分布四则运算

    二维正态分布(逐渐补充)

    马氏距离

    2.卡方分布

    概率密度函数(pdf):

     卡方分布表:

    卡方分布相关计算

    生成卡方分布随机数

    3.学生t分布

    概率密度函数(pdf):


    基本概念

    概率密度函数(PDF: Probability Density Function)

    连续随机变量的概率分布特性。

    累积分布函数(CDF: Cumulative Distribution Function)

    在x点左侧事件发生的总和。

    CDF特性:

    ①因为累计分布函数是计算x点左侧的点的数量,所以累计分布函数CDF是单调递增的。

    ②所有的CDF中,在x趋近-∞时,CDF趋近于0,当x趋近+∞时,CDF趋近于1。

    ③对于给定的数据集,CDF是唯一的

    核密度估计((kernel density estimation)

    核密度估计(kernel density estimation,KDE)是在概率论中用来估计未知的密度函数,属于非参数检验方法之一,通过核密度估计图可以比较直观的看出数据样本本身的分布特征。

    scipy中的stats.gaussian_kde可以计算高斯核函数的密度函数,而且提供了直接计算区间的累计密度函数,integrate_box_1d(low=-np.Inf, high=x)。

    1.正态分布

    表示为:N\sim \left ( \mu ,\sigma^2 \right ),其中期望为μ,方差为\sigma^2

    概率密度函数(pdf)

    f(x)=\frac{1}{\sigma \sqrt{2\pi } } e^{-\frac{(x-\mu)^2}{2\sigma^2} }

    python画图效果及代码(包含随机数生成):

    1. import numpy as np
    2. import matplotlib.pyplot as plt
    3. import matplotlib.mlab as mlab
    4. import matplotlib.cm as cm
    5. import math
    6. import scipy.stats as stats
    7. plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
    8. plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
    9. ################################ 正态分布 ###########################
    10. # 根据均值、标准差,求指定范围的正态分布概率值
    11. def normfun(x, mu, sigma):
    12. pdf = np.exp(-((x - mu)**2)/(2*sigma**2)) / (sigma * np.sqrt(2*np.pi))
    13. return pdf
    14. np.random.seed(0) ## 定义一个随机数种子
    15. result = np.random.normal(loc=10, scale=16, size=1000) # 均值为10,标准差为16
    16. ## !!!强调,以上参数中scale为标准差(方差的根号),不是方差,
    17. # 设定 x,y 轴,载入刚才的正态分布函数
    18. x = np.arange(min(result), max(result), 0.1)
    19. y = normfun(x, result.mean(), result.std())
    20. plt.plot(x, y) # 这里画出理论的正态分布概率曲线
    21. plt.hist(result, bins=20, rwidth=0.8, density=True) ## 柱状图
    22. plt.title('distribution')
    23. plt.xlabel('temperature')
    24. plt.ylabel('probability')
    25. plt.show()

    正态分布累积分布函数(CDF)

    1. ################################ 累积分布函数cdf ###########################
    2. #计算正态概率密度函数在x处的值
    3. def norm_dist_prob(theta):
    4. y = stats.norm.pdf(theta, loc=np.mean(data), scale=np.std(data))
    5. return y
    6. #计算正态分布累积概率值
    7. def norm_dist_cdf(theta):
    8. y = stats.norm.cdf(theta,loc=np.mean(data), scale=np.std(data))
    9. return y
    10. ## 数据生成
    11. data = np.random.normal(loc=0.0, scale=10, size=1000)
    12. x = np.linspace(stats.norm.ppf(0.01,loc=np.mean(data), scale=np.std(data)),
    13. stats.norm.ppf(0.99,loc=np.mean(data), scale=np.std(data)), len(data)) #linspace() 函数返回指定间隔内均匀间隔数字的 ndarray。
    14. y1=norm_dist_prob(x)
    15. y2=norm_dist_cdf(x)
    16. plt.plot(x, y1,'g', label='pdf')
    17. plt.plot(x, y2,'r', label='cdf1')
    18. #或
    19. sns.kdeplot(data,cumulative=True, label='cdf2')
    20. plt.legend()

    正态分布核密度估计(kde)

    1. ################################ 核密度估计 ###########################
    2. ## 数据生成
    3. data = np.random.normal(loc=0.0, scale=10, size=1000)
    4. ## 本程序是根据数据进行概率密度估计
    5. density = stats.gaussian_kde(data) #, bw_method=None, weights=[i[4] for i in data1]
    6. density.covariance_factor = lambda : .25 # lambda : .25
    7. density._compute_covariance()
    8. density.set_bandwidth(bw_method='silverman') ## 调用set_bandwidth 后计算的新带宽用于估计密度的后续评估。可选‘scott’, ‘silverman’
    9. xs = np.linspace(min(data), max(data), 200)
    10. fig, ax = plt.subplots()
    11. ax.plot(xs, density(xs), 'r')
    12. ax.fill_between(xs, density(xs), color="r", alpha=0.1)
    13. ax.hist(data, bins=30, rwidth=0.96, density =True, alpha=0.6,color = 'steelblue', edgecolor = 'w', label = 'dimensional histogram statistic ')
    14. ## 或者用seaborn
    15. fig, ax = plt.subplots()
    16. sns.distplot(data, hist=True, kde=True, rug=True, bins=20, ax=ax)
    17. # 通过hist和kde参数调节是否显示直方图及核密度估计(默认hist,kde均为True)
    18. # bins:int或list,控制直方图的划分
    19. # rug:控制是否生成观测数值的小细条
    20. # ax = sns.distplot(x, rug=True, rug_kws={"color": "g"},
    21. # ... kde_kws={"color": "k", "lw": 3, "label": "KDE"},
    22. # ... hist_kws={"histtype": "step", "linewidth": 3,
    23. # ... "alpha": 1, "color": "g"})fig, ax = plt.subplots()

    正态分布四则运算

     两个相互独立的正态分布分别满足

    X\sim N(\mu_1,\sigma_1^2), Y\sim N(\mu_2,\sigma_2^2)

    则:

    E(X+Y)=EX+EY=\mu_1+\mu_2

    D(X+Y)=DX+DY=\sigma_1^2+\sigma_2^2

    E(XY)=\frac{\sigma_1^2\mu_2+\sigma_2^2\mu_1}{\sigma_1^2+\sigma_2^2}

    D(XY)=\frac{\sigma_1^2\sigma_2^2}{\sigma_1^2+\sigma_2^2}

    二维正态分布(逐渐补充)

    (X,Y)\sim N(\mu_1,\mu_2,\sigma_1^2,\sigma_2^2,\rho )

    其生成及协方差椭圆的python实现如下:

    1. ################################ 二维正态分布 ###########################
    2. from matplotlib.patches import Ellipse
    3. def get_error_ellipse_parameters(cov, confidence=None, sigma=None):
    4. """Returns parameters of an ellipse which contains a specified
    5. amount of normally-distributed 2D data, where the data is
    6. characterised by its covariance matrix.
    7. Parameters
    8. ----------
    9. cov : array_like
    10. Input covariance matrix of shape (2,2)
    11. confidence : float
    12. Fraction of data points within ellipse. 0 < confidence < 1.
    13. If confidence is not given, it is calculated according to sigma.
    14. sigma : float
    15. Length of axes of the ellipse in standard deviations. If
    16. confidence is also given, sigma is ignored.
    17. Returns
    18. -------
    19. semi_major : float
    20. Length of major semiaxis of ellipse.
    21. semi_minor : float
    22. Length of minor semiaxis of ellipse.
    23. angle : float
    24. Rotation angle of ellipse in radian.
    25. confidence : float
    26. Fraction of data expected to lie within the ellipse.
    27. sigma : float
    28. Length of major and minor semiaxes in standard deviations.
    29. """
    30. cov = np.array(cov)
    31. if(cov.shape != (2,2)):
    32. raise ValueError("The covariance matrix needs to be of shape (2,2)")
    33. if(confidence == None and sigma == None):
    34. raise RuntimeError("One of confidence and sigma is needed as input argument")
    35. if(confidence and sigma):
    36. print("Argument sigma is ignored as confidence is also provided!")
    37. if(confidence == None):
    38. if(sigma < 0):
    39. raise ValueError("Sigma needs to be positive")
    40. #scaling = np.square(sigma)
    41. scaling = sigma
    42. confidence = stats.chi2.cdf(scaling, 2)
    43. if(sigma == None):
    44. if(confidence > 1 or confidence < 0):
    45. raise ValueError("Ensure that confidence lies between 0 and 1")
    46. scaling = stats.chi2.ppf(confidence, 2)
    47. #sigma = np.sqrt(scaling)
    48. sigma = scaling
    49. eigenvalues, eigenvectors = np.linalg.eig(cov)
    50. maxindex = np.argmax(eigenvalues)
    51. vx, vy = eigenvectors[:, maxindex]
    52. angle = np.arctan2(vy, vx)
    53. semi_minor, semi_major = np.sqrt(np.sort(eigenvalues) * scaling)
    54. print("With sigma = {:.3f}, {:.1f}% of data points lie within ellipse.".format(sigma, confidence * 100))
    55. return semi_major, semi_minor, angle, confidence, sigma
    56. mu = [1,2]
    57. cov = [[50,30],[30,50]] #sigma
    58. # 随机数生成
    59. z = stats.multivariate_normal(mu, cov)
    60. data_points = z.rvs(size = 5000)
    61. fig, ax = plt.subplots()
    62. plt.scatter(data_points[:,0], data_points[:,1], alpha = .5)
    63. # 画置信度椭圆
    64. confidence = 0.95
    65. semi_major, semi_minor, angle, confidence, sigma = get_error_ellipse_parameters(cov, confidence = confidence)
    66. ax.add_patch(Ellipse(mu, 2*semi_major, 2*semi_minor, 180*angle/np.pi, facecolor = 'none', edgecolor = 'red', label = 'Confidence = {:.0f}% (sigma = {:.2f})'.format(confidence * 100, sigma)))
    67. sigma = 1
    68. semi_major, semi_minor, angle, confidence, sigma, = get_error_ellipse_parameters(cov, sigma = sigma)
    69. ax.add_patch(Ellipse(mu, 2*semi_major, 2*semi_minor, 180*angle/np.pi, facecolor = 'none', edgecolor = 'yellow', label = 'Sigma = {:.0f} (confidence = {:.1f}%)'.format(sigma, confidence * 100)))
    70. plt.legend()
    71. plt.show()

    马氏距离

    计算马氏距离(Mahalanobis Distance)。一维马氏距离定义为:

    \sqrt{(u-v)V^{-1}(u-v)^{T}}

    1. iv = [[1, 0.5, 0.5], [0.5, 1, 0.5], [0.5, 0.5, 1]]
    2. md = distance.mahalanobis([1, 0, 0], [0, 1, 0], iv)
    3. print(md)
    4. # 或
    5. p = np.array([1,1])
    6. distr = np.array([2,2])
    7. cov = [[1,0.2],
    8. [0.2,1]]
    9. dis = distance.mahalanobis(p, distr, cov)
    10. # p: 一个点
    11. # distr : 一个分布
    12. # 计算分布的协方差矩阵
    13. #cov = np.cov(distr, rowvar=False)
    14. # 选取分布中各维度均值所在点
    15. #avg_distri = np.average(distr, axis=0)
    16. print(dis)

    2.卡方分布

    卡方分布,也写作:\chi ^2分布。服从自由度为n的卡方分布,记作\chi ^2\sim \chi ^2\left ( n \right ),其均值为 n,方差为2n。

    若n个相互独立的随机变量ξ₁,ξ₂,...,ξn ,均服从标准正态分布N(0,1),则这n个服从标准正态分布的随机变量的平方和构成一新的随机变量,其分布规律称为卡方分布(chi-square distribution)。

     直观说:如果 X1,X2,X3...X„是 n个具有标准正态分布的独立变量,那么其平方和V=X_1^2+X_2^2+...+X_n^2,满足具有n个自由度的\chi ^2分布。

    概率密度函数(pdf):

    f_n(x)=\left\{\begin{matrix} \frac{1}{2\Gamma (n/2)}{(\frac{x}{2} )}^{\frac{n}{2}-1 }e^{-\frac{x}{2} } &,x>0 \\ 0&,x\le 0 \end{matrix}\right.

    其中,\Gamma是Gamma函数,n为自由度,一般情况x\ge 0

    \Gamma (\alpha )=\int_{0}^{+\infty } x^{\alpha-1}e^{-x}dx

    1. ################################ 卡方分布 ###########################
    2. for PDF in range(1,8):
    3. plt.plot(np.linspace(0,15,100),stats.chi2.pdf(np.linspace(0,15,100),df=PDF),label='k='+str(PDF))
    4. plt.tick_params(axis="both",which="major",labelsize=18)
    5. plt.axhline(y=0,color="black",linewidth=1.3,alpha=.7)
    6. plt.legend()

     卡方分布表:

    卡方分布相关计算

    1. ## 卡方分布相关计算
    2. # 累积分布函数
    3. x = stats.chi2.cdf(5.991, df=2)
    4. # 百分比点函数(与cdf—百分位数相反)
    5. a = stats.chi2.ppf(0.95, df=2)
    6. print(x,a)

    生成卡方分布随机数

    1. #生成随机数
    2. r = stats.chi2.rvs(df=df, size=1000)

    3.学生t分布

    Student's t-distribution,简称为t分布。

    假设随机变量Z服从标准正态分布N(0,1),另一随机变量V服从m自由度的\chi ^2分布,进一步假设Z和 V 彼此独立,则下列的数量t服从自由度为m的学生t分布:

    概率密度函数(pdf):

    t=\frac{Z}{\sqrt{V/m} } \sim t(m)

    1. ################################ t分布 ###########################
    2. x = np.linspace( -3, 3, 100)
    3. plt.plot(x, stats.t.pdf(x,1), label='df=1')
    4. plt.plot(x, stats.t.pdf(x,2), label='df=20')
    5. plt.plot(x, stats.t.pdf(x,100), label = 'df=100')
    6. plt.plot( x[::5], stats.norm.pdf(x[::5]),'kx', label='normal')
    7. ## 累积分布函数cdf
    8. y = stats.t.cdf(x,df=100, loc=0, scale=1)
    9. plt.plot(x,y, label='cdf')
    10. plt.legend()

  • 相关阅读:
    Maven 的 spring-boot-maven-plugin 红色报错
    神经网络建模的适用范围,神经网络建模流程详解
    文本-图像生成(Text-to-Image Generation)的评价指标介绍——CLIPScore、TISE
    Android Studio Koala | 2024.1.1 发布,快来看看有什么更新吧
    如何进行各个终端的页面适配(react项目安装插件 postcss-px-to-viewport)
    基于Springboot的宠物医院管理系统-JAVA【数据库设计、论文、源码、开题报告】
    C++_第八周做题总结
    SpringBoot集成jjwt和使用
    【Linux】防火墙 iptables
    C语言之实现贪吃蛇小游戏篇(2)
  • 原文地址:https://blog.csdn.net/nature1949/article/details/127991604