import numpy as np
import time
First, a motivating example for why we might want a NUMerical PYthon (numpy) library.
Squaring a list of numbers:
num_elements = 1000000
input_array = list(range(num_elements))
start_time = time.time()
return_array = [0] * len(input_array)
for key, val in enumerate(input_array):
return_array[key] = val * val
print(time.time() - start_time)
start_time = time.time()
return_array_vectorized = np.square(input_array)
print(time.time() - start_time)
np.zeros(5)
np.identity(3)
array_1 = np.array([[1,2],[3,4],[5,6]]) # An array with arbitrary elements.
array_1
array_1.shape
type(array_1)
array_1.shape
array_1[1,1] # Access an element
array_1[1] # Access a row
array_1[:,1] # Access a column
array_1[1,:] # Access a row
array_1[1]
array_1[[1,1,1]]
array_1[:,1]
array_1[:,[1,1,1]]
Perhaps one of the most useful is to convert a list of integers to 1-hot vectors:
np.eye(3)[[1,1,0,2]]
array_1 + [[1,1],[1,1],[1,1]]
array_1 * array_1 # elementwise multiplication
array_2 = np.add(array_1, 1) # array_1 + 1
array_2
array_2 = array_1 + 1
array_2
# Recall:
array_2.shape
array_2 = array_1 + [1,2]
array_2
array_2 = array_1 + [1,2,3]
array_2
np.array([[1,2]]).shape
array_2 = array_1 + [[1,2]]
array_2
array_1 * 2 # np.multiply(array_1, 2)
array_1 / 2.0 # np.multiply(array_1, 1/2.0) @
# Vector
array_3 = np.array([1,2,3])
array_4 = np.array([4,5,6])
np.dot(array_3, array_4)
# Or:
array_3.dot(array_4)
# Matrix
array_3 = np.array([[1, 2]]) # [1, 2]
array_4 = np.array([[3], [4]]) # [2, 1]
np.dot(array_3, array_4) # Inner-product
array_5 = np.dot(array_4, array_3)
array_5
array_5.sum(axis=0) # np.mean(array_4, 0)
array_5.sum(axis=1) # np.mean(array_4, 0)
array_5.sum()
array_5.mean(axis=0)
array_5.std(axis=0)
array_5.max(axis=0)
array_5.shape
M1 = array_1.T
M1
np.power(M1, 3) # M1 ^ 2?
e = np.square(M1) == np.power(M1, 2)
e
if e:
print('e is True')
if np.all(e):
print('all entries of e are True')
if np.any(e):
print('at least 1 entry of e is')
if np.any(e):
print('at least 1 entry of e is')
np.all(e, 0) # if it makes sense, you can pass an axis argument!
np.linalg.inv(np.array([[2, 0], [0, 2]]))
np.linalg.inv(np.matmul(M1.T, M1)) # This should raise an exception.
A1 = np.array([[1, 1], [0, 1]])
x1 = np.array([[2], [2]])
b1 = np.matmul(A1, x1)
b1
x1_verify = np.linalg.solve(A1, b1)
all(x1 == x1_verify)
A2 = np.array([[1, 1], [2, 2]]) # Note that the rank of this matrix is 1.
x2 = np.array([[2], [3]])
potential_sol = np.matmul(A2, x2)
potential_sol
b2 = np.array([[5], [11]])
x2_verify = np.linalg.solve(A2, b2) # This should raise an exception.
# There is no selection of x to solve this linear system for A2 and b2.
x2_verify = np.linalg.solve(A2, potential_sol) # This should raise an exception.
# There happens to exist an x to solve this system, but numpy still fails.
A3 = np.array([[1, 0, 0], [0, 1, 1]])
x3 = np.array([[1], [1], [1]])
b3 = np.matmul(A3, x3)
b3
np.linalg.solve(A3, b3) # This should raise an exception.