Learn practical skills, build real-world projects, and advance your career
2 years ago

Probability and Statistics

Bivariate Normal Distributions:

A continuous bivariate random variable $(X,Y)$ is said to have Bivariate Normal distribution with parameters $\mu_1,\mu_2,\sigma_1^2,\sigma_2^2$, and $\rho$

if it's $JPDF$ is given by, $f_{X,Y}(x,y)=\frac{1}{2\pi\sigma_1\sigma_2\sqrt{1-\rho^2}}e^{{-\frac{1}{2(1-\rho^2)}}\left[\left(\frac{x-\mu_1}{\sigma_1}\right)^2+\left(\frac{y-\mu_2}{\sigma_2}\right)^2-2\rho\left(\frac{x-\mu_1}{\sigma_1}\right)\left(\frac{y-\mu_2}{\sigma_2}\right)\right]}$

$x,y,\mu_1,\mu_2\in\mathbb{R}$, $\sigma_1,\sigma_2>0$,$-1<\rho<1$

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
from mpl_toolkits.mplot3d import Axes3D
import ipyvolume as ipv
from matplotlib import cm
from ipywidgets import interact ,interactive, fixed, interact_manual
import ipywidgets as widgets
%matplotlib inline

def BVN1(mu1,mu2,s1,s2,r): # Interactive 3D surface plot using ipyvolume

#Create grid and Bivariate normal

x = np.linspace(-10,10,100)
y = np.linspace(-10,10,100)
X, Y = np.meshgrid(x,y)
# Z=f(X,Y)
Z=(1/(2*np.pi*s1*s2*np.sqrt(1-r**2)))*(np.exp((-1/(2*(1-r**2)))*( ((X-mu1)/s1)**2 + ((Y-mu2)/s2)**2  -2*r* ((X-mu1)/s1)*((Y-mu2)/s2))))
colormap = cm.coolwarm
znorm = Z - Z.min()
znorm /= znorm.ptp()
znorm.min(), znorm.max()
color = colormap(znorm)
#Make a 3D plot
ipv.figure()
ipv.pylab.plot_surface(X,Y,Z,color=color[...,:3])
#ipv.plot_wireframe(X, Z, Y, color="red")
ipv.pylab.zlim(0,Z.max())
#ipv.pylab.style.box_off()
ipv.show()

def BVN2(mu1,mu2,s1,s2,r):  #  3D surface plot using matplotlib
#Create grid and multivariate normal
x = np.linspace(-10,10,500)
y = np.linspace(-10,10,500)
X, Y = np.meshgrid(x,y)
pos = np.empty(X.shape + (2,))
pos[:, :, 0] = X; pos[:, :, 1] = Y
brv = multivariate_normal([mu1, mu2], [[s1**2, r*s1*s2], [r*s1*s2, s2**2]])

#Make a 3D plot
fig= plt.figure(figsize=(10,10))
# ax = fig.add_subplot(1,1,1,projection='3d')
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, brv.pdf(pos),cmap='viridis',linewidth=0)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
ax.set_xlim(-10,10)
ax.set_ylim(-10,10)
plt.show()

mu_1=widgets.FloatSlider(min=-3, max=3, step=0.5, value=0,description=r'$\mu_1$ :')
mu_2=widgets.FloatSlider(min=-3, max=3, step=0.5, value=0,description=r'$\mu_2$ :')
s_1=widgets.FloatSlider(min=0, max=3, step=0.5, value=1,description=r'$\sigma_1$ :')
s_2=widgets.FloatSlider(min=0, max=3, step=0.5, value=1,description=r'$\sigma_2$ :')
r=widgets.FloatSlider(min=-1, max=1, step=0.1, value=0,description=r'$\rho$ :')