hw13(第十三周)

Scipy相关练习

Exercise 10.1: Least squares Generate matrix A ∈ Rm×n with m > n. Also generate some vector b ∈ Rm. Now find x = arg(min xk)||Ax−bk||2. Print the norm of the residual.
Exercise 10.2: Optimization Find the maximum of the function
f(x) = (sin(x−2))^2 * e^(−x^(2))
Exercise 10.3: Pairwise distances Let X be a matrix with n rows and m columns. How can you compute the pairwise distances between every 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.


10.1的目的是已知矩阵A和向量b,使用最小二乘法求向量x,并求出残差的模。
10.2的目的是求f(x) = (sin(x−2))^2 * e^(−x^(2))的最大值。
10.3的目的是计算n个点中每两个点之间的距离。(使用Scipy中的函数)


效果:

10.1
A = [[3.29970122 4.7584198 0.11994548]
[1.10806457 4.11875492 7.82262271]
[4.11149242 2.98016391 1.85985557]
[0.10009004 7.7156862 6.02579851]
[0.55049201 3.73704831 7.01933204]]
b = [3.09298837 1.93370244 1.70862393 3.42058839 0.3262391 ]
x = [ 0.11220267 0.56255373 -0.15490991]
Norm of residual = 0.3610278285377418
10.2
max func(0.216211) = 0.911685
iterations = 16, function evaluations = 32
10.3
[[0.68474557 6.35072199]
[0.57396044 6.34347976]
[2.44547344 4.21650739]
[5.85283499 1.59502687]]
[0.11102161 2.76677332 7.02323176 2.83312062 7.10030432 4.2991014 ]


代码:

import scipy
import scipy.linalg
import scipy.spatial
import scipy.optimize as opt
import math

def ex10_1():
    print('10.1')
    m = 5
    n = 3
    A = scipy.random.rand(m, n) * scipy.random.randint(1, 10)
    b = scipy.random.rand(m) * scipy.random.randint(1, 10)
    x, resid, rnk, s = scipy.linalg.lstsq(A, b)
    print('A =', A)
    print('b =', b)
    print('x =', x)
    print('Norm of residual =', resid/n)

def ex10_2():
    print('10.2')
    func = lambda x: (math.sin(x - 2) ** 2) * math.exp(-x * x)
    maximum = opt.fmin(lambda x: -func(x), 1, full_output=True, disp=0)
    print('max func(%f) = %f'%(maximum[0], -maximum[1]))
    print('iterations = %d, function evaluations = %d'%(maximum[2], maximum[3]))

def ex10_3():
    print('10.3')
    m = 2
    n = 4
    X = scipy.random.rand(n, m) * scipy.random.randint(1, 10)
    print(X)
    Y = scipy.spatial.distance.pdist(X)
    print(Y)

ex10_1()
ex10_2()
ex10_3()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值