Search This Blog

Monday, March 9, 2009

Viterbi algorithm for second order Hidden Markov model

This post is a supplement to the Viterbi article on Wikipedia I'm posting this because I couldn't find an understandable implementation of Viterbi for second order HMM anywhere (I badly needed it for my assignment). So, Anup, Saurabh and I put our heads together and modified the Wiki article's Viterbi code to work for 2nd order HMM.

The story goes thus(from Wiki) - Two friends, Alice and Bob, who live far apart from each other and who talk together daily over the telephone about what they did that day. Bob is only interested in three activities: walking in the park, shopping, and cleaning his apartment. The choice of what to do is determined exclusively by the weather on a given day. Alice has no definite information about the weather where Bob lives, but she knows general trends. Based on what Bob tells her he did each day, Alice tries to guess what the weather must have been like.

Alice believes that the weather operates as a discrete Markov chain. There are two states, "Rainy" and "Sunny", but she cannot observe them directly, that is, they are hidden from her. On each day, there is a certain chance that Bob will perform one of the following activities, depending on the weather: "walk", "shop", or "clean". Since Bob tells Alice about his activities, those are the observations. The entire system is that of a hidden Markov model (HMM).

Alice knows the general weather trends in the area, and what Bob likes to do on average. start_probability reflects Alice's belief that it is rainy on a given day, there is a probability of 0.7 that it'll rain the next day as well.

Below is the python code (with some helpful print statements added). Feel free to copy :)


states = ('Rainy', 'Sunny')

observations = ('walk', 'shop', 'clean')

start_probability = {
'Rainy|Rainy' : 0.7,
'Rainy|Sunny' : 0.3,
'Sunny|Rainy' : 0.4,
'Sunny|Sunny' : 0.6
}

transition_probability = {
'Rainy|Rainy' : {'Rainy' : 0.8, 'Sunny' : 0.2},
'Rainy|Sunny' : {'Rainy' : 0.5, 'Sunny' : 0.5},
'Sunny|Rainy' : {'Rainy' : 0.6, 'Sunny' : 0.4},
'Sunny|Sunny' : {'Rainy' : 0.3, 'Sunny' : 0.7},
}

emission_probability = {
'Rainy' : {'walk': 0.1, 'shop': 0.4, 'clean': 0.5},
'Sunny' : {'walk': 0.6, 'shop': 0.3, 'clean': 0.1},
}

def forward_viterbi(obs, states, start_p, trans_p, emit_p):
T = {}
for state1 in states:
for state2 in states:
## prob. V. path V. prob.
T[state1+"|"+state2] = (start_p[state1+"|"+state2], [state2], start_p[state1+"|"+state2])
for output in obs:

U = {}
print "--------------------\nObservation:",output
for next_state in states:
total=0
argmax=None
valmax=0
print "Next state:"+next_state
for curr_state in states:
for prv_state in states:
print "\tprv_state|curr_state:",prv_state+"|"+curr_state
try:
(prob, v_path,v_prob)=T[prv_state+"|"+curr_state]
except KeyError:
(prob, v_path,v_prob)=T[prv_state+"|"+curr_state]=(0,None,0)

p=emit_p[curr_state][output] * trans_p[prv_state+"|"+curr_state][next_state]
prob *= p
v_prob *= p
total += prob
if v_prob > valmax:
argmax=v_path+[next_state]
valmax=v_prob
print "\t\t",v_path,v_prob
U[curr_state+"|"+next_state] = (total, argmax, valmax)
print "\targmax:",argmax,"valmax:",valmax
T=U
## apply sum/max to the final states:
total = 0
argmax = None
valmax = 0
for state1 in states:
for state2 in states:
try:
(prob, v_path, v_prob) = T[state1+"|"+state2]
except KeyError:
(prob, v_path, v_prob) = T[state1+"|"+state2]=(0,None,0)
total += prob
if v_prob > valmax:
argmax = v_path
valmax = v_prob
return (total, argmax, valmax)

def example():
return forward_viterbi(observations,
states,
start_probability,
transition_probability,
emission_probability)

res=example()
print "\nResult:",res

Saturday, December 20, 2008

Side-Middle Berth!!!


Population is increasing. There's no space for more lines, we can't introduce new trains. So what do we do? Increase packing density :)

Friday, December 12, 2008

My first 0


I got my first ever 0 in AI mid sem exams. Prof. Pushpak Bhattacharyya had a wry smile on as he distributed the answerbooks, as if to say "Welcome to IIT". I managed a BB in the subject :-)

Wednesday, December 10, 2008

A do-anything firefox toolbar

We have a course called "Software Lab" at IITB. The agenda of this course is - one programming language every week, with a side effect - you fall in love with linux and everything that is free and open source. As a part of the course, we have to contribute something to the open source community. So, I, along with Sumair and Sree developed "Run-a-prog", a do-anything toolbar for firefox. Screenshot

Run-a-prog allows you to run ANY program on the text selected on a webpage. For example, if you have a text2speech program, you can add it to the toolbar and make it read out the text you selected on the page at the click of a button. You can write your own programs using any programming language of your choice and add it to the toolbar, and run it on selected text. All your program has to do is take a file name as a command line argument. Besides this, there are a few other useful features as well ;)



Run-a-prog has been tested on Fedora Core, Ubuntu and Windows XP and works fine with Firefox 2.0 and 3.0. To install Run-a-prog, download our cross platform installer and open it with firefox. Comments and suggestions are welcome :)

I have published the project on Mozdev.org, and can be accessed at http://runaprog.mozdev.org

Here is a presentation which gives an overview of the functionality and design. The source code and the documentation is available here.

Sunday, December 7, 2008

26/11 and onwards

It was my last exam that day, and I was happy that it had gone well. After the exam, I went to the lab and started off on my mini-project for Service Oriented Computing. Dhaval and I had to do it, start to finish, in 36 hours, and we were coding frantically. At about 11PM, Vishal told us that there were blasts in a few hotels in Mumbai. We didn't give it much of a thought and just carried on with our work. At 2.30AM the same night, when I went back to the hostel, I saw the TV room was pretty crowded, and a whole lot of guys silently staring at the TV. I went in, saw the disturbing visuals for a while and went to bed, couldn't sleep for quite a while....

I woke up early the next day (because parents called early that morning to tell me to stay indoors) and grabbed a copy of the Times, the first page read - "WAR ON MUMBAI". The news didn't make a pleasant read. I went to the lab after breakfast and continued work on the mini-project, all the time hooked to the rediff homepage.

28th November was a busy day, I had my project demo. We did the final parts of the documentation, had a decent demo. I came back to the hostel TV room after that, and witnessed a very moving interview of Sabina Sehgal's husband on CNN-IBN, I simply couldn't stand the pain and went back to my room, lied down on my bed, frustrated, angry.

More thinking....and I thought of making a resolution to kill atleast one terrorist before I die...my heart said "yes", my mind kept on asking "Is it logical? Can you do it? What about your family?". I still don't know. The movie "A Wednesday" show's that even a "stupid common-man" can make a difference, but it's only a movie. My questions are still unanswered.

Tuesday, August 26, 2008

Janmashtami

Janmashtami

For the first time, I saw Janmashtami being celebrated the "Marathi" way. It was awesome fun watching :-) My friend Sree Shankar, one of the guys in the photo above(click to view more), has described the entire experience really well in his blog. Here is an extract (reproduced here with permission)

It was decided that 8 people will form the base, 4 on top of them and then a 3rd guy on top of us to break the matki. As all of were discussing of how to go about it, suddenly a bucket of water fell on us...."abee saale bhen**** teri maa ki..." shouts came out from the group...For me this water business was unexpected and I was totally drenched...

I was at the base (fat people are not allowed to climb others shoulders and break others hands :D). There were 8 of us. The water kept falling on us from the 2nd and 3rd floor....and the swearings kept coming out...The 2nd layer started forming. Everyone was shouting "Alareeeeee govindaaaaaaa"...The moment a guy got on to my shoulders I was like "O man this guy weighs a ton"...but the spirit of alare govinda kept all of us going....in between the guys on the top floor started pouring hot water...the swearing too got hotter....the water was soo hot that the cry of "alare govinda" was replaced by "aaaaaaaaaaaahhhhhhhhhhh $#&#@#%$"...we could even see smoke rising from the ground once the water touched the floor...

But we still kept on going...The 2nd layer was formed. (the guy above me seemed to have a special ability to increase his weight every second)...The last guy started climbing...by this time the "pyramid" already started shaking :D...suddenly..."dim dim dim...." before I knew what happened my shoulder suddenly felt light...then only I saw it...the 2nd layer and 3rd layers were now on the "ground floor"...one on top of the other...one guys head was inside the pile on the ground and his 2 legs jutting out...everyone started laughing out soo much...the ground had turned so much muddy with water that we were all covered in mud...

This went on like this for some 4-5 times,climbing and falling, before we successfully broke the pot. Cries of joy exploded out and it was all round celebrations. People were kicking mud on each other..photos taken...as for me it was such a good time...never in the recent past could I remember myself to be covered in so much mud and still enjoying...This was followed by tug of war. All in all it was such a gr8 day..one of my most memorable.

Monday, August 18, 2008

Life at IIT Bombay

Yes guys, it's been a long time since I blogged. I mainly attribute it to the deluge of assignments that I've been given.

Lots of you have been asking me - "How's life at IITB?", hence this post.

Before I came to IITB, I had imagined that it'd have green-carpet lawns, neatly pruned hedges and aesthetic looking trees etc. It's not so. IITB is wild. It has huge trees, with climbers covering the trunks, going all the way up to the branches, and then hanging down like ropes. It has money plants with leaves as big as banana leaves (I'm not exaggerating), parrots, mynas, pigeons, cranes, sea gulls and many other kinds of birds that I don't recognize.

IITB is flanked on the left by a green hill, and on the right by a lake. Near the hill is a national park (from which a panther had wandered into the campus a few years ago).

Moving from the wildlife to the hostels, most of the hostels look as if they may crumble any moment. But looks can be deceiving ;) The hostels are built to stand the Mumbai rains. Even during heavy rains that we saw in the last month, none of the rooms got even a drop of water inside, and no water logging anywhere. Every hostel consists of about six 3-storeyed buildings, and one can go from any building to any other building without getting wet. The rooms are good and comfy, bathrooms are beautiful too ;) We get hot water even at midnight! There are washing machines to do the laundry, a billiards table, TT table, carroms and a gym (all this within the hostel). We also get a dozen different newspapers everyday. Food is great most of the time(yeah, honest!)

I'll talk about the lessons some other day. That's it for now :)