Skip to content

Instantly share code, notes, and snippets.

View ThomasParistech's full-sized avatar
🚴

Thomas Rouch ThomasParistech

🚴
View GitHub Profile
# Normalize the density by the disk/kernel convolution
density /= gaussian_blurred
import cv2
def ceil_odd(x: float) -> int:
"""Round float to nearest odd integer."""
return 1 + 2*math.ceil(0.5*(x-1.0))
# Perform KDE and retrieve the bandwidth
kde = gaussian_kde(disk_xy.T)
sigma = np.sqrt(kde.covariance[0, 0])
from sklearn.neighbors import KernelDensity
kde = KernelDensity(kernel='linear', bandwidth="silverman")
kde.fit(input_xy)
density = np.exp(kde.score_samples(pred_xy))
...
# Change radius
new_radius = np.sqrt(2.0 - r**2)
...
... # Generate disk_xy
# Compute radius
r = np.linalg.norm(disk_xy, axis=-1)
# Change radius
new_radius = 2 - r
reflected_disk_xy = np.multiply((new_radius/r)[:, None],
disk_xy)
@ThomasParistech
ThomasParistech / base_kde.py
Created July 6, 2024 13:43
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)
import numpy as np
from scipy.stats import norm
def weighted_kde(x_data: np.ndarray, x_prediction: np.ndarray) -> np.ndarray:
h = silverman_bandwidth(x_data) # Required to evaluate CDF
area_values = norm.cdf(1.0, x_prediction, h) - norm.cdf(0.0, x_prediction, h)
basic_densities = basic_kde(x_data, x_prediction, h)
return basic_densities / area_values
import numpy as np
def reflective_kde(x_data: np.ndarray, x_prediction: np.ndarray) -> np.ndarray:
h = silverman_bandwidth(x_data) # Compute before adding reflected data
x_data_augmented = np.stack((-x_data, x_data, 2-x_data))
reflective_densities = basic_kde(x_data_augmented, x_prediction, h)
# Discard left and right reflected samples and normalize density by 1/3
return 3 * reflective_densities
import numpy as np
from scipy.special import logit
def transformed_kde(x_data: np.ndarray, x_prediction: np.ndarray) -> np.ndarray:
x_data_logit = logit(x_data)
x_prediction_logit = logit(x_prediction)
densities_logit = basic_kde(x_data_logit, x_prediction_logit)
return densities_logit / (x_prediction * (1.0-x_prediction))
@ThomasParistech
ThomasParistech / basic_kde.py
Last active February 25, 2024 23:05
basic_kde
import numpy as np
from scipy.stats import norm
def silverman_bandwidth(x_data: np.ndarray) -> float:
return (4/(3*x_data.shape[0]))**0.2 * np.std(x_data)
def basic_kde(x_data: np.ndarray, x_prediction: np.ndarray) -> np.ndarray:
"""Perform Gaussian Kernel Density Estimation.