Printing Serialized Matrices

When I’m writing code, I often run into mini-problems that are somewhat interesting, even if they’re not important in the overall scheme of things.

I was working with neural networks. A 4-5-3 NN (4 input nodes, 5 hidden nodes, 3 output nodes) has a 4×5 input-to-hidden weights matrix, a 1×5 hidden-biases matrix, a 5×3 hidden-to-output weights matrix, and a 1×3 output-biases matrix.

In order to pass these four matrices around as function parameters, it’s usual to serialize the values into a single array with 43 values. But when you display the values, it’s nice to see them displayed as four matrices.

I set out to write a little function (in Python) to do this. The calling signature is:

wts = np.array([
 0.01, 0.02, 0.03, 0.04, 
 0.05, 0.06, 0.07, 0.08, 
 0.09, 0.10, 0.11, 0.12, 
 0.13, 0.14, 0.15, 0.16, 
 0.17, 0.18, 0.19, 0.20, 

 0.21, 0.22, 0.23, 0.24, 0.25, 

 0.26, 0.27, 0.28, 
 0.29, 0.30, 0.31, 
 0.32, 0.33, 0.34, 
 0.35, 0.36, 0.37, 
 0.38, 0.39, 0.40, 

 0.41, 0.42, 0.43], dtype=np.float32)

my_print(wts, 4, [(4,5),(1,5),(5,3),(1,3)])

The single 4 indicates how many decimal points to display. The list-of-tuples indicates the shapes that the array of values should be displayed.

So, I fiddled around for a bit and was satisfied when I got the display function to work.

import numpy as np

def my_print(arr, decs, shapes):
  # print serialized-as-arrary matrices
  fmt = "% 0." + str(decs) + "f "  # like % 0.4f
  k = 0;
  for t in shapes:
    for i in range(t[0]):
      for j in range(t[1]):
        print(fmt % arr[k], end="")
        k += 1
      print("")
    print("")

There’s no big moral to the story, just the obvious: coding is a skill and you need to practice it. Every little problem solved increases your internal bag of tricks.

In the larger picture, I suspect (but don’t know for sure), that coding is good mental exercise and is beneficial to your general cognitive abilities.



For some entirely unknown reason, I enjoy watching old movie serials from the 1930s and 40s. In the days before television, people would go watch movies all the time. Before the main feature, theaters would show one 20-minute episode of the typically 12-part serial. “The Phantom Empire” (1935) starred Gene Autry, a wonderful man, who was a good friend of my father.

Advertisements
This entry was posted in Machine Learning, Miscellaneous. Bookmark the permalink.