import numpy as np
import scipy.spatial
import scipy.optimize
import math
#ex 10.1
print("#Exercise 10.1: Least squares")
A=np.random.normal(size=(3,2))
x=np.random.normal(size=(2,1))
b=np.dot(A,x)
print("A:",A)
print("b:",b)
print("True x:",x)
x1=np.dot(np.dot(np.linalg.inv(np.dot(A.T, A)), A.T), b)
print("Estimated x",x1)
print("residual norm:",np.linalg.norm(x1-x,2))
#ex 10.2
print("#Exercise 10.2: Optimization")
func = lambda x: -((math.sin(x-2))**2*math.exp(-x**2))
result=scipy.optimize.minimize_scalar(func,bounds=[0,2])
print("the maximum of the function:",-result.fun)
print("the x value is:",result.x)
#ex 10.3
print("#Exercise 10.3: Pairwise distances")
X=np.random.normal(size=(3,5))
print("X",X)
pairwise_dis=scipy.spatial.distance.pdist(X)
print("pairwise distances of X:",pairwise_dis)
运行结果:
#Exercise 10.1: Least squares
A: [[ 0.1887666 0.35927881]
[ 0.0905203 1.89474195]
[ 0.67870223 -2.25891406]]
b: [[-0.45153451]
[-0.5705992 ]
[-0.89358483]]
True x: [[-2.00077887]
[-0.20556261]]
Estimated x [[-2.00077887]
[-0.20556261]]
residual norm: 8.326672684688674e-17
#Exercise 10.2: Optimization
the maximum of the function: 0.9116854118471548
the x value is: 0.2162413285869684
#Exercise 10.3: Pairwise distances
X [[-0.35967317 -1.82759773 0.27892946 -1.62499491 -0.9192283 ]
[-1.47943739 -0.71917658 0.73090661 0.48700129 0.59099761]
[-1.21258195 -1.58022035 -1.30685922 0.18144239 0.26473742]]
pairwise distances of X: [3.07051509 2.82282929 2.27264377]
[Finished in 0.3s]