Exercise 10.1: Least squares
Generate matrix A 2 Rmn with m > n. Also generate some vector b 2 Rm.
Now nd x = arg minx kAx �� bk2.
Print the norm of the residual.
代码展示
import numpy as np
from scipy import linalg
m = 6
n = 5
A = np.mat(np.random.rand(m,n))
b = np.mat(np.random.rand(m,1))
x = linalg.lstsq(A,b)[0]
norm = linalg.norm(A.dot(x)-b, ord=2)
print("A=",A)
print("\nb=",b)
print("\nsolution=",x)
print("\nnorm=",norm)
运行结果
A= [[0.7224207 0.36410643 0.45697718 0.2742294 0.49262217]
[0.33141127 0.07697228 0.86524478 0.5532029 0.97940514]
[0.38922893 0.56453673 0.77706287 0.0448745 0.36353075]
[0.59885064 0.3126778 0.57036671 0.40783491 0.59128013]
[0.09054347 0.74915138 0.65523353 0.82922898 0.65026449]
[0.14499319 0.10757928 0.92837588 0.1238894 0.61040316]]
b= [[0.15459247]
[0.25208535]
[0.46024235]
[0.14527383]
[0.47331631]
[0.0995887 ]]
solution= [[-0.67976103]
[ 1.53524102]
[-1.21838531]
[-1.5626144 ]
[ 2.29837656]]
norm= 0.10137353709297185
Exercise 10.2: Optimization
代码展示
import numpy as np
from scipy import linalg
m = 6
n = 5
A = np.mat(np.random.rand(m,n))
b = np.mat(np.random.rand(m,1))
x = linalg.lstsq(A,b)[0]
norm = linalg.norm(A.dot(x)-b, ord=2)
print("A=",A)
print("\nb=",b)
print("\nsolution=",x)
print("\nnorm=",norm)
运行结果
X= 0.21624122114794078
Maximize: -0.9116854118471323
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
from scipy.spatial import distance
m = 5
n = 4
x = np.random.rand(m,n)
y = distance.pdist(x)
z = distance.squareform(y)
print("distance=",z)
运行结果
distance= [[0. 0.99544534 0.69025783 0.43715256 1.1468476 ]
[0.99544534 0. 0.88091227 1.04215157 0.71381617]
[0.69025783 0.88091227 0. 0.66632103 0.6734988 ]
[0.43715256 1.04215157 0.66632103 0. 0.95983582]
[1.1468476 0.71381617 0.6734988 0.95983582 0. ]]