在Python中使用具有固定协方差的高斯混合

Ulf*_*lak 11 python machine-learning scikit-learn gmm

我有一些2D数据(GPS数据)与簇(停止位置),我知道它类似于具有特征标准偏差的高斯(与GPS样本的固有噪声成比例).下图显示了我期望有两个这样的聚类的样本.图像宽25米,高13米.

在此输入图像描述

sklearn模块具有sklearn.mixture.GaussianMixture允许您将高斯混合物拟合到数据的功能.该函数有一个参数,covariance_type使您可以假设有关高斯形状的不同内容.例如,您可以使用'tied'参数假设它们是统一的.

但是,似乎不能直接假设协方差矩阵保持不变.从sklearn源代码中进行修改似乎是微不足道的,但是使用允许这种更新的拉取请求感觉有点过分(我也不想意外地添加错误sklearn).是否有更好的方法将混合拟合到每个高斯的协方差矩阵固定的数据?

我想假设SD应该保持恒定在每个组件大约3米,因为这大致是我的GPS样本的噪音水平.

Dav*_*ale 7

编写您自己的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)
Run Code Online (Sandbox Code Playgroud)

在像你这样的数据上,模型会很快收敛:

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();
Run Code Online (Sandbox Code Playgroud)

和输出

11 iterations
[[9.92301067 4.62282807]
 [0.09413883 0.03527411]]
Run Code Online (Sandbox Code Playgroud)

您可以看到估计的中心 ((9.9, 4.6)(0.09, 0.03)) 接近真实中心 ((10, 5)(0, 0))。

在此处输入图片说明