Python-Scipy相关习题及解析

Scipy

Exercise 10.1: Least squares

Generate matrix ARm×n A ∈ R m × n with m>n m > n . Also generate some vector bRm b ∈ R m .
Now find x=argminxAxb2 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)

结果这里写图片描述


Exercise 10.2: Optimization

Find the maximum of the function

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

代码

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() 实现

结果

Python-Scipy相关习题及解析_第1张图片


Exercise 10.3: Pairwise distances

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))

结果

Python-Scipy相关习题及解析_第2张图片

结果中的第m行第n列表示:第m个点到第n个点的距离

你可能感兴趣的:(Python)