将双变量分布中的值标准化为 0-1 - python

Normalise values in bivariate distribution to 0-1 - python

我下面有一个双变量分布,它是根据 'Int_1','Int_2' 中每个 Group 的 xy 点生成的。目的是应用这些点和 return 组之间的多元分布。然后我想通过 Norm 规范化分布值,使 z 值介于 0 和 1 之间。现在通过着色器查看 z 值时,值在 0.24-0.72.[=16 之间变化=]

在上一个问题中,有人提到我实际上 return 不是多元分布。而是两组之间的概率比。

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) 

是否如你所愿:

Z = Z_GB - Z_GA
Norm = xx,yy, (Z - np.min(Z)) / (np.max(Z) - np.min(Z))
>>> np.min(Norm[2])
0.0

>>> np.max(Norm[2])
1.0