Min, Max and Norm

I'm going to begin by initializing a numpy array.

In [1]:
import numpy as np
x = np.array([4,2,9,-6,5,11,13])
x
Out[1]:
array([ 4,  2,  9, -6,  5, 11, 13])

So now I have instantiated a numpy. And I may want to figure out the highest and/or lowest elements in the array. Now numpy has built in functions for precisely this.

  • I need simply type np.max of x and np.min of x.
  • Alternatively, I can access the maxes and mins from an array
In [2]:
np.max(x)
Out[2]:
13
In [3]:
x.max()
Out[3]:
13
In [4]:
np.min(x)
Out[4]:
-6
In [5]:
x.min()
Out[5]:
-6

Random and Linear Algebra in Numpy

Random
  • Let's start with random. And to do this, I'm going to go ahead and type an np.random.
  • generating a random matrix.

So I'm going to go ahead and type in np.random.random once more and feed it in a size.
I want to make random 2 by 1 numpy array. This produces a 2 by 1 matrix with elements drawn randomly from the uniform distribution.

In [6]:
np.random.random([2,1])
Out[6]:
array([[0.89333437],
       [0.80202254]])

I can also produce one element at random by simply typing np.random.random.

In [7]:
np.random.random()
Out[7]:
0.9087695743413609

I'll have a number drawn randomly from the uniform distribution, in this case, 0.977

Linear Algebra Module
  • is numpy's built in linear algebra module. And I can access it via np, or numpy, dot linalg. Just as with random, there is a vast set of methods and attributes within. And in particular, I want to talk about finding the norm of a matrix

  • norm is built into numpy's linear algebra module as well. Now let's recall our numpy array x. I now want to find its L2 norm. That is the square root of the sum of each of its elements squared.

  • The way to do this is np.linalg.norm(x)

In [8]:
np.linalg.norm(x)
Out[8]:
21.2602916254693

Example:

Write a function called norm that takes as input two Numpy column arrays A and B, adds them, and returns s, the L2 norm of their sum.

In [9]:
def norm(A,B):
    """
    Takes two Numpy column arrays, A and B, and returns the L2 norm of their
    sum.

    Arg:
      A - a Numpy array
      B - a Numpy array
    Returns:
      s - the L2 norm of A+B.
    """
    s = np.linalg.norm(A + B)
    return s
In [10]:
A = np.random.random([4,])
B = np.random.random([4,])
In [11]:
A
Out[11]:
array([0.12531355, 0.43334018, 0.70309934, 0.10365833])
In [12]:
B
Out[12]:
array([0.99766888, 0.94448308, 0.77763883, 0.76006777])
In [13]:
norm(A,B)
Out[13]:
2.469432075981698