MATLAB ksdensity equivalent in Python

I looked online and have not yet found an answer or a way to understand the following

I translated MATLAB code into Python, where in MATLAB im, to find the kernel density estimate using the function:

[p,x] = ksdensity(data) 

where p is the probability at the point x in the distribution.

Scipy has a function, but returns p.

Is there any way to find probability with x values?

Thanks!

+5
source share
2 answers

This form of ksdensity call automatically generates an arbitrary x . scipy.stats.gaussian_kde() returns a callable function that can be evaluated using any x of your choice. The equivalent x will be np.linspace(data.min(), data.max(), 100) .

 import numpy as np from scipy import stats data = ... kde = stats.gaussian_kde(data) x = np.linspace(data.min(), data.max(), 100) p = kde(x) 
+5
source

Another option is to estimate kernel density in the Python Scikit-Learn package, sklearn.neighbors.KernelDensity

Here is a small example similar to the Matlab documentation for ksdensity for a Gaussian distribution:

 import numpy as np import matplotlib.pyplot as plt from sklearn.neighbors import KernelDensity np.random.seed(12345) # similar to MATLAB ksdensity example x = [randn(30,1); 5+randn(30,1)]; Vecvalues=np.concatenate((np.random.normal(0,1,30), np.random.normal(5,1,30)))[:,None] Vecpoints=np.linspace(-8,12,100)[:,None] kde = KernelDensity(kernel='gaussian', bandwidth=0.5).fit(Vecvalues) logkde = kde.score_samples(Vecpoints) plt.plot(Vecpoints,np.exp(logkde)) plt.show() 

The plot created is as follows:

enter image description here

+4
source

Source: https://habr.com/ru/post/1213571/


All Articles