GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — machine_learning_examples/hmm_class/hmmd_theano2.py at master · evalcoding/machine_learning_examples

Expand file tree

/

hmmd_theano2.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
150 lines (119 loc) · 4.78 KB
/

hmmd_theano2.py

Copy path

File metadata and controls

150 lines (119 loc) · 4.78 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# https://deeplearningcourses.com/c/unsupervised-machine-learning-hidden-markov-models-in-python
# https://udemy.com/unsupervised-machine-learning-hidden-markov-models-in-python
# http://lazyprogrammer.me
# Discrete Hidden Markov Model (HMM) in Theano using gradient descent.
# This script differs from hmmd_theano.py in the following way:
# Instead of re-normalizing the parameters at each iteration,
# we instead make the parameters free to vary between -inf to +inf.
# We then use softmax to ensure the probabilities are positive and sum to 1.
from __future__ import print_function, division
from builtins import range
# Note: you may need to update your version of future
# sudo pip install -U future
import numpy as np
import theano
import theano.tensor as T
import matplotlib.pyplot as plt
class HMM:
def __init__(self, M):
self.M = M # number of hidden states
def fit(self, X, learning_rate=0.001, max_iter=10, V=None, print_period=1):
# train the HMM model using stochastic gradient descent
# print "X to train:", X
# determine V, the vocabulary size
# assume observables are already integers from 0..V-1
# X is a jagged array of observed sequences
if V is None:
V = max(max(x) for x in X) + 1
N = len(X)
print("number of train samples:", N)
preSoftmaxPi0 = np.zeros(self.M) # initial state distribution
preSoftmaxA0 = np.random.randn(self.M, self.M) # state transition matrix
preSoftmaxB0 = np.random.randn(self.M, V) # output distribution
thx, cost = self.set(preSoftmaxPi0, preSoftmaxA0, preSoftmaxB0)
pi_update = self.preSoftmaxPi - learning_rate*T.grad(cost, self.preSoftmaxPi)
A_update = self.preSoftmaxA - learning_rate*T.grad(cost, self.preSoftmaxA)
B_update = self.preSoftmaxB - learning_rate*T.grad(cost, self.preSoftmaxB)
updates = [
(self.preSoftmaxPi, pi_update),
(self.preSoftmaxA, A_update),
(self.preSoftmaxB, B_update),
]
train_op = theano.function(
inputs=[thx],
updates=updates,
allow_input_downcast=True,
)
costs = []
for it in range(max_iter):
if it % print_period == 0:
print("it:", it)
for n in range(N):
# this would of course be much faster if we didn't do this on
# every iteration of the loop
c = self.get_cost_multi(X).sum()
costs.append(c)
train_op(X[n])
# print "A:", self.A.get_value()
# print "B:", self.B.get_value()
# print "pi:", self.pi.get_value()
plt.plot(costs)
plt.show()
def get_cost(self, x):
# returns log P(x | model)
# using the forward part of the forward-backward algorithm
# print "getting cost for:", x
return self.cost_op(x)
def log_likelihood(self, x):
return -self.cost_op(x)
def get_cost_multi(self, X):
P = np.random.random(len(X))
return np.array([self.get_cost(x) for x, p in zip(X, P)])
def set(self, preSoftmaxPi, preSoftmaxA, preSoftmaxB):
self.preSoftmaxPi = theano.shared(preSoftmaxPi)
self.preSoftmaxA = theano.shared(preSoftmaxA)
self.preSoftmaxB = theano.shared(preSoftmaxB)
pi = T.nnet.softmax(self.preSoftmaxPi).flatten()
# softmax returns 1xD if input is a 1-D array of size D
A = T.nnet.softmax(self.preSoftmaxA)
B = T.nnet.softmax(self.preSoftmaxB)
# define cost
thx = T.ivector('thx')
def recurrence(t, old_a, x):
a = old_a.dot(A) * B[:, x[t]]
s = a.sum()
return (a / s), s
[alpha, scale], _ = theano.scan(
fn=recurrence,
sequences=T.arange(1, thx.shape[0]),
outputs_info=[pi*B[:,thx[0]], None],
n_steps=thx.shape[0]-1,
non_sequences=thx
)
cost = -T.log(scale).sum()
self.cost_op = theano.function(
inputs=[thx],
outputs=cost,
allow_input_downcast=True,
)
return thx, cost
def fit_coin():
X = []
for line in open('coin_data.txt'):
# 1 for H, 0 for T
x = [1 if e == 'H' else 0 for e in line.rstrip()]
X.append(x)
hmm = HMM(2)
hmm.fit(X)
L = hmm.get_cost_multi(X).sum()
print("LL with fitted params:", L)
# try true values
# remember these must be in their "pre-softmax" forms
pi = np.log( np.array([0.5, 0.5]) )
A = np.log( np.array([[0.1, 0.9], [0.8, 0.2]]) )
B = np.log( np.array([[0.6, 0.4], [0.3, 0.7]]) )
hmm.set(pi, A, B)
L = hmm.get_cost_multi(X).sum()
print("LL with true params:", L)
if __name__ == '__main__':
fit_coin()
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.