python - scikit-learn:如何使用拟合概率模型?

标签 python scikit-learn

所以我使用了 scikit-learn 的 Gaussian mixture models( http://scikit-learn.org/stable/modules/mixture.html ) 来拟合我的数据,现在我想使用该模型,我该怎么做?具体来说:

  1. 如何绘制概率密度分布?
  2. 如何计算拟合模型的均方误差?

这是您可能需要的代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from sklearn import mixture
import matplotlib as mpl

from matplotlib.patches import Ellipse
%matplotlib inline

n_samples = 300

# generate random sample, two components
np.random.seed(0)
shifted_gaussian = np.random.randn(n_samples, 2) + np.array([20, 5])
sample= shifted_gaussian 

# fit a Gaussian Mixture Model with two components
clf = mixture.GMM(n_components=2, covariance_type='full')
clf.fit(sample)

# plot sample scatter
plt.scatter(sample[:, 0], sample[:, 1])

# 1. Plot the probobility density distribution
# 2. Calculate the mean square error of the fitting model

更新: 我可以通过以下方式绘制分布:

x = np.linspace(-20.0, 30.0)
y = np.linspace(-20.0, 40.0)
X, Y = np.meshgrid(x, y)
XX = np.array([X.ravel(), Y.ravel()]).T
Z = -clf.score_samples(XX)[0]
Z = Z.reshape(X.shape)

CS = plt.contour(X, Y, Z, norm=LogNorm(vmin=1.0, vmax=1000.0),
                 levels=np.logspace(0, 3, 10))
CB = plt.colorbar(CS, shrink=0.8, extend='both')

但这不是很奇怪吗?有更好的方法吗?我可以画这样的东西吗? enter image description here

最佳答案

我认为结果是合理的,如果你稍微调整一下xlim和ylim:

# plot sample scatter
plt.scatter(sample[:, 0], sample[:, 1], marker='+', alpha=0.5)

# 1. Plot the probobility density distribution
# 2. Calculate the mean square error of the fitting model
x = np.linspace(-20.0, 30.0, 100)
y = np.linspace(-20.0, 40.0, 100)
X, Y = np.meshgrid(x, y)
XX = np.array([X.ravel(), Y.ravel()]).T
Z = -clf.score_samples(XX)[0]
Z = Z.reshape(X.shape)

CS = plt.contour(X, Y, Z, norm=LogNorm(vmin=1.0, vmax=10.0),
                 levels=np.logspace(0, 1, 10))
CB = plt.colorbar(CS, shrink=0.8, extend='both')
plt.xlim((10,30))
plt.ylim((-5, 15))

enter image description here

关于python - scikit-learn:如何使用拟合概率模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32419367/

相关文章:

python - 从骨灰盒中绘制的 Numpy

python - 在 sklearn 的 TfidfVectorizer 中将单词添加到 stop_words 列表

scikit-learn - 如何在 scikit-learn 中缩放输入 DBSCAN

python - 将 C 中的包含文件转换为 python

python - 如果在列中,则无法减去日期时间和 NaT

python Pandas : select columns with all zero entries in dataframe

python - 使用内部支持的优化器优化 scikit-learn 中 GPR 的 RBF 内核的内核参数

python - 当我调用这个对象时,哪个方法直接返回类的元素?

python - Pandas groupby 和聚合输出应包括所有原始列(包括未聚合的列)

python - 如果先运行并行代码会挂起,但如果在运行非并行代码之后运行则可以正常工作