Python-Scipy相关习题及解析

Scipy

Exercise 10.1: Least squares

Generate matrix A R m × n with m > n . Also generate some vector b R m .
Now find 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 ) = 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() 实现

结果

这里写图片描述


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.

代码

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个点的距离

猜你喜欢

转载自blog.csdn.net/james_154_best/article/details/80548110