Scipy

Scipy Homework

Exercise 10.1: Least squares

Generate matrix $A \in R^{m \times n}$ with m > n. Also generate some vector $b \in R^m$ Now find $x=\arg \min_x||Ax - b||_2$ Print the norm of the residual.

from scipy.optimize import least_squares
import numpy as np 
M = 30
N = 20
SCALE = 10
A = SCALE * np.random.random((M, N))
b = SCALE * np.random.random(M)
b.shape = (M, )
def costFunction(x):
    return A.dot(x) - b

res = least_squares(costFunction, np.random.random(N))

print(res.cost)

这里使用了scipy.optimize.least_squares最小二乘法工具。 第一个参数是一个函数,返回一个1-D np.arrayleast_squres会对该数组自动计算二模,并通过迭代的方法求其最小值。
第二个参数是初始值。这里采用随机的方法设定。

Exercise 10.2: Optimization

Find the maximum of the function $f(x) = \sin^2(x-2)e^{-x}$

from scipy.optimize import fmin
from math import sin,exp
def f(x):
    return sin(x-2)**2 * exp(-x**2)

max_x = fmin(lambda x:-f(x), 0)
print(f(max_x))

使用scipy.optimize.fmin函数来求全局最大值。

由于fmin会求出函数的最小值,故使用lambda x : -f(x)来取得最大值。

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.

from scipy.spatial import distance
import numpy as np
N = 20
M = 3
SCALE = 10
coords = SCALE * np.random.random((N, M))
print(coords)
m = distance.cdist(coords, coords, 'euclidean')
print(m)

使用scipy.spatial.distance.cdist完成上述功能。

cdist对输入的第一个参数和第二个参数,计算他们两两之间的距离。
第三个参数是一个字符串,表示以何种方式定义距离。

这里的euclidean表示使用欧几里得距离,即通常二模。