Question: ****** This question is Python lab programming********* Your initial data comes in the form of counts. These are from the ANES data, and represent ideology
****** This question is Python lab programming*********
Your initial data comes in the form of counts. These are from the ANES data, and represent ideology (rows) and votechoice (columns).
data = np.atleast_2d( [
[106.0, 4.0],
[366.0, 7.0],
[216.0, 30.0],
[309.0, 205.0],
[85.0, 215.0],
[26.0, 475.0],
[8.0, 123.0]
] )
print(data.shape)
print(data)
1. Write a function that converts a 2D array of counts to a probability distribution.
def counts_to_probabilities( cnts ):
pass
probs = counts_to_probabilities( data )
# the probability of row 2 [0-based indexing], column 0 should be 0.0993
2. Write two functions: one that calculates the marginal distribution of the rows, and one that calculates the marginal distribution of the columns.
def marginalize_out_rows( probs ):
pass
def marginalize_out_cols( probs ):
pass
row_marg = marginalize_out_rows( probs )
print(row_marg.shape) # should be 2x1, or (2,)
print(row_marg[0]) # 0.513
col_marg = marginalize_out_cols( probs )
print(col_marg.shape) # should be 7x1, or (7,)
print(col_marg[0]) # 0.051
3. Write two functions: one that calculates the conditional distribution of columns, given a specific row; and one that calculates the conditional distribution of rows, given a specific column.
print( condition_on_row( probs, 3)[0] ) # should be 0.601
print( condition_on_col( probs, 0)[3] ) # should be 0.277
4. Write a function that calculates the expectation of a function f, given a probability distribution probs. You may assume that the values of x are integers ranging from 0 to the length of the distribution.
def f1(x):
return np.exp(x)/20 + 17
def f2(x):
return np.cos(5*x)*np.sin(x/3)
print( expectation( condition_on_row(probs,3), f1 ) ) # 8.5421
print( expectation( condition_on_col(probs,1), f2 ) ) # 0.5736
print( expectation( row_marginal(probs), f1 ))
print( expectation( col_marginal(probs), f2 ))
6. In a style similar to f1 and f2 above, write a small identity function.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
