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
from scipy.linalg import norm,lstsq
n = 10
m = 20
A = np.random.randint(0, 100, size=(m, n))
b = np.random.randint(0, 100, size=(m, 1))
x,res, rnk, s= lstsq(A, b)
l = norm(b-np.dot(A,x),ord=2)
print(A)
print(b)
print(l)
result:
RuntimeWarning: internal gelsd driver lwork query error, required iwork dimension not returned. This is likely the result of LAPACK bug 0038, fixed in LAPACK 3.2.2 (released July 21, 2010). Falling back to 'gelss' driver.
我上网查了一下,发现不是什么大问题,不会影响结果。
Exercise 10.2: Optimization
Find the maximum of the function
f(x) = sin2(x − 2)e−x2
import numpy as np
from scipy import optimize
fun = lambda x : (-1)*(np.sin(x-2))**2*np.exp((-1)*(x**2))
temp = optimize.minimize_scalar(fun)
ans = -temp.fun
print(temp)
print("the maximum is " + str(ans))
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.
import numpy as np
import scipy.spatial.distance
n = 10
m = 20
X = np.random.randint(0,100,size=(n,m))
ans = scipy.spatial.distance.pdist(X, "euclidean")
print(X)
print(ans)
result: