Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
Marginal and Conditional Probability
A joint distribution P(X,Y) is a table: entry (i,j) is the probability of X=i and Y=j. The whole table sums to 1.
Two things you can extract from it:
Marginal — collapse one variable by summing it away.
That is a row sum, which is joint.sum(axis=1). The name comes from writing the totals in the margin of the table.
Conditional — restrict to one row and renormalise so it sums to 1 again.
joint = [[0.1, 0.2],
[0.3, 0.4]]
row sums (marginal over Y): [0.3, 0.7]
P(Y | X=0) = [0.1, 0.2] / 0.3 = [0.3333, 0.6667]Conditioning is where axis and keepdims stop being trivia: divide a (n, m) table by a (n,) vector and numpy broadcasts down the columns instead of across the rows, and you get numbers rather than an error.
Your task:
Implement conditional_given_row(joint, row) returning P(Y∣X=row) as a 1-D array that sums to 1.
Example Tests
Conditioning on the first row renormalises [0.1, 0.2] to sum to 1
Input: {"row":0,"joint":[[0.1,0.2],[0.3,0.4]]}
Expected: [0.33333,0.66667]
The second row is already twice as likely at its right-hand entry
Input: {"row":1,"joint":[[0.1,0.2],[0.3,0.4]]}
Expected: [0.42857,0.57143]
A row that is already uniform stays uniform
Input: {"row":0,"joint":[[0.25,0.25],[0.25,0.25]]}
Expected: [0.5,0.5]
import numpy as np
def conditional_given_row(joint, row):
"""
Conditional distribution of Y given a fixed value of X.
Args:
joint: 2-D array of joint probabilities, shape (n, m), summing to 1
row: which value of X to condition on
Returns:
array of shape (m,) summing to 1
"""
# YOUR CODE HERE
pass