简体   繁体   English

使用 python 的条件和联合问题

[英]conditional and joint prob using python

I have a table of joint prob P(x,y) and I want to creat a function the calculate the conditional probabilities given a the joint prob list.我有一个联合概率 P(x,y) 表,我想创建一个 function 来计算给定联合概率列表的条件概率。 For example I have the following list XY=np.array([[.1,0,0],[.1,.3,.2],[.1,0,.2]]) XY.shape= (3,3)例如,我有以下列表 XY=np.array([[.1,0,0],[.1,.3,.2],[.1,0,.2]]) XY.shape= ( 3,3)

I want to get the conditional probibility for each index so to find the conditional probabilty of x1cony1=XY[0,0]/y1=1 x2cony1=XY[0,1]/y1=.1我想获得每个索引的条件概率,以便找到 x1cony1=XY[0,0]/y1=1 x2cony1=XY[0,1]/y1=.1 的条件概率

Is there is a way to write a function for that to iterate through the matrix and provide me with a table of all the conditional prob?有没有办法编写一个 function 来遍历矩阵并为我提供所有条件概率的表?

Thanks谢谢

I don't understand your notation.我不明白你的符号。 I will try to answer your question with my notation and hopefully, you can extrapolate to yours.我将尝试用我的符号回答您的问题,并希望您可以推断出您的问题。 Let's say that the matrix XY contains the join probabilities, ie such that假设矩阵 XY 包含连接概率,即这样

P(x=x_i, y=y_j) = XY[i, j].

Well now, the conditional probability is现在好了,条件概率是

P(x=x_i | y=y_j) = P(x=x_i, y=y_j)/P(y=y_j) = XY[i,j]/(XY[0,j]+XY[1,j]+XY[2,j])

The denominator can be calculated easily using the NumPy sum over the first axis:可以使用 NumPy 和在第一轴上轻松计算分母:

XY.sum(axis=0)

Now you should divide the first column (which contains the probabilities P(x=x_i, y=y_0)) by the first value of the sum, which is the probability P(y=y_0).现在您应该将第一列(包含概率 P(x=x_i, y=y_0))除以总和的第一个值,即概率 P(y=y_0)。 And analogous for the other two columns.与其他两列类似。 This can also be done straightforward because in NumPy the product of a (3,3) matrix with a (3) vector is done by columns, which is just what we want.这也可以直接完成,因为在 NumPy 中,(3,3) 矩阵与 (3) 向量的乘积是按列完成的,这正是我们想要的。 Therefore this should give you the matrix of conditional probabilities:因此,这应该为您提供条件概率矩阵:

XY = np.array(...)  # XY[i,j] is the probability of x=x_i, y=y_j.
# The probability of x_i conditioned to y_j is given by the [i,j] element of:
cond_prob = XY/XY.sum(axis=0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM