Skip to content

Instantly share code, notes, and snippets.

@ThomasParistech
Last active February 25, 2024 23:05
Show Gist options
  • Save ThomasParistech/a381d9bb105416bbba343b048f8560ab to your computer and use it in GitHub Desktop.
Save ThomasParistech/a381d9bb105416bbba343b048f8560ab to your computer and use it in GitHub Desktop.
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.
Args:
x_data: Sample points drawn from the distribution to estimate.
Numpy array of shape (N,)
x_prediction: Points at which to evaluate the density estimate.
Numpy array of shape (N,)
Returns:
Densities evaluated at `x_prediction` by averaging gaussian kernels
around `x_data`. Numpy array of shape (N,)
"""
h = silverman_bandwidth(x_data)
pdf_values = norm.pdf(x_prediction.reshape(1, -1),
loc=x_data.reshape(-1, 1),
scale=h)
densities = np.mean(pdf_values, axis=0)
return densities
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment