Exercise 10.1: Least squares
Generate matrix A ∈ R^m×n with m > n. Also generate some vector b ∈ R^m . Now find x = argmin x ||Ax − b||_2 .Print the norm of the residual.
import numpy as np
import scipy.linalg as lina
m = 20
n = 10
A = np.random.normal(size=(m, n))
print('A = ')
print(A)
b = np.random.normal(size=(m, 1))
print('b = ')
print(b)
x = np.dot(np.dot(lina.inv(np.dot(A.T, A)), A.T), b)
print('estimated x = ', x)
Exercise 10.2: Optimization
Find the maximum of the functionf(x) = (sin(x − 2))^2 e ^(−x^2)
#10.2
def f(x):
return - np.power(np.sin(x-2), 2) * np.exp(-x*x)
result = - opt.minimize_scalar(f).fun
print('\nmaximum of f(x) is ', result)
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.
#10.3
x = np.random.rand(10, 5)
y = dis.pdist(x)
print('pairwise distances between every two rows are:')
print(y)