![](https://i-blog.csdnimg.cn/blog_migrate/5fb0022e89dd421c85b3370b2fd7f3c6.png)
其实这道题就是利用最小二乘法求x及其残差的范数,可以直接用函数scipy.linalg.lstsq()
返回的第一个值是x,第二个值是残差的范数
#10.1_Least squares
import numpy as np
import scipy.linalg
m = 30
n = 20
A = np.random.rand(m,n)
b = np.random.rand(m)
x, residues , rank, s = scipy.linalg.lstsq(A,b)
print(x)
print(residues)
![](https://i-blog.csdnimg.cn/blog_migrate/2bb604e339e7b14bcac7a2df362d9282.png)
这道题是求最大值,找到了scipy.optimize.fmin求最小值,所以函数里面加了一个负号
#10.2_ Optimization
import math
import scipy.optimize
def func(x):
return -(math.sin(x-2) * math.sin(x-2) * math.exp(-x**2))
maxi = scipy.optimize.fmin(func, 1)
print(maxi)
运行结果如下,所以最大值是0.911685
![](https://i-blog.csdnimg.cn/blog_migrate/5e6556b6288110dbe6790a79efbbddfb.png)
![](https://i-blog.csdnimg.cn/blog_migrate/b879ea18c23103b257b8e5b9ebfa7aba.png)
求两点间距离,矩阵的行数是点的个数,列数是点的维度利用
scipy.spatial.distance.pdist(X, 'euclidean')可以直接得到每两个点之间的距离
#10.3_Pairwise distances
import scipy.spatial.distance as dis
m = 12
n = 8
X = np.random.rand(m,n)
Y = dis.pdist(X, 'euclidean')
print(Y)