目錄
基本概念
概率密度函數(shù)(PDF: Probability Density Function)
累積分布函數(shù)(CDF: Cumulative Distribution Function)
核密度估計((kernel density estimation)
1.正態(tài)分布
概率密度函數(shù)(pdf)
正態(tài)分布累積分布函數(shù)(CDF)
正態(tài)分布核密度估計(kde)
正態(tài)分布四則運算
二維正態(tài)分布(逐漸補充)
馬氏距離
2.卡方分布
概率密度函數(shù)(pdf):
?卡方分布表:
卡方分布相關(guān)計算
生成卡方分布隨機數(shù)
3.學生t分布
概率密度函數(shù)(pdf):
基本概念
概率密度函數(shù)(PDF: Probability Density Function)
連續(xù)隨機變量的概率分布特性。
累積分布函數(shù)(CDF: Cumulative Distribution Function)
在x點左側(cè)事件發(fā)生的總和。
CDF特性:
①因為累計分布函數(shù)是計算x點左側(cè)的點的數(shù)量,所以累計分布函數(shù)CDF是單調(diào)遞增的。
②所有的CDF中,在x趨近-∞時,CDF趨近于0,當x趨近+∞時,CDF趨近于1。
③對于給定的數(shù)據(jù)集,CDF是唯一的
核密度估計((kernel density estimation)
核密度估計(kernel density estimation,KDE)是在概率論中用來估計未知的密度函數(shù),屬于非參數(shù)檢驗方法之一,通過核密度估計圖可以比較直觀的看出數(shù)據(jù)樣本本身的分布特征。
scipy中的stats.gaussian_kde可以計算高斯核函數(shù)的密度函數(shù),而且提供了直接計算區(qū)間的累計密度函數(shù),integrate_box_1d(low=-np.Inf, high=x)。
1.正態(tài)分布
表示為:,其中期望為μ,方差為。
概率密度函數(shù)(pdf)
python畫圖效果及代碼(包含隨機數(shù)生成):
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cm as cm
import math
import scipy.stats as stats
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用來正常顯示中文標簽
plt.rcParams['axes.unicode_minus'] = False # 用來正常顯示負號
################################ 正態(tài)分布 ###########################
# 根據(jù)均值、標準差,求指定范圍的正態(tài)分布概率值
def normfun(x, mu, sigma):
pdf = np.exp(-((x - mu)**2)/(2*sigma**2)) / (sigma * np.sqrt(2*np.pi))
return pdf
np.random.seed(0) ## 定義一個隨機數(shù)種子
result = np.random.normal(loc=10, scale=16, size=1000) # 均值為10,標準差為16
## ?。?!強調(diào),以上參數(shù)中scale為標準差(方差的根號),不是方差,
# 設(shè)定 x,y 軸,載入剛才的正態(tài)分布函數(shù)
x = np.arange(min(result), max(result), 0.1)
y = normfun(x, result.mean(), result.std())
plt.plot(x, y) # 這里畫出理論的正態(tài)分布概率曲線
plt.hist(result, bins=20, rwidth=0.8, density=True) ## 柱狀圖
plt.title('distribution')
plt.xlabel('temperature')
plt.ylabel('probability')
plt.show()
正態(tài)分布累積分布函數(shù)(CDF)
################################ 累積分布函數(shù)cdf ###########################
#計算正態(tài)概率密度函數(shù)在x處的值
def norm_dist_prob(theta):
y = stats.norm.pdf(theta, loc=np.mean(data), scale=np.std(data))
return y
#計算正態(tài)分布累積概率值
def norm_dist_cdf(theta):
y = stats.norm.cdf(theta,loc=np.mean(data), scale=np.std(data))
return y
## 數(shù)據(jù)生成
data = np.random.normal(loc=0.0, scale=10, size=1000)
x = np.linspace(stats.norm.ppf(0.01,loc=np.mean(data), scale=np.std(data)),
stats.norm.ppf(0.99,loc=np.mean(data), scale=np.std(data)), len(data)) #linspace() 函數(shù)返回指定間隔內(nèi)均勻間隔數(shù)字的 ndarray。
y1=norm_dist_prob(x)
y2=norm_dist_cdf(x)
plt.plot(x, y1,'g', label='pdf')
plt.plot(x, y2,'r', label='cdf1')
#或
sns.kdeplot(data,cumulative=True, label='cdf2')
plt.legend()
正態(tài)分布核密度估計(kde)
################################ 核密度估計 ###########################
## 數(shù)據(jù)生成
data = np.random.normal(loc=0.0, scale=10, size=1000)
## 本程序是根據(jù)數(shù)據(jù)進行概率密度估計
density = stats.gaussian_kde(data) #, bw_method=None, weights=[i[4] for i in data1]
density.covariance_factor = lambda : .25 # lambda : .25
density._compute_covariance()
density.set_bandwidth(bw_method='silverman') ## 調(diào)用set_bandwidth 后計算的新帶寬用于估計密度的后續(xù)評估。可選‘scott’, ‘silverman’
xs = np.linspace(min(data), max(data), 200)
fig, ax = plt.subplots()
ax.plot(xs, density(xs), 'r')
ax.fill_between(xs, density(xs), color="r", alpha=0.1)
ax.hist(data, bins=30, rwidth=0.96, density =True, alpha=0.6,color = 'steelblue', edgecolor = 'w', label = 'dimensional histogram statistic ')
## 或者用seaborn
fig, ax = plt.subplots()
sns.distplot(data, hist=True, kde=True, rug=True, bins=20, ax=ax)
# 通過hist和kde參數(shù)調(diào)節(jié)是否顯示直方圖及核密度估計(默認hist,kde均為True)
# bins:int或list,控制直方圖的劃分
# rug:控制是否生成觀測數(shù)值的小細條
# ax = sns.distplot(x, rug=True, rug_kws={"color": "g"},
# ... kde_kws={"color": "k", "lw": 3, "label": "KDE"},
# ... hist_kws={"histtype": "step", "linewidth": 3,
# ... "alpha": 1, "color": "g"})fig, ax = plt.subplots()
正態(tài)分布四則運算
?兩個相互獨立的正態(tài)分布分別滿足
則:
二維正態(tài)分布(逐漸補充)
其生成及協(xié)方差橢圓的python實現(xiàn)如下:
################################ 二維正態(tài)分布 ###########################
from matplotlib.patches import Ellipse
def get_error_ellipse_parameters(cov, confidence=None, sigma=None):
"""Returns parameters of an ellipse which contains a specified
amount of normally-distributed 2D data, where the data is
characterised by its covariance matrix.
Parameters
----------
cov : array_like
Input covariance matrix of shape (2,2)
confidence : float
Fraction of data points within ellipse. 0 < confidence < 1.
If confidence is not given, it is calculated according to sigma.
sigma : float
Length of axes of the ellipse in standard deviations. If
confidence is also given, sigma is ignored.
Returns
-------
semi_major : float
Length of major semiaxis of ellipse.
semi_minor : float
Length of minor semiaxis of ellipse.
angle : float
Rotation angle of ellipse in radian.
confidence : float
Fraction of data expected to lie within the ellipse.
sigma : float
Length of major and minor semiaxes in standard deviations.
"""
cov = np.array(cov)
if(cov.shape != (2,2)):
raise ValueError("The covariance matrix needs to be of shape (2,2)")
if(confidence == None and sigma == None):
raise RuntimeError("One of confidence and sigma is needed as input argument")
if(confidence and sigma):
print("Argument sigma is ignored as confidence is also provided!")
if(confidence == None):
if(sigma < 0):
raise ValueError("Sigma needs to be positive")
#scaling = np.square(sigma)
scaling = sigma
confidence = stats.chi2.cdf(scaling, 2)
if(sigma == None):
if(confidence > 1 or confidence < 0):
raise ValueError("Ensure that confidence lies between 0 and 1")
scaling = stats.chi2.ppf(confidence, 2)
#sigma = np.sqrt(scaling)
sigma = scaling
eigenvalues, eigenvectors = np.linalg.eig(cov)
maxindex = np.argmax(eigenvalues)
vx, vy = eigenvectors[:, maxindex]
angle = np.arctan2(vy, vx)
semi_minor, semi_major = np.sqrt(np.sort(eigenvalues) * scaling)
print("With sigma = {:.3f}, {:.1f}% of data points lie within ellipse.".format(sigma, confidence * 100))
return semi_major, semi_minor, angle, confidence, sigma
mu = [1,2]
cov = [[50,30],[30,50]] #sigma
# 隨機數(shù)生成
z = stats.multivariate_normal(mu, cov)
data_points = z.rvs(size = 5000)
fig, ax = plt.subplots()
plt.scatter(data_points[:,0], data_points[:,1], alpha = .5)
# 畫置信度橢圓
confidence = 0.95
semi_major, semi_minor, angle, confidence, sigma = get_error_ellipse_parameters(cov, confidence = confidence)
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)))
sigma = 1
semi_major, semi_minor, angle, confidence, sigma, = get_error_ellipse_parameters(cov, sigma = sigma)
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)))
plt.legend()
plt.show()
馬氏距離
計算馬氏距離(Mahalanobis Distance)。一維馬氏距離定義為:
iv = [[1, 0.5, 0.5], [0.5, 1, 0.5], [0.5, 0.5, 1]]
md = distance.mahalanobis([1, 0, 0], [0, 1, 0], iv)
print(md)
# 或
p = np.array([1,1])
distr = np.array([2,2])
cov = [[1,0.2],
[0.2,1]]
dis = distance.mahalanobis(p, distr, cov)
# p: 一個點
# distr : 一個分布
# 計算分布的協(xié)方差矩陣
#cov = np.cov(distr, rowvar=False)
# 選取分布中各維度均值所在點
#avg_distri = np.average(distr, axis=0)
print(dis)
2.卡方分布
卡方分布,也寫作:分布。服從自由度為n的卡方分布,記作,其均值為 n,方差為2n。
若n個相互獨立的隨機變量ξ?,ξ?,...,ξn ,均服從標準正態(tài)分布N(0,1),則這n個服從標準正態(tài)分布的隨機變量的平方和構(gòu)成一新的隨機變量,其分布規(guī)律稱為卡方分布(chi-square distribution)。
?直觀說:如果 X1,X2,X3...X?是 n個具有標準正態(tài)分布的獨立變量,那么其平方和,滿足具有n個自由度的分布。
概率密度函數(shù)(pdf):
其中,是Gamma函數(shù),n為自由度,一般情況:
################################ 卡方分布 ###########################
for PDF in range(1,8):
plt.plot(np.linspace(0,15,100),stats.chi2.pdf(np.linspace(0,15,100),df=PDF),label='k='+str(PDF))
plt.tick_params(axis="both",which="major",labelsize=18)
plt.axhline(y=0,color="black",linewidth=1.3,alpha=.7)
plt.legend()
?卡方分布表:
卡方分布相關(guān)計算
## 卡方分布相關(guān)計算
# 累積分布函數(shù)
x = stats.chi2.cdf(5.991, df=2)
# 百分比點函數(shù)(與cdf—百分位數(shù)相反)
a = stats.chi2.ppf(0.95, df=2)
print(x,a)
生成卡方分布隨機數(shù)
#生成隨機數(shù)
r = stats.chi2.rvs(df=df, size=1000)
3.學生t分布
Student's t-distribution,簡稱為t分布。
假設(shè)隨機變量Z服從標準正態(tài)分布N(0,1),另一隨機變量V服從m自由度的分布,進一步假設(shè)Z和 V 彼此獨立,則下列的數(shù)量t服從自由度為m的學生t分布:文章來源:http://www.zghlxwxcb.cn/news/detail-780477.html
概率密度函數(shù)(pdf):
文章來源地址http://www.zghlxwxcb.cn/news/detail-780477.html
################################ t分布 ###########################
x = np.linspace( -3, 3, 100)
plt.plot(x, stats.t.pdf(x,1), label='df=1')
plt.plot(x, stats.t.pdf(x,2), label='df=20')
plt.plot(x, stats.t.pdf(x,100), label = 'df=100')
plt.plot( x[::5], stats.norm.pdf(x[::5]),'kx', label='normal')
## 累積分布函數(shù)cdf
y = stats.t.cdf(x,df=100, loc=0, scale=1)
plt.plot(x,y, label='cdf')
plt.legend()
到了這里,關(guān)于正態(tài)分布,二維正態(tài)分布,卡方分布,學生t分布——概率分布學習 python的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!