第十三周作业

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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值