题目:
代码:
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.71295719 -0.22372115]
[-0.52395625 -0.11005857]
[ 0.30022309 -2.12489615]]
b: [[-0.78927766]
[-0.52799398]
[-1.79264937]]
True x: [[ 0.80655984]
[ 0.95759845]]
Estimated x [[ 0.80655984]
[ 0.95759845]]
residual norm: 2.22044604925e-16
#Exercise 10.2: Optimization
the maximum of the function: 0.9116854118471548
the x value is: 0.216241328587
#Exercise 10.3: Pairwise distances
X [[-1.41494497 -0.94018276 -0.5963188 -1.05400167 -0.24725318]
[-1.98642478 0.31075111 -0.6268892 1.22340041 -0.23211028]
[ 1.60339519 0.78625578 -2.56692033 1.3082986 1.58916266]]
pairwise distances of X: [ 2.66066699 4.99270703 4.49453844]