本文介绍了在 sympy.stats 中绘制混合分布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(此问题的要点 此处)

我想创建两个 Gamma 分布的混合,并绘制在给定范围内评估的结果.

I'd like create a mixture of two Gamma distributions and plot the result, evaluated over a given range.

sympy.stats 似乎能够做到这一点,因为它能够计算混合物的期望值并从中提取样本.我对 sympy 很陌生,所以不确定在这种情况下是否有比我一直在使用的方法更喜欢的评估和绘图方法.

It would appear that sympy.stats is capable of this because it is able to compute the expectation of the mixture and sample from it. I'm quite new to sympy, so not sure if there is a preferred way for evaluating and plotting in this situation than the one I've been using.

%matplotlib inline
from matplotlib import pyplot as plt
from sympy.stats import Gamma, E, density
import numpy as np

G1 = Gamma("G1", 5, 2.5)
G2 = Gamma("G2", 4, 1.5)
f1 = 0.7; f2 = 1-f1
G3 = f1*G1 + f2*G2

期望为我提供了所有 3 个合理的数字

Expectation gives me single sensible number for all 3

In [19]: E(G1)
Out[19]: 12.5000000000000

In [20]: E(G2)
Out[20]: 6.00000000000000

In [21]: E(G3)
Out[21]: 10.5500000000000

...但在混合物上绘图失败

...but plotting fails on the mixture

u = np.linspace(0, 50)
D1 = density(G1); D2 = density(G2); D3 = density(G3)
v1 = [D1.args[1].subs(D1.args[0][0], i).evalf() for i in u]
v2 = [D2.args[1].subs(D2.args[0][0], i).evalf() for i in u]
v3 = [D3.args[1].subs(D3.args[0][0], i).evalf() for i in u]

plt.plot(u, v1)
plt.plot(u, v2)
plt.plot(u, v3)  # this one fails with error 'can't convert expression to float'

问题似乎是混合词仍然包含自由符号

The problem would appear to be that the mixture terms still contain free symbols

In [44]:  v1[0].free_symbols
Out[44]:  set()

In [45]:  v3[0].free_symbols
Out[45]:  {x}

...正如我所说,我认为 sympy.stats 似乎在计算期望时以某种方式处理了这个问题.所以我想我需要在这里应用这种机制来评估和绘制混合分布 (?)

...as I said, sympy.stats appears to be dealing with this ok somehow in computing the expectation, I assume. So I think I need to apply that machinery here in evaluating and plotting the mixture distribution (?)

推荐答案

看起来这个问题已经修复.我可以在 SymPy 0.7.3 中重现您的错误,但它在最新版本 0.7.4.1 中运行良好.

It looks like this was fixed. I can reproduce your error in SymPy 0.7.3 but it works just fine in 0.7.4.1, the latest version.

首先,您不需要对 .args 进行繁琐的操作.density 返回的表达式是可调用的.调用D1(i).evalf()就可以得到D1i处的数值,如

First off, you don't need the fanagling with the .args. The expressions returned by density are callable. Just call D1(i).evalf() to get the numerical value of D1 at i, like

D1 = density(G1); D2 = density(G2); D3 = density(G3)
v1 = [D1(i).evalf() for i in u]
v2 = [D2(i).evalf() for i in u]
v3 = [D3(i).evalf() for i in u]

我已将工作版本上传到 http://nbviewer.ipython.org/gist/asmeurer/8486176.

I've uploaded a working version to http://nbviewer.ipython.org/gist/asmeurer/8486176.

这篇关于在 sympy.stats 中绘制混合分布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:08