網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
Scipy自帶了多種常見(jiàn)的分布,如正態(tài)分布、均勻分布、二項(xiàng)分布、多項(xiàng)分布、伽馬分布等等,還可以自定義任意的概率分布。本文將介紹如何利用Scipy自定義任意的概率分布。
連續(xù)變量分布
考慮連續(xù)變量x滿(mǎn)足如下概率密度分布函數(shù):
其在實(shí)數(shù)域積分為1。我們可以通過(guò)scipy.stats中的rv_continuous類(lèi)去實(shí)現(xiàn)這個(gè)分布,代碼如下:
from scipy.stats import rv_continuous
import matplotlib.pyplot as plt
import numpy as np
class MyDistribution(rv_continuous):
def _pdf(self, x):#概率密度分布函數(shù)
return 2*sqrt(0.1)*exp(-0.1*x**2)*cos(x)**2/(sqrt(pi)*(exp(-10) + 1))
distribution = MyDistribution()
xlist=np.linspace(-8,8,300)
ylist=distribution.pdf(xlist)
samples=distribution.rvs(size=200);#取200次樣
fig,ax=plt.subplots(figsize=(8,6))
ax.plot(xlist,ylist,lw=3,color='red',label="$\mathrm{ideal}$");
ax.hist(samples,color='blue',density=True, bins=np.arange(-8,8,0.25), histtype='barstacked', rwidth=0.9,label=r"$\mathrm{samples}$")
ax.legend(fontsize=20);
ax.set_xlabel(r"$x$",size=25)
ax.set_ylabel(r"$\mathrm{PDF}$",size=20)
ax.set_xlim(-8,8);
ax.tick_params(axis='both',direction='in',width=1.3,length=3,top=1,right=1,labelsize=20,pad=2)
fig.tight_layout();
fig.show();
運(yùn)行結(jié)果如下:
增加采樣次數(shù),分布直方圖逐漸趨于理想的概率分布函數(shù)P(x)。
離散變量分布
考慮連續(xù)變量x滿(mǎn)足泊松分布,則可以用scipy.stats中的rv_discrete類(lèi)去實(shí)現(xiàn)這個(gè)分布,代碼如下:
from scipy.stats import rv_discrete
import matplotlib.pyplot as plt
import numpy as np
from scipy.special import factorial
class MyDistribution(rv_discrete):
def _pmf(self, k, mu):
return exp(-mu)*mu**k/factorial(k)
distribution = MyDistribution()
mu=2
samples=distribution.rvs(size=500,mu=mu);#取500次樣
klist = np.arange(0,10,1)
plist = distribution.pmf(klist,mu)
fig, ax = plt.subplots()
ax.plot(klist, plist, 'ro', ms=12, mec='r',label="$\mathrm{ideal}$");
ax.hist(samples,color='blue',density=True, bins=klist, histtype='barstacked', rwidth=0.8,label=r"$\mathrm{samples}$",align="left")
ax.legend(fontsize=20);
fig.show();
運(yùn)行結(jié)果如下:
可以修改上述MyDistribution類(lèi)中的pmf函數(shù),實(shí)現(xiàn)任意想要的離散分布。
二項(xiàng)分布Binomial Distribution
是n個(gè)獨(dú)立的成功/失敗試驗(yàn)中成功的次數(shù)的離散概率分布,其中每次試驗(yàn)的成功概率為p。這樣的單次成功/失敗試驗(yàn)又稱(chēng)為伯努利試驗(yàn)。實(shí)際上,當(dāng)n=1時(shí),二項(xiàng)分布就是伯努利分布。
'''1、定義隨機(jī)變量'''
# 比如5次擲硬幣實(shí)驗(yàn),正面朝上的次數(shù)
n2=5
x2=np.arange(1,n2+1,1)
x2
array([1, 2, 3, 4, 5])
'''2、求對(duì)應(yīng)的概率質(zhì)量函數(shù) (PMF)'''
p2=0.5
pList2=stats.binom.pmf(x2,n2,p2)
# 返回一個(gè)列表,列表中每個(gè)元素表示隨機(jī)變量中對(duì)應(yīng)值的概率
pList2
array([0.15625, 0.3125 , 0.3125 , 0.15625, 0.03125])
'''3、繪圖'''
fig=plt.figure()
# plot在此的作用為顯示兩個(gè)標(biāo)記點(diǎn)
plt.plot(x2,pList2,marker='o',linestyle='None')
'''
vlines用于繪制豎直線(vertical lines),
參數(shù)說(shuō)明:vline(x坐標(biāo)值, y坐標(biāo)最小值, y坐標(biāo)值最大值)
'''
plt.vlines(x2, 0, pList2)
plt.xlabel('隨機(jī)變量:拋硬幣5次')
plt.ylabel('概率')
plt.title('二項(xiàng)分布:n=%d,p2=%0.2f' % (n2,p2))
plt.show()
幾何分布Geometric Distribution
在n次伯努利試驗(yàn)中,試驗(yàn)k次才得到第一次成功的機(jī)率。詳細(xì)地說(shuō),是:前k-1次皆失敗,第k次成功的概率。幾何分布是帕斯卡分布當(dāng)r=1時(shí)的特例。
'''1、定義隨機(jī)變量'''
# 比如射箭1次中靶的概率為90%,射5次箭
k=5
x3=np.arange(1,k+1,1)
x3
array([1, 2, 3, 4, 5])
'''2、求對(duì)應(yīng)的概率質(zhì)量函數(shù) (PMF)'''
p3=0.7
pList3=stats.geom.pmf(x3,p3)
# 返回一個(gè)列表,表示在第i次射擊中,第一次射中的概率
pList3
array([0.7 , 0.21 , 0.063 , 0.0189 , 0.00567])
'''3、繪圖'''
fig=plt.figure()
# plot在此的作用為顯示兩個(gè)標(biāo)記點(diǎn)
plt.plot(x3,pList3,marker='o',linestyle='None')
'''
vlines用于繪制豎直線(vertical lines),
參數(shù)說(shuō)明:vline(x坐標(biāo)值, y坐標(biāo)最小值, y坐標(biāo)值最大值)
'''
plt.vlines(x3, 0, pList3)
plt.xlabel('隨機(jī)變量:射擊5次')
plt.ylabel('概率')
plt.title('幾何分布:n=%d,p=%0.2f' % (k,p3))
plt.show()
泊松分布Poisson Distribution
描述在某單位時(shí)間內(nèi),事件發(fā)生n次的概率
'''1、定義隨機(jī)變量'''
# 某機(jī)器每季度發(fā)生故障平均為1次,那么在一年中機(jī)器發(fā)生10次的概率為
mu=4 # 平均值
k=10 # 要求發(fā)生10次的概率
x4=np.arange(1,k+1,1)
x4
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
'''2、求對(duì)應(yīng)的概率質(zhì)量函數(shù) (PMF)'''
pList4=stats.poisson.pmf(x4,mu) # 一年的平均值為4
# 返回一個(gè)列表,表示1年中發(fā)生i次故障的概率
pList4
array([0.07326256, 0.14652511, 0.19536681, 0.19536681, 0.15629345,
0.10419563, 0.05954036, 0.02977018, 0.01323119, 0.00529248])
'''3、繪圖'''
fig=plt.figure()
# plot在此的作用為顯示兩個(gè)標(biāo)記點(diǎn)
plt.plot(x4,pList4,marker='o',linestyle='None')
'''
vlines用于繪制豎直線(vertical lines),
參數(shù)說(shuō)明:vline(x坐標(biāo)值, y坐標(biāo)最小值, y坐標(biāo)值最大值)
'''
plt.vlines(x4, 0, pList4)
plt.xlabel('隨機(jī)變量:發(fā)生k次故障')
plt.ylabel('概率')
plt.title('泊松分布:n=%d' % k)
plt.show()
原文鏈接:https://blog.csdn.net/nejssd/article/details/126254737
相關(guān)推薦
- 2022-07-27 Python中的pandas表格模塊、文件模塊和數(shù)據(jù)庫(kù)模塊_python
- 2022-10-15 Go?Excelize?API源碼閱讀GetPageLayout及SetPageMargins_Go
- 2022-03-29 jquery實(shí)現(xiàn)頁(yè)面彈球效果_jquery
- 2022-09-28 React報(bào)錯(cuò)解決之ref返回undefined或null_React
- 2023-02-18 Go?gin權(quán)限驗(yàn)證實(shí)現(xiàn)過(guò)程詳解_Golang
- 2022-01-18 npm ERR! code ENOENT npm ERR! syscall open npm ERR
- 2022-05-13 Django-Rest framwork框架 序列化與反序列化
- 2022-01-21 吃透Mybatis源碼-緩存的理解(三)
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支