0

I have a portion of Viterbi algorithm that I want to manipulate. I need to understand the slicing part in this code:

import numpy as np

A = np.array([[0.6, 0.2, 0.2], [0.5, 0.3, 0.2], [0.4, 0.1, 0.5]])
pi = np.array([0.5, 0.2, 0.3])
O = np.array([[0.7, 0.1, 0.2], [0.1, 0.6, 0.3], [0.3, 0.3, 0.4]])

states = UP, DOWN, UNCHANGED = 0, 1, 2
observations = [UP, UP, DOWN]

alpha = np.zeros((len(observations), len(states))) # time steps x states
alpha[:,:] = float('-inf')
backpointers = np.zeros((len(observations), len(states)), 'int')

***alpha[0, :] = pi * O[:,UP]***

in the last line print out the O[:,UP] what is should give me: [0.7, 0.1, 0.2] I believe instead, it gives me:

O[:,UP]
Out[15]: array([ 0.7,  0.1,  0.3])

I tried to look into this Understanding Python's slice notation I couldn't understand why it changes the last element of the array.

Also, I run this:

O[:,UNCHANGED]
Out[17]: array([ 0.2,  0.3,  0.4])

I'm still newbie in python, I need some help

Ali
  • 43
  • 7

1 Answers1

1

You are mixing up the notation for columns and rows.

You print O[:,UP] which gives you all the rows and just the "UP"th column (index 0).

Your O is:

array([[ 0.7,  0.1,  0.2],
       [ 0.1,  0.6,  0.3],
       [ 0.3,  0.3,  0.4]])

And O[:,0] is

         #↓ this column
array([[ 0.7,  0.1,  0.2],
       [ 0.1,  0.6,  0.3],
       [ 0.3,  0.3,  0.4]])

where O[0,:] would be

array([[ 0.7,  0.1,  0.2], #This row
       [ 0.1,  0.6,  0.3],
       [ 0.3,  0.3,  0.4]])

And just to make the last part clear, O[:,UNCHANGED] is O[:,2] which is here:

                      #↓ this column
array([[ 0.7,  0.1,  0.2],
       [ 0.1,  0.6,  0.3],
       [ 0.3,  0.3,  0.4]])
Stephen C
  • 1,966
  • 1
  • 16
  • 30
  • OOh I got it now, I'm really mixing this up. Thank though. I got the point – Ali Feb 26 '18 at 05:20
  • NumPy slicing can be a bit odd depending on what language you are coming from, but after you get used to it, it's awesome. Best luck =) – Stephen C Feb 26 '18 at 05:22