Simple exemple sur comment calculer et tracer une estimation par noyau avec python et scipy
[image:kernel-estimation-1d]
from scipy.stats.kde import gaussian_kde
import matplotlib.pyplot as plt
import numpy as np
data = [-2.1,-1.3,-0.4,5.1,6.2]
kde = gaussian_kde(data)
x = np.linspace(-15, 20.0, 50)
y = [kde(i) for i in x]
plt.scatter(data,[0 for i in data])
plt.plot(x,y)
plt.title("Estimation par noyau avec pytho et scipy")
plt.grid()
plt.savefig("kernel_estimation_1d.png",bbox_inches='tight')
plt.show()
Exemple 2:
from scipy.stats.kde import gaussian_kde
from scipy.stats import norm
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 0, 0.1 # mean and standard deviation
s = np.random.normal(mu, sigma, 1000)
my_pdf = gaussian_kde(s)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
count, bins, ignored = plt.hist(s, 50, normed=True)
len_bins = len(bins)
resol = (bins[len_bins-1] - bins[0]) / 100.0
x = np.arange(bins[0],bins[len_bins-1],resol)
plt.text(0.2, 0.6,'Gaussian KDE',
horizontalalignment='center',
verticalalignment='center',
transform = ax.transAxes, fontsize=14,color='g')
plt.text(0.2, 0.7,'Normal Gaussian \n Distribution',
horizontalalignment='center',
verticalalignment='center',
transform = ax.transAxes, fontsize=14,color='r')
plt.plot(x,my_pdf(x), linewidth=2, color='g')
plt.plot(bins, norm.pdf(bins, mu,sigma), linewidth=2, color='r')
plt.savefig('KDE_Example.png',bbox_inches='tight')
plt.show()
Recherches associées
Liens | Site |
---|---|
Estimation par noyau | wikipedia |
scipy.stats.gaussian_kde | scipy doc |
Simple 1D Kernel Density Estimation | scikit-learn |
Kernel Density Estimation in Python | blog |