Exercise 10.1: Least squares
Generate matrix A ∈ Rm×n with m > n. Also generate some vector b ∈ Rm. Now find x = arg minx ∥Ax − b∥2.
Print the norm of the residual.
import numpy as np
import scipy as sp
m = 20
n = 15
A = np.random.random((m,n))
b = np.random.random((m,))
x, residual, rank, s = sp.linalg.lstsq(A,b)
b1 = A.dot(x)
print(sp.linalg.norm(b - b1))
运行结果:
0.3462921048521962
Exercise 10.2: Optimization
Find the maximum of the function :f(x) = sin2(x − 2)e−x2
from scipy.optimize import fmin
def func(x):
return -(np.sin(x-2))**2*(np.exp(-x**2))
opt = fmin(func,0)
print(-f(opt)[0])
运行结果:
Optimization terminated successfully.
Current function value: -0.911685
Iterations: 20
Function evaluations: 40
0.9116854117069156
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.
n = 5
m = 3
A = np.random.rand(n,m)
X = scipy.spatial.distance.pdist(A)
Y = scipy.spatial.distance.squareform(X)
print(Y)
运行结果:
[[0. 1.03161295 0.79745052 0.54036634 0.49914287]
[1.03161295 0. 0.89030578 1.18083032 0.67161284]
[0.79745052 0.89030578 0. 0.84625376 0.9042936 ]
[0.54036634 1.18083032 0.84625376 0. 0.69062377]
[0.49914287 0.67161284 0.9042936 0.69062377 0. ]]