What is the most pythonic way to conditionally compute?

I implement Bayesian point detection in Python / NumPy (if you're interested in looking at). I need to calculate the probabilities for the data in the ranges [a, b]where aand bcan have all values ​​from 1to n. However, I can shorten the calculation at some points, so I don’t need to calculate every probability. On the other hand, some probabilities are used more than once, so I can save time by storing the values ​​in the matrix P[a, b]. Now I am checking if the value is calculated when I use it, but I find it to be a bit of a hassle. It looks like this:

# ...
P = np.ones((n, n)) * np.inf  # a likelihood can't get inf, so I use it 
                            # as pseudo value

for a in range(n):
    for b in range(a, n):

        # The following two lines get annoying and error prone if you 
        # use P more than once

        if P[a, b] == np.inf:  
            P[a, b] = likelihood(data, a, b)

        Q[a] += P[a, b] * g[a] * Q[a - 1]  # some computation using P[a, b]
        # ...

, , if ... P[a, b]. - , - . , , likelihood , , - (, ). .

, . , . -... .

from scipy.special import gammaln
def gaussian_obs_log_likelihood(data, t, s):
    n = s - t
    mean = data[t:s].sum() / n

    muT = (n * mean) / (1 + n)
    nuT = 1 + n
    alphaT = 1 + n / 2
    betaT = 1 + 0.5 * ((data[t:s] - mean) ** 2).sum() + ((n)/(1 + n)) * (mean**2 / 2)
    scale = (betaT*(nuT + 1))/(alphaT * nuT)

    # splitting the PDF of the student distribution up is /much/ faster. (~ factor 20)
    prob = 1
    for yi in data[t:s]:
        prob += np.log(1 + (yi - muT)**2/(nuT * scale)) 

    lgA = gammaln((nuT + 1) / 2) - np.log(np.sqrt(np.pi * nuT * scale)) - gammaln(nuT/2)

    return n * lgA - (nuT + 1)/2 * prob

Python 2.7, 2.7 3.x .

+4
1

sibling defaultdict ( defaultdict , ):

class Cache(object):
    def __init__(self):
        self.cache = {}

    def get(self, a, b):
        key = (a,b)

        result = self.cache.get(key, None)
        if result is None:
            result = likelihood(data, a, b)
            self.cache[key] = result

        return result

likelihood .

+4

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


All Articles