MCPcopy Create free account
hub / github.com/lazyprogrammer/machine_learning_examples / HMM

Class HMM

hmm_class/hmmc.py:23–237  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

21
22
23class HMM:
24 def __init__(self, M, K):
25 self.M = M # number of hidden states
26 self.K = K # number of Gaussians
27
28 def fit(self, X, max_iter=30, eps=1e0):
29 # train the HMM model using the Baum-Welch algorithm
30 # a specific instance of the expectation-maximization algorithm
31
32 N = len(X)
33 D = X[0].shape[1] # assume each x is organized (T, D)
34
35 self.pi = np.ones(self.M) / self.M # initial state distribution
36 self.A = random_normalized(self.M, self.M) # state transition matrix
37 self.R = np.ones((self.M, self.K)) / self.K # mixture proportions
38 print("initial A:", self.A)
39 print("initial R:", self.R)
40 self.mu = np.zeros((self.M, self.K, D))
41 for i in range(self.M):
42 for k in range(self.K):
43 random_idx = np.random.choice(N)
44 x = X[random_idx]
45 random_time_idx = np.random.choice(len(x))
46 self.mu[i,k] = x[random_time_idx]
47 self.sigma = np.zeros((self.M, self.K, D, D))
48 for j in range(self.M):
49 for k in range(self.K):
50 self.sigma[j,k] = np.eye(D)
51
52 costs = []
53 for it in range(max_iter):
54 if it % 1 == 0:
55 print("it:", it)
56 alphas = []
57 betas = []
58 gammas = []
59 Bs = []
60 # components = []
61 P = np.zeros(N)
62
63 for n in range(N):
64 x = X[n]
65 T = len(x)
66
67 # calculate B so we can lookup when updating alpha and beta
68 B = np.zeros((self.M, T))
69 component = np.zeros((self.M, self.K, T)) # we'll need these later
70 for j in range(self.M):
71 for t in range(T):
72 for k in range(self.K):
73 p = self.R[j,k] * mvn.pdf(x[t], self.mu[j,k], self.sigma[j,k])
74 component[j,k,t] = p
75 B[j,t] += p
76 Bs.append(B)
77
78 alpha = np.zeros((T, self.M))
79 alpha[0] = self.pi*B[:,0]
80 for t in range(1, T):

Callers 2

real_signalFunction · 0.70
fake_signalFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected