scipy
Exercise 10.1: Least squares
Generate matrix A ∈ Rm×n with m > n. Also generate some vector b ∈ Rm. Now find x = argmin x ||Ax−b||2. Print the norm of the residual.
import numpy as np
import scipy.optimize as opt
A = np.random.rand(10, 5)
b = np.random.rand(10, 1)
def func(p, A, b):
x = p.reshape(5, 1)
return (np.dot(A, x) - b).reshape(-1)
p0 = np.random.rand(5, 1)
p0 = [p0]
res = opt.leastsq(func, p0, (A, b))
norm = np.linalg.norm(func(res[0], A, b))
print(res[0])
print(norm)
运行结果:
[ 0.59510766 0.09119742 0.48249284 0.67933586 -0.5243152 ]
0.33809584697476897
Exercise 10.2: Optimization
Find the maximum of the function
sin2(x−2)e−x2 sin 2 ( x − 2 ) e − x 2
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
def f(x):
return - np.sin(x) ** 2 * np.e ** ( - x ** 2)
res = opt.minimize_scalar(f)
print(res)
x = np.linspace(-5, 5, 1000)
y = -f(x)
plt.figure()
plt.plot(x, y, 'r')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('f(x) = sin²(x−2)e^(−x²)')
plt.show()
运行结果:
fun: -0.2741283295576515
nfev: 14
nit: 10
success: True
x: 0.8603335912423467
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
A = np.random.randint(0, 10, (5, 2))
res = dis.pdist(A)
print(A)
print(res)
print(dis.squareform(res)) # 向量形式的距离转换为矩阵形式
运行结果:
[[3 4]
[2 2]
[0 4]
[7 4]
[7 9]]
[2.23606798 3. 4. 6.40312424 2.82842712 5.38516481
8.60232527 7. 8.60232527 5. ]
[[0. 2.23606798 3. 4. 6.40312424]
[2.23606798 0. 2.82842712 5.38516481 8.60232527]
[3. 2.82842712 0. 7. 8.60232527]
[4. 5.38516481 7. 0. 5. ]
[6.40312424 8.60232527 8.60232527 5. 0. ]]