第13周作业 #高级编程技术

scipy


Exercise 10.1: Least squares

Generate matrix A ∈ Rm×n with m > n. Also generate some vector b ∈ Rm. Now find x = argmin x ||Ax−b||2. Print the norm of the residual.

import numpy as np
import scipy.optimize as opt

A = np.random.rand(10, 5)
b = np.random.rand(10, 1)

def func(p, A, b):
    x = p.reshape(5, 1)
    return (np.dot(A, x) - b).reshape(-1)

p0 = np.random.rand(5, 1)
p0 = [p0]
res = opt.leastsq(func, p0, (A, b))
norm = np.linalg.norm(func(res[0], A, b))
print(res[0])
print(norm)

运行结果:

[ 0.59510766  0.09119742  0.48249284  0.67933586 -0.5243152 ]
0.33809584697476897



Exercise 10.2: Optimization

Find the maximum of the function

sin2(x2)ex2 sin 2 ⁡ ( x − 2 ) e − x 2

import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt

def f(x):
    return - np.sin(x) ** 2 * np.e ** ( - x ** 2)

res = opt.minimize_scalar(f)
print(res)

x = np.linspace(-5, 5, 1000)
y = -f(x)

plt.figure()
plt.plot(x, y, 'r')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('f(x) = sin²(x−2)e^(−x²)')
plt.show()

运行结果:

     fun: -0.2741283295576515
    nfev: 14
     nit: 10
 success: True
       x: 0.8603335912423467

Figure


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.

import numpy as np
import scipy.spatial.distance as dis

A = np.random.randint(0, 10, (5, 2))

res = dis.pdist(A)
print(A)
print(res)
print(dis.squareform(res))      # 向量形式的距离转换为矩阵形式

运行结果:

[[3 4]
 [2 2]
 [0 4]
 [7 4]
 [7 9]]
[2.23606798 3.         4.         6.40312424 2.82842712 5.38516481
 8.60232527 7.         8.60232527 5.        ]
[[0.         2.23606798 3.         4.         6.40312424]
 [2.23606798 0.         2.82842712 5.38516481 8.60232527]
 [3.         2.82842712 0.         7.         8.60232527]
 [4.         5.38516481 7.         0.         5.        ]
 [6.40312424 8.60232527 8.60232527 5.         0.        ]]



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值