机器学习-用python绘制常见的统计分布

来源:互联网 发布:js旋转木马轮播图 编辑:程序博客网 时间:2024/06/08 20:06

1.二项分布

服从二项分布的随机变量X表示在n个独立的是/非试验中成功的次数,其中每次试验的成功概率为p。

E(X) = np, Var(X) = np(1−p)

#coding:utf-8import numpy as npfrom matplotlib import pyplot#绘制二项分布def DrawBinomial(n,p):k = np.arange(0,11)binomial = stats.binom.pmf(k,n,p)#绘制图像pyplot.plot(k,binomial,'o-')pyplot.title('Binomial: n = %i,p = %.2f' % (n,p))pyplot.xlabel('Number of successes')pyplot.ylabel('Probability of successes')pyplot.show()DrawBinomial(10,0.30)



2.正态分布


一维正态分布定义:

可视化:
#coding:utf-8import numpy as npfrom matplotlib import pyplotfrom scipy import stats#绘制一维正态分布def DrawNormalDistribution(mu,sigma):x1 = np.arange(-5,5,0.1)y1 = stats.norm.pdf(x1,mu,sigma)x2 = np.arange(-5,5,0.1)y2 = stats.norm.pdf(x2,mu+1,sigma)x3 = np.arange(-5,5,0.1)y3 = stats.norm.pdf(x2,mu,sigma+1)#绘制图像pyplot.plot(x1,y1,linewidth = 2,color = 'r')pyplot.plot(x2,y2,linewidth = 2,color = 'b')pyplot.plot(x3,y3,linewidth = 2,color = 'g')pyplot.xlabel('x')pyplot.ylabel('Probability density')pyplot.show()DrawNormalDistribution(0.0,1.0)#DrawNormalDistribution(1.0,1.0)#DrawNormalDistribution(1.0,0.5)

程序截图:




二维正态分布定义:

我们假设二维随机变量(X,Y)中,X和Y相互独立(即参数p = 0)
则f(x,y) = 
可视化:
#coding:utf-8import numpy as npfrom matplotlib import pyplotfrom mpl_toolkits.mplot3d import Axes3D#绘制二维正态分布len = 10
step = 0.1def DrawNormalDistribution2D(mu1,mu2,sigma1,sigma2,p):x1 = np.arange(-len,len,step)x2 = np.arange(-len,len,step)x1,x2= np.meshgrid(x1, x2)part1 = 2*np.pi*sigma1*sigma2*np.sqrt(1-p**2)part2 = -1.0/(2*(1-p**2));part3 = (x1-mu1)**2/(sigma1**2);part4 = (x2-mu2)**2/(sigma2**2);part5 = 2*p*(x1-mu1)*(x2-mu2)/(sigma1*sigma2)z = np.exp(part2*(part3-part5+part4))/part1fig = pyplot.figure()ax = Axes3D(fig)ax.plot_surface(x1, x2, z, rstride=1, cstride=1, cmap='rainbow')pyplot.show()DrawNormalDistribution2D(0.0,0.0,1.0,1.0,0.0)



3.逻辑斯谛分布



#coding:utf-8import numpy as npfrom matplotlib import pyplotfrom scipy import stats
#逻辑斯蒂分布def DrawLogisticDestribution(mu,gama):x = np.arange(-len,len,step)y1 = stats.logistic.pdf(x,mu,gama)y2 = 1.0/(1+np.exp(-(x-mu)/gama))#绘制图像pyplot.plot(x,y1,'b-',x,y2,'r-')pyplot.title('logistic: mu = %.1f,gama = %.2f' % (mu,gama))pyplot.xlabel('x')pyplot.ylabel('y')pyplot.show()DrawLogisticDestribution(0.0,1.0)





阅读全文
0 0
原创粉丝点击