#180 · Probability · Medium
⊣ Solve on deep-ml.comCompute the Conditional Probability from a Joint Distribution. Given a joint probability table P(X, Y), compute the conditional distribution P(X | Y = y) or P(Y | X = x).
import numpy as np
def conditional_from_joint(joint: np.ndarray, given_axis: int,
given_index: int) -> np.ndarray:
if given_axis == 1:
joint_slice = joint[:, given_index]
else:
joint_slice = joint[given_index, :]
marginal = np.sum(joint_slice)
if marginal == 0:
return np.zeros_like(joint_slice)
return joint_slice / marginaljoint[i, j] = P(X=i, Y=j).