由于它不是一个与数学相关的问题,而是关于使用库进行符号计算,所以SO比{math | stats} .stackexchange.com
更适合回答这个问题。我想使用Sympy来计算以下内容:
这是我在Sympy中使用的代码
from sympy.stats import Normal, density, DiscreteUniform, P, given
from sympy import Symbol, pprint, symbols, Symbol, Eq
sigma = Symbol("sigma", positive=True)
mu = DiscreteUniform('mu', [1,2])
N = Normal('normal', mu, sigma)
sampling_dist = given(N, Eq(mu, 1))
prior = P(Eq(mu, 1))
marginal = P(Eq(mu, 1))*given(N, Eq(mu, 1))+P(Eq(mu, 2))*given(N, Eq(mu,2))
post = prior * sampling_dist / marginal
现在我想
我试图通过用
询问密度来打印方程式density(post)(Symbol('x'))
我收到以下错误
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-9b0e1c9ada72> in <module>()
----> 1 density(post)(Symbol('x'))
/Users/alexis/anaconda3/lib/python3.4/site-packages/sympy/stats/rv.py in density(expr, condition, evaluate, numsamples, **kwargs)
692 **kwargs)
693
--> 694 return Density(expr, condition).doit(evaluate=evaluate, **kwargs)
695
696
/Users/alexis/anaconda3/lib/python3.4/site-packages/sympy/stats/rv.py in doit(self, evaluate, **kwargs)
643 isinstance(pspace(expr), SinglePSpace)):
644 return expr.pspace.distribution
--> 645 result = pspace(expr).compute_density(expr, **kwargs)
646
647 if evaluate and hasattr(result, 'doit'):
/Users/alexis/anaconda3/lib/python3.4/site-packages/sympy/stats/rv.py in pspace(expr)
430 return rvs[0].pspace
431 # Otherwise make a product space
--> 432 return ProductPSpace(*[rv.pspace for rv in rvs])
433
434
/Users/alexis/anaconda3/lib/python3.4/site-packages/sympy/stats/rv.py in __new__(cls, *spaces)
278 # Overlapping symbols
279 if len(symbols) < sum(len(space.symbols) for space in spaces):
--> 280 raise ValueError("Overlapping Random Variables")
281
282 if all(space.is_Finite for space in spaces):
ValueError: Overlapping Random Variables
即使我使用常量sigma我也会得到同样的错误。我(很明显)不明白我做错了什么。