Как я могу построить функцию плотности вероятности для установленной модели гауссовой смеси при изучении scikit?
Я борюсь с довольно простой задачей. У меня есть вектор поплавков, к которому я хотел бы подгонять модель смеси Гаусса с двумя гауссовыми ядрами:
from sklearn.mixture import GMM
gmm = GMM(n_components=2)
gmm.fit(values) # values is numpy vector of floats
Теперь я хотел бы построить функцию плотности вероятности для модели смеси, которую я создал, но я не могу найти никакой документации о том, как это сделать. Как лучше всего действовать?
Edit:
Здесь - это вектор данных, которые я подхожу. Ниже приведен более подробный пример того, как я делаю:
from sklearn.mixture import GMM
from matplotlib.pyplot import *
import numpy as np
try:
import cPickle as pickle
except:
import pickle
with open('/path/to/kde.pickle') as f: # open the data file provided above
kde = pickle.load(f)
gmm = GMM(n_components=2)
gmm.fit(kde)
x = np.linspace(np.min(kde), np.max(kde), len(kde))
# Plot the data to which the GMM is being fitted
figure()
plot(x, kde, color='blue')
![enter image description here]()
# My half-baked attempt at replicating the scipy example
fit = gmm.score_samples(x)[0]
plot(x, fit, color='red')
![]()
Построенная кривая не выглядит похожей на то, что я ожидаю. Он даже не кажется гауссовым, что немного странно, учитывая, что он был создан гауссовским процессом. Я сошел с ума?
Ответы
Ответ 1
Взгляните на один из примеров scikit-learn на Github
https://github.com/scikit-learn/scikit-learn/blob/master/examples/mixture/plot_gmm_pdf.py
Идея состоит в том, чтобы сгенерировать meshgrid
, получить их score
из gmm
и нарисовать его.
В этом примере показано
![enter image description here]()
Ответ 2
Я следовал некоторым примерам, упомянутым в этой и других темах, и сумел приблизиться к решению, но функция окончательной плотности вероятности не интегрируется ни с одной. Я думаю, что я опубликую вопрос об этом в другой теме.
import ntumpy as np
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture
np.random.seed(1)
mus = np.array([[0.2], [0.8]])
sigmas = np.array([[0.1], [0.1]]) ** 2
gmm = GaussianMixture(2)
gmm.means_ = mus
gmm.covars_ = sigmas
gmm.weights_ = np.array([0.5, 0.5])
#Fit the GMM with random data from the correspondent gaussians
gaus_samples_1 = np.random.normal(mus[0], sigmas[0], 10).reshape(10,1)
gaus_samples_2 = np.random.normal(mus[1], sigmas[1], 10).reshape(10,1)
fit_samples = np.concatenate((gaus_samples_1, gaus_samples_2))
gmm.fit(fit_samples)
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0, 1, 1000).reshape(1000,1)
logprob = gmm.score_samples(x)
pdf = np.exp(logprob)
#print np.max(pdf) -> 19.8409464401 !?
ax.plot(x, pdf, '-k')
plt.show()
![Here is the resulting plot]()
Ответ 3
Посмотрите на эту ссылку:
http://www.astroml.org/book_figures/chapter4/fig_GMM_1D.html
Они показывают, как построить 1D GMM тремя различными способами:
![1D GMM plots]()
Ответ 4
Я думаю, что это отличный ресурс - https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/