Python之二維正態(tài)分布采樣置信橢圓繪制
更新時間:2023年02月01日 11:49:22 作者:猶有傲霜枝
這篇文章主要介紹了Python之二維正態(tài)分布采樣置信橢圓繪制方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
二維正態(tài)分布采樣后,繪制置信橢圓
假設(shè)二維正態(tài)分布表示為:

下圖為兩個二維高斯分布采樣后的置信橢圓

和

每個二維高斯分布采樣100個數(shù)據(jù)點,圖片為:

代碼如下
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def make_ellipses(mean, cov, ax, confidence=5.991, alpha=0.3, color="blue", eigv=False, arrow_color_list=None):
"""
多元正態(tài)分布
mean: 均值
cov: 協(xié)方差矩陣
ax: 畫布的Axes對象
confidence: 置信橢圓置信率 # 置信區(qū)間, 95%: 5.991 99%: 9.21 90%: 4.605
alpha: 橢圓透明度
eigv: 是否畫特征向量
arrow_color_list: 箭頭顏色列表
"""
lambda_, v = np.linalg.eig(cov) # 計算特征值lambda_和特征向量v
# print "lambda: ", lambda_
# print "v: ", v
# print "v[0, 0]: ", v[0, 0]
sqrt_lambda = np.sqrt(np.abs(lambda_)) # 存在負的特征值, 無法開方,取絕對值
s = confidence
width = 2 * np.sqrt(s) * sqrt_lambda[0] # 計算橢圓的兩倍長軸
height = 2 * np.sqrt(s) * sqrt_lambda[1] # 計算橢圓的兩倍短軸
angle = np.rad2deg(np.arccos(v[0, 0])) # 計算橢圓的旋轉(zhuǎn)角度
ell = mpl.patches.Ellipse(xy=mean, width=width, height=height, angle=angle, color=color) # 繪制橢圓
ax.add_artist(ell)
ell.set_alpha(alpha)
# 是否畫出特征向量
if eigv:
# print "type(v): ", type(v)
if arrow_color_list is None:
arrow_color_list = [color for i in range(v.shape[0])]
for i in range(v.shape[0]):
v_i = v[:, i]
scale_variable = np.sqrt(s) * sqrt_lambda[i]
# 繪制箭頭
"""
ax.arrow(x, y, dx, dy, # (x, y)為箭頭起始坐標(biāo),(dx, dy)為偏移量
width, # 箭頭尾部線段寬度
length_includes_head, # 長度是否包含箭頭
head_width, # 箭頭寬度
head_length, # 箭頭長度
color, # 箭頭顏色
)
"""
ax.arrow(mean[0], mean[1], scale_variable*v_i[0], scale_variable * v_i[1],
width=0.05,
length_includes_head=True,
head_width=0.2,
head_length=0.3,
color=arrow_color_list[i])
# ax.annotate("",
# xy=(mean[0] + lambda_[i] * v_i[0], mean[1] + lambda_[i] * v_i[1]),
# xytext=(mean[0], mean[1]),
# arrowprops=dict(arrowstyle="->", color=arrow_color_list[i]))
# v, w = np.linalg.eigh(cov)
# print "v: ", v
# # angle = np.rad2deg(np.arccos(w))
# u = w[0] / np.linalg.norm(w[0])
# angle = np.arctan2(u[1], u[0])
# angle = 180 * angle / np.pi
# s = 5.991 # 置信區(qū)間, 95%: 5.991 99%: 9.21 90%: 4.605
# v = 2.0 * np.sqrt(s) * np.sqrt(v)
# ell = mpl.patches.Ellipse(xy=mean, width=v[0], height=v[1], angle=180 + angle, color="red")
# ell.set_clip_box(ax.bbox)
# ell.set_alpha(0.5)
# ax.add_artist(ell)
def plot_2D_gaussian_sampling(mean, cov, ax, data_num=100, confidence=5.991, color="blue", alpha=0.3, eigv=False):
"""
mean: 均值
cov: 協(xié)方差矩陣
ax: Axes對象
confidence: 置信橢圓的置信率
data_num: 散點采樣數(shù)量
color: 顏色
alpha: 透明度
eigv: 是否畫特征向量的箭頭
"""
if isinstance(mean, list) and len(mean) > 2:
print "多元正態(tài)分布,多于2維"
mean = mean[:2]
cov_temp = []
for i in range(2):
cov_temp.append(cov[i][:2])
cov = cov_temp
elif isinstance(mean, np.ndarray) and mean.shape[0] > 2:
mean = mean[:2]
cov = cov[:2, :2]
data = np.random.multivariate_normal(mean, cov, 100)
x, y = data.T
plt.scatter(x, y, s=10, c=color)
make_ellipses(mean, cov, ax, confidence=confidence, color=color, alpha=alpha, eigv=eigv)
def main():
# plt.figure("Multivariable Gaussian Distribution")
plt.rcParams["figure.figsize"] = (8.0, 8.0)
fig, ax = plt.subplots()
ax.set_xlabel("x")
ax.set_ylabel("y")
print "ax:", ax
mean = [4, 0]
cov = [[1, 0.9],
[0.9, 0.5]]
plot_2D_gaussian_sampling(mean=mean, cov=cov, ax=ax, eigv=True, color="r")
mean1 = [5, 2]
cov1 = [[1, 0],
[0, 1]]
plot_2D_gaussian_sampling(mean=mean1, cov=cov1, ax=ax, eigv=True)
plt.savefig("./get_pickle_data/pic/gaussian_covariance_matrix.png")
plt.show()
if __name__ == "__main__":
main()
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解PyQt5 GUI 接收UDP數(shù)據(jù)并動態(tài)繪圖的過程(多線程間信號傳遞)
這篇文章主要介紹了PyQt5 GUI 接收UDP數(shù)據(jù)并動態(tài)繪圖(多線程間信號傳遞),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09
Python抓取通過Ajax加載數(shù)據(jù)的示例
在網(wǎng)頁上,有一些內(nèi)容是通過執(zhí)行Ajax請求動態(tài)加載數(shù)據(jù)渲染出來的,本文主要介紹了使用Python抓取通過Ajax加載數(shù)據(jù),感興趣的可以了解一下2023-05-05
Python面向?qū)ο缶幊讨庋b的藝術(shù)你了解嗎
這篇文章主要為大家詳細介紹了Python面向?qū)ο缶幊讨庋b的藝術(shù),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02
Python3.4 splinter(模擬填寫表單)使用方法
今天小編就為大家分享一篇Python3.4 splinter(模擬填寫表單)使用方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10
Python中將兩個或多個list合成一個list的方法小結(jié)
python中,list這種數(shù)據(jù)結(jié)構(gòu)很常用到,如果兩個或者多個list結(jié)構(gòu)相同,內(nèi)容類型相同,我們通常會將兩個或者多個list合并成一個,這樣我們再循環(huán)遍歷的時候就可以一次性處理掉了2019-05-05
解決python打開https出現(xiàn)certificate verify failed的問題
這篇文章主要介紹了解決python打開https出現(xiàn)certificate verify failed的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09

