Numpy Examples
This post is an introduction to using numpy, and some fundamental matrix operations that someone will frequently use whem using numpy library. I had written these snippets when I was doing Computational Photography and Computer Vision Courses. This also demonstrates using ipython notebook in my blog.
Reference Materials¶
In [9]:
"""
Program: numpy_transpose.py
Purpose: This example illustrates transpose of a matrix.
Study Material:
* https://www.khanacademy.org/math/linear-algebra/matrix-transformations/matrix-transpose/v/linear-algebra-transpose-of-a-matrix
Associated thoughts:
Why is Matrix Transpose useful?
* http://mathforum.org/library/drmath/view/71949.html
"""
import pprint
import numpy as np
def main():
print("Simple Matrix.")
mat = np.arange(9).reshape(3, 3)
pprint.pprint(mat)
print("----")
print("Transpose of the Matrix.")
transposed = np.transpose(mat)
pprint.pprint(transposed)
if __name__ == '__main__':
main()
In [10]:
"""
Roll the specified axis backwards, until it lies in a given position.
start parameter denotes the axis which is rolled until it lies before this position.
The default, 0, results in a “complete” roll.
Reference:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html
What is an axis or How is axis indexed in numpy array?
the axis number of the dimension is the index of that dimension within the array's shape
* https://stackoverflow.com/a/17079437/18852
Why is rollaxis so confusing?
* https://stackoverflow.com/a/29903842/18852
"""
import numpy as np
def main():
a = np.arange(8).reshape(4, 2, 1)
print("shape")
print(a.shape)
print("rollaxis 0, 1, 2")
print(np.rollaxis(a, 0).shape)
print(np.rollaxis(a, 1).shape)
print(np.rollaxis(a, 2).shape)
print("rollaxis 0, start 1")
print(np.rollaxis(a, 0, 1).shape)
print("rollaxis 1, start 1")
print(np.rollaxis(a, 1, 1).shape)
print("rollaxis 2, start 1")
print(np.rollaxis(a, 2, 1).shape)
print("rollaxis 0, start 2")
print(np.rollaxis(a, 0, 2).shape)
print("rollaxis 1, start 2")
print(np.rollaxis(a, 1, 2).shape)
print("rollaxis 2, start 2")
print(np.rollaxis(a, 2, 2).shape)
if __name__ == '__main__':
main()
In [11]:
"""
Axis is the dimension of the matrix. For the 2d matrix, we often say rows or columns instead of axis.
But when more than 2 dimensions are involved, we refer to them as axis.
According to numpy documentation, axes are defined for arrays with more than one dimension. A 2-dimensional array has
two corresponding axes: the first running vertically downwards across rows (axis 0), and the second running
horizontally across columns (axis 1).
Many operation can take place along one of these axes.
For example, we can sum each row of an array, in which case we operate along columns, or axis 1:
If you do .sum(axis=n), then dimension n is collapsed and deleted, with each value in the new matrix equal to the
sum of the corresponding collapsed values.
References
* https://docs.scipy.org/doc/numpy-1.13.0/glossary.html
* https://stackoverflow.com/questions/17079279/how-is-axis-indexed-in-numpys-array/17079437#17079437
"""
import numpy as np
def main():
mat = np.arange(12).reshape((3, 4))
print("Original Matrix:")
print(mat)
collapse_rows_with_sum = np.sum(mat, axis=1)
print("Matrix Collapsed with Sum along the rows:")
print(collapse_rows_with_sum)
if __name__ == '__main__':
main()
In [12]:
"""
A numpy array is a grid of values,
* All of the same type. (unlike python arrays which can be heterogenous).
* Is Indexed by a tuple of non negative integers.
The number of dimensions is the rank of the array;
the shape of an array is a tuple of integers giving the size of the array along each dimension.
Arrays can be initialized in variety of ways.
Reference
* http://cs231n.github.io/python-numpy-tutorial/
"""
import numpy as np
def main():
print("Single Dimensional Array.")
a = np.array([1, 2, 3])
print(a)
print("Two Dimensional Array.")
a = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(a)
print("Array of Zeros")
a = np.zeros((4, 5))
print(a)
print("Array of Ones")
a = np.ones((3, 2, 3))
print(a)
print("Constant Array")
a = np.full((1, 2, 3, 4), 5)
print(a)
print("Create an Identity Matrix")
a = np.eye(4)
print(a)
print("Creating a Random Array")
a = np.random.random((2, 5))
print(a)
if __name__ == '__main__':
main()
In [13]:
"""
Numpy linspace returns evenly spaced numbers over a specified interval.
We specify the start point, and the end point, and the total number points we want within that interval.
The linspace function will return those.
References
----------
* https://www.sharpsightlabs.com/blog/numpy-linspace/
"""
import numpy as np
def main():
print("linspace from 0 to 100 of 5 values.")
values = np.linspace(start=0, stop=100, num=5)
print(values)
print("linspace from 0 to 100 of 5 values, excluding the endpoint")
values = np.linspace(start=0, stop=100, num=5, endpoint=False)
print(values)
print("linspace from 0 to 100 of 5 values, with return step.")
values = np.linspace(start=0, stop=100, num=5, endpoint=False, retstep=True)
print(values)
if __name__ == '__main__':
main()
In [14]:
"""
arange is an array-valued version of the built in python range function.
This can be used instead of linspace, but when using a non integer step, such as 0.1,
the results will often not be consistent. It is better to use `numpy.linspace` for these cases.
"""
import numpy as np
def main():
out = np.arange(15)
print(out)
out = np.arange(15, dtype=np.float32)
print(out)
# When using a non-integer step, such as 0.1, the results will often not
# be consistent. It is better to use `numpy.linspace` for these cases.
out = np.arange(0, 2, 0.1, dtype=np.float32)
print(out)
if __name__ == '__main__':
main()
In [15]:
"""
asarray is a numpy numpy method to convert the input to an ndarray, but it does not copy the input if it is already an
ndarray.
"""
import numpy as np
def main():
a = [1, 2, 3]
out = np.asarray(a)
print(out)
a = np.array([1., 2, 3], dtype=np.float16)
print(a)
print(a.dtype)
out = np.asarray(a, dtype=np.int32)
print(out)
print(out.dtype)
if __name__ == '__main__':
main()