Monday, 28 June 2021

Normalise values in bivariate distribution to 0-1 - python

I have a bivariate distribution below that is generated from the xy points for each Group in 'Int_1','Int_2'. The aim to to apply these points and return a multivariate distribution between the Groups. I then want to normalise the distribution value via Norm so the z-value ranges between 0 and 1. When looking at the z-value now via the colorer, the values vary between 0.24-0.72.

In a previous question, it was mentioned that I'm not actually returning a multivariate distribution. Rather a ratio of probabilities between the two groups.

import pandas as pd
import numpy as np
from scipy.stats import multivariate_normal as mvn
import matplotlib.pyplot as plt
from scipy.interpolate import RectBivariateSpline


df = pd.DataFrame({'Int_1': [1.0, 2.0, 1.0, 3.0, 1.0, 2.0, 3.0, 2.0], 
           'Int_2': [1.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 2.0],
           'Item_X': [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0],
           'Item_Y': [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0],               
           'Period': [1, 1, 1, 1, 2, 2, 2, 2],
           'Group': ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'],
           'Item': ['Y', 'Y', 'A', 'B', 'A', 'B', 'A', 'B'],
           'id': ['1', '2', '3', '4', '1', '2', '3', '4']})

Group_A = [df[df['Group'] == 'A'][['Int_1','Int_2']].to_numpy()]
Group_B = [df[df['Group'] == 'B'][['Int_1','Int_2']].to_numpy()]
Item = [df[['Item_X','Item_Y']].to_numpy()]

period = df['Period'].drop_duplicates().reset_index(drop = True)

def bivart_func(member_no, location, time_index, group):

  if group == 'A':
    data = Group_A.copy()

  elif group == 'B':
    data = Group_B.copy()

  else:

    return

  if np.all(np.isfinite(data[member_no][[time_index,time_index + 1],:])) & np.all(np.isfinite(Item[0][time_index,:])):

    sxy = (data[member_no][time_index + 1,:] - data[member_no][time_index,:]) / (period[time_index + 1] - period[time_index])

    mu = data[member_no][time_index,:] + sxy * 0.5

    out = mvn.pdf(location,mu) / mvn.pdf(data[member_no][time_index,:],mu)

  else:
    out = np.zeros(location.shape[0])

  return out

xx,yy = np.meshgrid(np.linspace(-10,10,200),np.linspace(-10,10,200))
Z_GA = np.zeros(40000)
Z_GB = np.zeros(40000)

for k in range(1):
  Z_GA += bivart_func(k,np.c_[xx.flatten(),yy.flatten()],0,'A')
  Z_GB += bivart_func(k,np.c_[xx.flatten(),yy.flatten()],0,'B')

fig, ax = plt.subplots(figsize=(8,8))
ax.set_xlim(-10,10)
ax.set_ylim(-10,10)

Z_GA = Z_GA.reshape((200,200))
Z_GB = Z_GB.reshape((200,200))

Norm = xx,yy, 1 / (1 + np.exp(Z_GB - Z_GA))

cfs = ax.contourf(*Norm, cmap = 'magma')

ax.scatter(Item[0][1,0],Item[0][1,1], color = 'white', edgecolor = 'black')

fig.colorbar(cfs, ax = ax)

#f = RectBivariateSpline(xx[0, :], yy[:, 0], Norm)
#z = f(df['Item_X'], df['Item_Y'], grid = False) 


from Normalise values in bivariate distribution to 0-1 - python

No comments:

Post a Comment