如何在SymPy中创建一个其参数本身就是随机变量的随机变量? [英] How to create a random variable whose parameters are themselves random variables in SymPy?

查看:60
本文介绍了如何在SymPy中创建一个其参数本身就是随机变量的随机变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个随机变量 Y,它的分布是泊松分布,参数本身是一个随机变量 X,它是参数 10 的泊松.

I have a random variable Y whose distribution is Poisson with parameter that is itself a random variable X, which is Poisson with parameter 10.

如何使用 SymPy 自动计算 X 和 Y 之间的协方差?代码

How can I use SymPy to automatically calculate the covariance between X and Y? The code

from sympy.stats import *
x1 = Poisson("x1", 3)
x2 = Poisson("x2", x1)
print(covariance(x2,x1))

引发错误ValueError: Lambda 必须是正数关于这个问题的文档对我来说不清楚,并且使用 given 函数似乎没有用.

raises an error ValueError: Lambda must be positive The documentation is not clear to me on this matter, and playing around with the function given did not seem to work.

推荐答案

SymPy 中没有实现这种操作.但是您可以为分布的参数传递一个符号(下面的 z1).然后在第一步计算之后,用x1替换z1并取期望值.

This kind of manipulation is not implemented in SymPy. But you can pass a symbol (z1 below) for the parameter of a distribution. Then after the first step of computation, replace z1 by x1 and take expected value.

from sympy import Symbol
from sympy.stats import Poisson, E
z1 = Symbol("z1")
x1 = Poisson("x1", 3)
x2 = Poisson("x2", z1)
Ex2 = E(E(x2).subs(z1, x1))
Vx2 = E(E((x2-Ex2)**2).subs(z1, x1))
cov = E(E((z1-E(x1))*(x2-Ex2)).subs(z1, x1))
print("E(x2) = {}, var(x2) = {}, cov(x1, x2) = {}".format(Ex2, Vx2, cov))

输出:

E(x2) = 3, var(x2) = 6, cov(x1, x2) = 3

注意在方差和协方差公式中出现 Ex2 而不是 E(x2).在这里使用 E(x2) 会给出错误的结果,因为 E(x2) 是一个涉及 z1 的表达式.出于同样的原因,我没有使用 variancecovariance 函数(因为它们涉及变量 E(x2) 而不是正确的值 3),将所有内容明确表示为期望值.

Notice the appearance of Ex2 instead of E(x2) in the formulas for variance and covariance. Using E(x2) here would give incorrect results because E(x2) is an expression involving z1. For the same reason I'm not using variance or covariance functions (as they'd involve the variable E(x2) instead of the correct value 3), expressing everything explicitly as an expected value.

这篇关于如何在SymPy中创建一个其参数本身就是随机变量的随机变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆