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)為箭頭起始坐標,(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)文章
python數(shù)據(jù)結(jié)構(gòu)之搜索講解
這篇文章主要介紹了python數(shù)據(jù)結(jié)構(gòu)之搜索講解,搜索是指從元素集合中找到某個特定元素的算法過程。搜索過程通常返回?True?或?False,?分別表示元素是否存在,下面一起來了解文章的詳細內(nèi)容吧,希望對你有所幫助2021-12-12python爬蟲流程基礎(chǔ)示例零基礎(chǔ)學(xué)習(xí)
這篇文章主要為大家介紹了python爬蟲流程基礎(chǔ)示例零基礎(chǔ)學(xué)習(xí),我們將討論 Python 網(wǎng)絡(luò)編程中的爬蟲基礎(chǔ),作為一個完全的初學(xué)者,你將學(xué)習(xí)到爬蟲的基本概念、常用庫以及如何編寫一個簡單的爬蟲2023-06-06python matplotlib坐標軸設(shè)置的方法
本篇文章主要介紹了python matplotlib坐標軸設(shè)置的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12Python實現(xiàn)把xml或xsl轉(zhuǎn)換為html格式
這篇文章主要介紹了Python實現(xiàn)把xml或xsl轉(zhuǎn)換為html格式,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下2015-04-04