Generate matrix A∈Rm∗n A ∈ R m ∗ n with m > n. Also generate some vector b∈Rm b ∈ R m .
Now find x=argminx||Ax−b||2 x = a r g m i n x | | A x − b | | 2 .
Print the norm of the residual.
分析:直接用scipy.linalg中的lstsq与norm函数即可,注意此时b要求是m*1的矩阵,因此要reshape一下。
import numpy as np
import scipy.linalg as la
m, n = 20, 10
A = np.random.randn(m, n)
b = np.random.randn(m).reshape(m, 1)
res = la.lstsq(A, b)
x = res[0]
print(x)
residual = la.norm(np.dot(A, x) - b, ord=2)
print(residual)
Find the maximum of the function
分析:注意这些最优化方法求的都是最小值,要求最大值就把函数计算的值取反
import numpy as np
import scipy.optimize as opt
def func(nums):
return (np.sin(nums - 2) ** 2) * (np.e ** (-nums ** 2))
func_inv = lambda x: -func(x)
res1 = opt.brute(func_inv, ((-5, 5),), full_output=1)
res2 = opt.fmin(func_inv, 0, full_output=1)
max1, max2 = -res1[1], -res2[1]
print(max1, max2)
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 dist
n, m = 6, 3
X = np.random.randint(5, 20, size=(n, m))
D = dist.cdist(X, X)
print(D)