LabVIEW

cancel
Showing results for 
Search instead for 
Did you mean: 

Multivariate kernel density estimation

Dear All,

 

Could anybody help me to find an example or a existent tool for two-dimensional kernel density estimation with an axis-aligned bivariate normal kernel?

I have created VI's for computing density and for plotting it but I need an 2d kernel estimation (in the 3rd dimension is represented the density).

references

https://en.wikipedia.org/wiki/Multivariate_kernel_density_estimation https://stat.ethz.ch/R-manual/R-devel/library/MASS/html/kde2d.html

 

Thank you,

 

0 Kudos
Message 1 of 2
(1,810 Views)

I did it with python but I'd love it if someone ported gaussian_kde to LabVIEW to remove the python dependency.

 

 

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

# Generate random scatter data
np.random.seed(42)
x_vals = np.random.normal(loc=0, scale=1, size=1000)  # 1000 points, normal distribution
y_vals = np.random.normal(loc=0, scale=1, size=1000)  # Same for y-values

# Function to compute KDE-based 2D density array
def compute_kde_density(x, y, nx=100, ny=100):
    data = np.vstack([x, y])  # Stack x and y as rows
    kde = gaussian_kde(data, bw_method='scott')  # Gaussian KDE with default bandwidth
    
    # Define grid
    xgrid = np.linspace(min(x), max(x), nx)
    ygrid = np.linspace(min(y), max(y), ny)
    Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)
    positions = np.vstack([Xgrid.ravel(), Ygrid.ravel()])
    
    # Evaluate KDE on grid
    Z = kde(positions).reshape(Xgrid.shape)
    return Z
    
if __name__ == "__main__":
    # Compute the KDE density
    Z = compute_kde_density(x_vals, y_vals)
    xgrid = np.linspace(min(x_vals), max(x_vals), 100)
    ygrid = np.linspace(min(y_vals), max(y_vals), 100)
    Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)

    # Plot the original scatter and density heatmap
    fig, ax = plt.subplots(1, 2, figsize=(12, 6))

    # Scatter plot
    ax[0].scatter(x_vals, y_vals, s=5, alpha=0.5)
    ax[0].set_title('Scatter Plot')
    ax[0].set_xlabel('X')
    ax[0].set_ylabel('Y')

    # Density heatmap
    density_plot = ax[1].pcolormesh(Xgrid, Ygrid, Z, shading='auto', cmap='viridis')
    fig.colorbar(density_plot, ax=ax[1], label='Density')
    ax[1].set_title('Density Heatmap')
    ax[1].set_xlabel('X')
    ax[1].set_ylabel('Y')

    plt.tight_layout()
    plt.show()

densityPlot2.png

 

0 Kudos
Message 2 of 2
(14 Views)