画出Dirichlet分布的单纯形图

本文介绍如何使用Python的matplotlib库来绘制等边三角形网格上的Dirichlet概率密度函数轮廓图。首先定义了三角形网格及其重心坐标系转换方法,接着通过Dirichlet类实现概率密度函数的计算,并最终绘制出轮廓图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as tri

#生成等边三角形
corners = np.array([[0, 0], [1, 0], [0.5, 0.75**0.5]])
triangle = tri.Triangulation(corners[:, 0], corners[:, 1])

#每条边中点位置
midpoints = [(corners[(i + 1) % 3] + corners[(i + 2) % 3]) / 2.0 for i in range(3)]

def xy2bc(xy, tol=1.e-3):
    #将三角形顶点的笛卡尔坐标映射到重心坐标系
    s = [(corners[i] - midpoints[i]).dot(xy - midpoints[i]) / 0.75 for i in range(3)]
    return np.clip(s, tol, 1.0 - tol)

#有了重心坐标,可以计算Dirichlet概率密度函数的值
class Dirichlet(object):
    
    def __init__(self, alpha):
        from math import gamma
        from operator import mul
        from functools import reduce
        self._alpha = np.array(alpha)
        self._coef = gamma(np.sum(self._alpha)) / reduce(mul, [gamma(a) for a in self._alpha]) #reduce:sequence连续使用function
        
    def pdf(self, x):
        #返回概率密度函数值
        from operator import mul
        from functools import reduce
        return self._coef * reduce(mul, [xx ** (aa - 1) for (xx, aa)in zip(x, self._alpha)])
    
def draw_pdf_contours(dist, nlevels=200, subdiv=8, **kwargs):
    import math
    
    #细分等边三角形网格
    refiner = tri.UniformTriRefiner(triangle)
    trimesh = refiner.refine_triangulation(subdiv=subdiv)
    pvals = [dist.pdf(xy2bc(xy)) for xy in zip(trimesh.x, trimesh.y)]

    plt.tricontourf(trimesh, pvals, nlevels, **kwargs)
    plt.axis('equal')
    plt.xlim(0, 1)
    plt.ylim(0, 0.75**0.5)
    plt.axis('off')

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

### 绘制 Dirichlet 分布 为了绘制 Dirichlet 分布,可以使用 Python 中的 `matplotlib` 库来进行可视化。下面是一个具体的例子,展示如何生成并绘制三维的 Dirichlet 分布。 #### 导入必要库 ```python import numpy as np from scipy.stats import dirichlet import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D ``` #### 定义函数以创建网格点和计算概率密度 ```python def plot_dirichlet(alpha, ax): """Plot a 3D surface of the Dirichlet distribution.""" # Create grid points on simplex triangle x = [] y = [] z = [] for i in range(100): for j in range(100 - i): x.append(i / 100.) y.append(j / 100.) z.append((100 - i - j) / 100.) coords = np.array(list(zip(x, y, z))) mask = ~np.any(coords == 0, axis=1) filtered_coords = coords[mask] # Compute PDF values at these coordinates pdf_vals = dirichlet.pdf(filtered_coords, alpha) img = ax.scatter(filtered_coords[:, 0], filtered_coords[:, 1], filtered_coords[:, 2], c=np.log(pdf_vals), cmap='viridis', s=5) fig.colorbar(img) ax.view_init(elev=48, azim=-70) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') fig = plt.figure(figsize=(9, 6)) ax = fig.add_subplot(111, projection='3d') alphas = [1., 2., 6.] # Example parameters for Dirichlet distribution plot_dirichlet(alphas, ax) plt.title(f'Dirichlet Distribution with Alpha={alphas}') plt.show() ``` 这段代码定义了一个名为 `plot_dirichlet` 的辅助函数,它接受两个参数:一个是代表 Dirichlet 分布形状参数的列表 `alpha`;另一个是用于绘的目标轴对象 `ax`。此函数会在给定的坐标系上一个基于指定参数的 Dirichlet 分布图像[^1]。 通过调整输入向量 `alpha` 的值,可以看到不同的分布形态变化。上述示例选择了 `[1., 2., 6.]` 这组参数作为演示用途。最终的效果展示了三个维度上的概率密度情况,并采用了颜色映射来区分高低密度区域。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值