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
for a in range(n):
for b in range(a, n):
if P[a, b] == np.inf:
P[a, b] = likelihood(data, a, b)
Q[a] += P[a, b] * g[a] * Q[a - 1]
, , 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)
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 .