Install distribution on the counter in scipy

I have a collection.Counter object with the number of occurrences of different values, such as:

1:193260
2:51794
3:19112
4:9250
5:6486

How can I match the probability distribution with this data in scipy? scipy.stats.expon.fit () seems to want a list of numbers. It seems wasteful to create a list since 193260 [1] s, 51794 [2] s, etc. Is there a more elegant or efficient way?

+4
source share
1 answer

It looks like scipy.stats.expon.fit is basically a small wrapper over scipy.optimize.minimize, where it first creates a function to calculate neg-log-likelihood, and then uses scipy.optimize.minimize to match the PDF.

, , , , scipy.optimize.minimize.

, scipy "" http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.expon.html

, pdf:

pdf(x) = 1 / scale * exp ( - x / scale)

, , :

log_pdf(x) = - log(scale) - x / scale

, -- :

def neg_log_likelihood(scale):
    total = 0.0
    for x, count in counter.iteritems():
       total += (math.log(scale) + x / scale) * count
    return total

, .

import scipy.stats
import scipy.optimize
import math
import collections

def fit1(counter):
    def neg_log_likelihood(scale):
        total = 0.0
        for x, count in counter.iteritems():
           total += (math.log(scale) + x / scale) * count
        return total

    optimize_result = scipy.optimize.minimize(neg_log_likelihood, [1.0])
    if not optimize_result.success:
        raise Exception(optimize_result.message)
    return optimize_result.x[0]

def fit2(counter):
    data = []
    # Create an array where each key is repeated as many times
    # as the value of the counter.
    for x, count in counter.iteritems():
        data += [x] * count
    fit_result = scipy.stats.expon.fit(data, floc = 0)
    return fit_result[-1]    

def test(): 
    c = collections.Counter()
    c[1] = 193260
    c[2] = 51794
    c[3] = 19112
    c[4] = 9250
    c[5] = 6486

    print "fit1 'scale' is %f " % fit1(c)
    print "fit2 'scale' is %f " % fit2(c)

test()

:

fit1 'scale' is 1.513437 
fit2 'scale' is 1.513438 
+1

Source: https://habr.com/ru/post/1527625/


All Articles