Exercise 10.1: Least squares
Generate matrix with . Also generate some vector .
Now find .
Print the norm of the residual.
import numpy as np from scipy import linalg m, n = 5, 4 A = np.mat(np.random.rand(m, n)) b = np.mat(np.random.rand(m, 1)) x, res, rnk, s = linalg.lstsq(A, b) norm = linalg.norm(A.dot(x) - b, ord = 2) print("A =\n",A) print("b =\n",b) print("Solution =\n", x) print("Norm =", res / n)
Exercise 10.2: Optimization
Find the maximum of the function .
import numpy as np from scipy import optimize from matplotlib import pyplot as plt def func(x): return -np.sin(x - 2) ** 2 * np.exp(-x * x) maximum = optimize.fmin(func, 0) print(maximum)
Exercise 10.3: Pairwise distances
Let be a matrix with rows and columns. How can you compute the pairwise distances between every two rows?
As an example application, consider 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 from scipy.spatial import distance m, n = 5, 2 x = np.random.rand(m, n) print("X =\n", x) y = distance.pdist(x) z = distance.squareform(y) print("Distance =\n", z)