Skip to content

Instantly share code, notes, and snippets.

@ThomasParistech
Created July 6, 2024 13:43
Show Gist options
  • Save ThomasParistech/6060c13b08ca711d18498b32238a5df2 to your computer and use it in GitHub Desktop.
Save ThomasParistech/6060c13b08ca711d18498b32238a5df2 to your computer and use it in GitHub Desktop.
Boundary bias in Basic KDE on unit disk
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
# Generate a uniform grid of points in [-1, 1] x [-1, 1]
n_rows = 100
grid_xy = np.stack(np.meshgrid(np.linspace(-1, 1, n_rows),
np.linspace(-1, 1, n_rows),
indexing="xy"),
axis=-1).reshape(-1, 2)
# Select points within the unit disk
disk_mask = np.linalg.norm(grid_xy, axis=-1) <= 1
disk_xy = grid_xy[disk_mask]
# Estimate the density using a Gaussian KDE
kde = gaussian_kde(disk_xy.T)
density = kde(grid_xy.T)
# Set the density to zero outside the unit disk
density[~disk_mask] = 0.
# Normalize the density
density *= np.pi
# Plot the density
density = density.reshape((n_rows, n_rows))
plt.imshow(density, cmap="jet", vmin=0., vmax=1.2)
plt.colorbar()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment