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 lstsq
A = np.mat(np.random.randint(0,10,(20,10)))
b = np.mat(np.random.randint(0,10,(20,1)))
ret = lstsq(A,b)
x = np.mat(ret[0])
norm_re = np.linalg.norm(A*x-b,ord=2)
print("x= \n",x)
print("norm = ",norm_re,"\n")
样例输出:x=
[[ 0.27747234]
[ 0.01934983]
[-0.17288909]
[ 0.40072252]
[ 0.25301335]
[ 0.34450555]
[ 0.03587142]
[-0.16029266]
[-0.18460015]
[-0.14021874]]
norm = 5.7700277909560445
Exercise 10.2: Optimization
Find the maximum of the function f(x) = sin2(x − 2)e−x2
代码:
from scipy.optimize import fmin
import numpy as np
def f(x):
return (-1)*(np.sin(x-2)**2)*(np.e**(-1*x**2))
res = fmin(f,1)
res_ = -1*res[0]
print(res_)
样例输出:Optimization terminated successfully.
Current function value: -0.911685
Iterations: 16
Function evaluations: 32
-0.2162109374999993
Exercise 10.3: Pairwise distances
Let X be a matrix with n rows and m columns. How can you compute the pairwise distances betweenevery two rows?
As an example application, consider n cities, and we are given their coordinates in two columns. Nowwe 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.
代码:
from scipy.spatial.distance import pdist
import numpy as np
X = np.mat(np.random.randint(0,10,(4,3)))
dis = pdist(X,'euclidean')
print(dis)
样例输出:
[ 7.34846923 11.04536102 9.43398113 7.07106781 8.30662386 8.18535277]