python - 如何使用python分离两条高斯曲线?
解决方案
基本上,您需要推断高斯混合的参数。我将为插图生成一个类似的数据集。
生成具有已知参数的混合物
from itertools import starmap
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import mlab
sns.set(color_codes=True)
# inline plots in jupyter notebook
%matplotlib inline
# generate synthetic data from a mixture of two Gaussians with equal weights
# the solution below readily generalises to more components
nsamples = 10000
means = [30, 120]
sds = [10, 50]
weights = [0.5, 0.5]
draws = np.random.multinomial(nsamples, weights)
samples = np.concatenate(
list(starmap(np.random.normal, zip(means, sds, draws)))
)
绘制分布
sns.distplot(samples)
推断参数
from sklearn.mixture import GaussianMixture
mixture = GaussianMixture(n_components=2).fit(samples.reshape(-1, 1))
means_hat = mixture.means_.flatten()
weights_hat = mixture.weights_.flatten()
sds_hat = np.sqrt(mixture.covariances_).flatten()
print(mixture.converged_)
print(means_hat)
print(sds_hat)
print(weights_hat)
我们得到:
True
[ 122.57524745 29.97741112]
[ 48.18013893 10.44561398]
[ 0.48559771 0.51440229]
您可以调整 GaussianMixture 的超参数以提高拟合度,但这看起来已经足够好了。现在我们可以绘制每个组件(我只绘制第一个):
mu1_h, sd1_h = means_hat[0], sds_hat[0]
x_axis = np.linspace(mu1_h-3*sd1_h, mu1_h+3*sd1_h, 1000)
plt.plot(x_axis, mlab.normpdf(x_axis, mu1_h, sd1_h))
附言
在旁注上。似乎您正在处理受约束的数据,并且您的观察结果非常接近左约束(零)。虽然高斯可能会很好地逼近您的数据,但您应该谨慎行事,因为高斯假设几何不受约束。
推荐阅读
- bash - Bash如何从参数解析关联数组?
- python - 如何过滤和限制 PyTube 下载的文件大小?
- javascript - 在shopify中用积分付款之前不要创建新订单?
- c# - Partials 是在 ASP.net MVC 中创建向导模板的好方法吗?
- php - PHP Symfony X.509 身份验证
- spring-boot - 登录 NullPointerException 时 Spring Security 无法访问 userService
- javascript - 如何制作一个动态 JSON.parse() 函数来解析本地存储中所有声明的项目
- prestashop - 如何在自定义模块的视图中列出产品?(PS 1.7)
- objective-c - Swift 和@objc 方法:如何转换一个方法以便它可以由@objc 表示?
- amazon-web-services - 当通过 SAM 使用 HttpApi 时,OpenApi 定义是唯一的事实吗?