AttributeError: экземпляр GaussianMixture не имеет атрибута «логоподобный» - PullRequest
0 голосов
/ 26 апреля 2018

Я пытаюсь реализовать модель гауссовой смеси с алгоритмом ожидания-максимизации, и я получаю эту ошибку.Это модель гауссовой смеси, которую я использовал:

class GaussianMixture:
    "Model mixture of two univariate Gaussians and their EM estimation"

    def __init__(self, data, mu_min=min(data), mu_max=max(data), sigma_min=.1, sigma_max=1, mix=.5):
        self.data = data
        #init with multiple gaussians
        self.one = Gaussian(uniform(mu_min, mu_max), 
                            uniform(sigma_min, sigma_max))
        self.two = Gaussian(uniform(mu_min, mu_max), 
                            uniform(sigma_min, sigma_max))

        #as well as how much to mix them
        self.mix = mix

    def Estep(self):
        "Perform an E(stimation)-step, freshening up self.loglike in the process"
        # compute weights
        self.loglike = 0. # = log(p = 1)
        for datum in self.data:
            # unnormalized weights
            wp1 = self.one.pdf(datum) * self.mix
            wp2 = self.two.pdf(datum) * (1. - self.mix)
            # compute denominator
            den = wp1 + wp2
            # normalize
            wp1 /= den
            wp2 /= den
            # add into loglike
            self.loglike += log(wp1 + wp2)
            # yield weight tuple
            yield (wp1, wp2)

    def Mstep(self, weights):
        "Perform an M(aximization)-step"
        # compute denominators
        (left, rigt) = zip(*weights)
        one_den = sum(left)
        two_den = sum(rigt)
        # compute new means
        self.one.mu = sum(w * d / one_den for (w, d) in zip(left, data))
        self.two.mu = sum(w * d / two_den for (w, d) in zip(rigt, data))
        # compute new sigmas
        self.one.sigma = sqrt(sum(w * ((d - self.one.mu) ** 2)
                                  for (w, d) in zip(left, data)) / one_den)
        self.two.sigma = sqrt(sum(w * ((d - self.two.mu) ** 2)
                                  for (w, d) in zip(rigt, data)) / two_den)
        # compute new mix
        self.mix = one_den / len(data)

    def iterate(self, N=1, verbose=False):
        "Perform N iterations, then compute log-likelihood"

    def pdf(self, x):
        return (self.mix)*self.one.pdf(x) + (1-self.mix)*self.two.pdf(x)

    def __repr__(self):
        return 'GaussianMixture({0}, {1}, mix={2.03})'.format(self.one, 
                                                              self.two, 
                                                              self.mix)

    def __str__(self):
        return 'Mixture: {0}, {1}, mix={2:.03})'.format(self.one, 
                                                        self.two, 
                                                        self.mix)

И затем, во время обучения, я получаю эту ошибку в условном выражении.

# Check out the fitting process
n_iterations = 5
best_mix = None
best_loglike = float('-inf')
mix = GaussianMixture(data)
for _ in range(n_iterations):
    try:
        #train!
        mix.iterate(verbose=True)
        if mix.loglike > best_loglike:
            best_loglike = mix.loglike
            best_mix = mix

    except (ZeroDivisionError, ValueError, RuntimeWarning): # Catch division errors from bad starts, and just throw them out...
        pass

Есть идеи, почему у меня появляется следующая ошибка?

AttributeError: Экземпляр GaussianMixture не имеет атрибута 'loglike'

1 Ответ

0 голосов
/ 26 апреля 2018

Атрибут loglike создается только при вызове метода Estep.

def Estep(self):
    "Perform an E(stimation)-step, freshening up self.loglike in the process"
    # compute weights
    self.loglike = 0. # = log(p = 1)

Вы не вызывали Estep между созданием экземпляра GaussianMixture и mix.loglike:

mix = GaussianMixture(data)
for _ in range(n_iterations):
    try:
        #train!
        mix.iterate(verbose=True)
        if mix.loglike > best_loglike:

И метод iterate пуст (похоже, вы забыли здесь какой-то код).

def iterate(self, N=1, verbose=False):
    "Perform N iterations, then compute log-likelihood"

Таким образом, к моменту выполнения if mix.loglike атрибут loglike не будет установлен для экземпляра mix. Следовательно, AttributeError.

Вам необходимо выполнить одно из следующих действий:

  1. Вызовите метод Estep (поскольку вы установили self.loglike там)
  2. Определить атрибут loglike в __init__
...