Scipy Exercises
Exercise 10.1: Least squares
import numpy as np
import scipy.optimize as opt
m = 10
n = 5
num = 20
A = np.random.randint(-num, num, size = m * n).reshape(m, n)
b = np.random.randint(-num, num, size = m * 1).reshape(m, 1)
# Least squares, solve (A.T)Ax = (A.T)b
x = np.dot(np.dot(np.linalg.inv(np.dot(A.T, A)), A.T), b)
# Compute the norm of the residual
print ("The norm of the residual:", np.linalg.norm(x))
Result of Exercise 10.1
Exercise 10.2: Optimization
import numpy as np
import scipy.optimize as opt
def f(x):
"""Compute f(x) = -sin^2(x - 2)exp(-x^2)"""
return -np.power(np.sin(x - 2), 2) * np.exp(-np.power(x, 2))
print ("f(x) = -sin^2(x - 2)exp(-x^2)")
# find maximum by minimum of -f(x)
max = -opt.minimize_scalar(f).fun
print ("maximum of f(x):", max)
print ("when x =", opt.minimize_scalar(f).x)
Result of Exercise 10.2
Exercise 10.3: Pairwise distances
import numpy as np
from scipy.spatial import distance
n = 5
m = 5
num = 20
# Generate matrix X with 5 rows and 5 cols
X = np.random.randint(-num, num, size = n * m).reshape(n, m)
print ("Matrix X")
print (X)
for i in range(0, n):
for j in range(i + 1, n):
print ("The distance between row", i + 1, "and row", j + 1, "is ", end = "")
print (distance.cityblock(X[i], X[j]))
Result of Exercise 10.3