Exercise 10.1: Least squares
Generate matrix A 2 R m × n with m > n . Also generate some vector b 2 R m .Now find x = arg minx ||Ax - b||. Print the norm of the residual.
import numpy as np
from scipy.linalg import norm,lstsq
m=30
n=20
A = np.random.randint(0,100,size=(m,n))
b = np.random.randint(0,100,size=(m,1))
#lstsq(a, b)返回的结果包括所求系数列向量t,残差,矩阵a的秩与奇异值
x,res, rnk, s= lstsq(A, b) #最小二乘法求系数
bb= norm(b-np.dot(A,x),ord=2)
print("A:")
print(A)
print("b:")
print(b)
print("bb:")
print(bb)
Result:
Exercise 10.2: Optimization
Find the maximum of the function
def func():
import math
import numpy as np
from scipy import optimize
func=lambda x:-1*(np.sin(x-2)*np.sin(x-2)*np.exp((-1)*(x*x)))
a=optimize.minimize_scalar(func)
#print(a.fun)
print("The maximum is "+str(abs(a.fun)))
func()
Result:
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. 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.distance import cdist
import math
m=5
n=5
XA = np.random.rand(m, n)
XB = np.random.rand(m, n)
result=cdist(XA, XB, metric="euclidean", p=2, V=None, VI=None, w=None)
print(result)
Result: