科学学习:如何使用拟合概率模型?

2024-05-12 14:25:02 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我使用了scikitlearn的Gaussian mixture modelshttp://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

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

^{pr2}$

但这不是很奇怪吗?有更好的办法吗?我能画出这样的图吗? enter image description here


Tags: thesamplefrom模型importmatplotlibasnp
1条回答
网友
1楼 · 发布于 2024-05-12 14:25:02

我认为这个结果是合理的,如果你稍微调整一下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

相关问题 更多 >