Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python transition matrix

I have a list looking like this:

[2, 1, 3, 1, 2, 3, 1, 2, 2, 2]

What I want is a transition matrix which shows me the sequence like:

  • How often is a 1 followed by a 1
  • How often is a 1 followed by a 2
  • How often is a 1 followed by a 3

  • How often is a 2 followed by a 1

  • How often is a 2 followed by a 2
  • How often is a 2 followed by a 3

and so on...

((0,2,1), (1,2,1), (2,0,0))

Is there a premade module go get this?

like image 579
Flo Avatar asked Dec 11 '22 04:12

Flo


1 Answers

I don't know if there's a module, but I'd go with this code, which is easily generalizeable:

import numpy as np
from collections import Counter
a = [2, 1, 3, 1, 2, 3, 1, 2, 2, 2]
b = np.zeros((3,3))
for (x,y), c in Counter(zip(a, a[1:])).iteritems():
    b[x-1,y-1] = c
print b
array([[ 0.,  2.,  1.],
       [ 1.,  2.,  1.],
       [ 2.,  0.,  0.]])

With no numpy installed:

b = [[0 for _ in xrange(3)] for _ in xrange(3)]
for (x,y), c in Counter(zip(a, a[1:])).iteritems():
    b[x-1][y-1] = c

print b
[[0, 2, 1], [1, 2, 1], [2, 0, 0]]

A few details of what's going on, if needed:

  1. zip(a, a[1:]) gets all the pairs of consecutive numbers.
  2. Counter counts how many times each pair appears
  3. The for loop simple converts the dictionary Counter produces into the matrix / list of lists you requested
like image 168
Korem Avatar answered Dec 31 '22 15:12

Korem