Code
import numpy as np
def joint_prob(val_x,val_y,X,Y):
= len(X)
n =0
countfor i in range(n):
if (X[i]==val_x and Y[i]==val_y):
+=1
countreturn count/n
def mutual_info(X,Y):
= len(X)
n = list(set(X))
unique_x = list(set(Y))
unique_y = [X.count(x)/n for x in unique_x]
prob_x = [Y.count(y)/n for y in unique_y]
prob_y =0
MIfor i in range(len(unique_x)):
for j in range(len(unique_y)):
= prob_x[i]
px = prob_y[j]
py = joint_prob(unique_x[i],unique_y[j],X,Y)
jointp if jointp==0:
continue
else:
+= jointp * np.log(jointp/(px*py))
MI
return MI
= ["A","B","C","A","B","C"]
X = ["A","B","C","A","B","C"]
Y = ["A","A","A","A","A","A"]
Z = ["A","A","C","A","A","C"]
W print(f"Mutual information of X and Y is {mutual_info(X,Y)}")
print(f"Mutual information of X and W is {mutual_info(X,W)}")
print(f"Mutual information of X and Z is {mutual_info(X,Z)}")
Mutual information of X and Y is 1.0986122886681096
Mutual information of X and W is 0.6365141682948128
Mutual information of X and Z is 0.0