[英]Fit mixture of Gaussians with fixed covariance in Python
我有一些2D数据(GPS数据)与簇(停止位置),我知道它类似于具有特征标准偏差的高斯(与GPS样本的固有噪声成比例)。 下图显示了我期望有两个这样的聚类的样本。 图像宽25米,高13米。
sklearn
模块有一个函数sklearn.mixture.GaussianMixture
,它允许您将高斯混合物拟合到数据中。 该函数有一个参数covariance_type
,使您可以假设有关高斯形状的不同内容。 例如,您可以使用'tied'
参数假设它们是统一的。
但是,似乎不能直接假设协方差矩阵保持不变。 从sklearn
源代码中进行修改似乎是微不足道的,但是使用允许此更新的拉取请求感觉有点过分(我也不想在sklearn
意外添加错误)。 是否有更好的方法将混合拟合到每个高斯的协方差矩阵固定的数据?
我想假设SD应该保持恒定在每个组件大约3米,因为这大致是我的GPS样本的噪音水平。
编写自己的EM算法实现非常简单。 它也会让你对这个过程有一个很好的直觉。 我假设协方差是已知的,并且组件的先验概率是相等的,并且仅适合于均值。
该类看起来像这样(在Python 3中):
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
class FixedCovMixture:
""" The model to estimate gaussian mixture with fixed covariance matrix. """
def __init__(self, n_components, cov, max_iter=100, random_state=None, tol=1e-10):
self.n_components = n_components
self.cov = cov
self.random_state = random_state
self.max_iter = max_iter
self.tol=tol
def fit(self, X):
# initialize the process:
np.random.seed(self.random_state)
n_obs, n_features = X.shape
self.mean_ = X[np.random.choice(n_obs, size=self.n_components)]
# make EM loop until convergence
i = 0
for i in range(self.max_iter):
new_centers = self.updated_centers(X)
if np.sum(np.abs(new_centers-self.mean_)) < self.tol:
break
else:
self.mean_ = new_centers
self.n_iter_ = i
def updated_centers(self, X):
""" A single iteration """
# E-step: estimate probability of each cluster given cluster centers
cluster_posterior = self.predict_proba(X)
# M-step: update cluster centers as weighted average of observations
weights = (cluster_posterior.T / cluster_posterior.sum(axis=1)).T
new_centers = np.dot(weights, X)
return new_centers
def predict_proba(self, X):
likelihood = np.stack([multivariate_normal.pdf(X, mean=center, cov=self.cov)
for center in self.mean_])
cluster_posterior = (likelihood / likelihood.sum(axis=0))
return cluster_posterior
def predict(self, X):
return np.argmax(self.predict_proba(X), axis=0)
在像您这样的数据上,模型会快速收敛:
np.random.seed(1)
X = np.random.normal(size=(100,2), scale=3)
X[50:] += (10, 5)
model = FixedCovMixture(2, cov=[[3,0],[0,3]], random_state=1)
model.fit(X)
print(model.n_iter_, 'iterations')
print(model.mean_)
plt.scatter(X[:,0], X[:,1], s=10, c=model.predict(X))
plt.scatter(model.mean_[:,0], model.mean_[:,1], s=100, c='k')
plt.axis('equal')
plt.show();
和输出
11 iterations
[[9.92301067 4.62282807]
[0.09413883 0.03527411]]
您可以看到估计的中心( (9.9, 4.6)
和(0.09, 0.03)
)接近真实的中心( (10, 5)
和(0, 0)
)。
首先,您可以使用spherical
选项,它将为每个组件提供单个方差值。 通过这种方式,您可以检查自己,如果收到的差异值太大,那么就会出现问题。
如果您想预设差异,则问题会退化为仅为您的组件找到最佳中心。 例如,您可以使用k-means
来完成。 如果您不知道组件的数量,则可以扫描所有逻辑值(例如1到20)并评估拟合错误的减量。 或者,您可以优化自己的EM功能,同时查找中心和组件数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.