第十八次作业

题目:




代码:

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]



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值