Exercise 10.1: Least squares Generate matrix A ∈ Rm×n with m > n. Also generate some vector b ∈ Rm. Now find x = argminxkAx−bk2. Print the norm of the residual.
import numpy as np
import scipy.linalg as li
m = 10
n = 20
A = np.random.rand(m, n)
b = np.random.rand(m, 1)
A = np.mat(A)
b = np.mat(b)
x = li.inv(A.T * A) * A.T * b
print(x)
Exercise 10.2: Optimization Find the maximum of the function
import numpy as np
import scipy.optimize as op
import math
def func(x):
return (-(math.sin(x-2)**2)*math.exp(-(x ** 2)))
a = op.fminbound(func, -10, 10)
print(-func(a))
Exercise 10.3: Pairwise distances Let X be a matrix with n rows and m columns. How can you compute the pairwise distances between every two rows?As an example application, consider n cities, and we are given their coordinates in two columns. Now we want a nice table that tells us for each two cities, how far they are apart.
Again, make sure you make use of Scipy's functionality instead of writing your own routine.
import numpy as np
import scipy.spatial.distance as dis
import math
X = np.random.rand(m, n)
print(X)
Y = dis.pdist(X)
print('Distance is :')
print(dis.squareform(Y))