Python Matrices

I’ve been using the Python programming language increasingly often over the past few months, mostly because two powerful machine learning libraries — Google’s TensorFlow and Microsoft’s CNTK — have Python interfaces.

For both tools, a solid knowledge of Python is essential so that the libraries can be customized to fit the problem at hand. In many situations this means reading data into a vector, or a matrix, or an n-dimensional array.

There are two basic ways to create a (two-dimensional) matrix in Python. You can use a built-in list-of-lists approach, or you can use the ndarray type from the NumPy (“numerical Python”) add-on package. So, here’s my personal reminder of the difference between the two.

A typical 3×4 list-of-lists style matrix is:

nRows = 3
nCols = 4
matrix_ll = [[0.0 for j in range(0, nCols)]
  for i in range(0, nRows)]
# matrix_ll[1,2] = 5.0  # error
matrix_ll[1][2] = 5.0
print("list-of-lists matrix: ")

There are of course zillions of alternatives. Using a NumPy approach:

import numpy as np

matrix_np = np.zeros(shape=[nRows,nCols],
matrix_np[1,2] = 5.0  # my preferred indexing style
matrix_np[2][3] = 7.0  # list-like indexing style works too
print("numpy matrix: ")

The NumPy approach is basically better, with the exception that you take a dependency on the NumPy package.

This entry was posted in Machine Learning. Bookmark the permalink.