Generate matrix A∈Rm×n A ∈ R m × n with m>n m > n . Also generate some vector b∈Rm b ∈ R m .
Now find x=argminx∥Ax−b∥2 x = arg min x ‖ A x − b ‖ 2 .
Print the norm of the residual.
import numpy as np
from scipy.optimize import leastsq
A = (np.random.random([20,10])-0.5)*2 #生成(20,10)的随机数矩阵,范围在(-1,1)
b = (np.random.random([20])-0.5)*4 #生成(20,)的随机数向量
initial = np.random.random([10]) #初始
#误差函数
def error(p,x,y):
return np.dot(x,p)-y
res = leastsq(error,initial,args=(A,b))[0]
norm = np.dot(A,res)-b
print(norm)
Find the maximum of the function
import numpy as np
from scipy.optimize import fmin
def f(x):
return -(np.sin(x-2)**2)*np.exp(-(x**2))
res = fmin(f,0)
print(res)
也可以用
scipy.optimize.brute()
实现
Let X X be a matrix with n n rows and m m columns. How can you compute the pairwise distances between every two rows?
As an example application, consider n 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
from scipy.spatial.distance import cdist
m = 5
n = 2
X = (np.random.random([m,n])-0.5)*10
print(X)
print(cdist(X,X))
结果中的第m行第n列表示:第m个点到第n个点的距离