scipy练习
10.1
Exercise 10.1: Least squares Generate matrix A ∈ Rm×n with m > n.
Also generate some vector b ∈ Rm.
Now find x = argminxkAx−bk2.
Print the norm of the residual.
from scipy.linalg import toeplitz
from scipy.optimize import minimize
from scipy.spatial.distance import *
import numpy as np
import scipy.stats
m = 20
n = 10
#----------------------------------------
#question 1
#----------------------------------------
A = np.random.random(size = (m,n))
b = np.random.random(size = (m,1))
print(A)
print(b)
x = np.array(np.linalg.lstsq(A,b,rcond = -1)[0])
print(x)
10.2
Exercise 10.2: Optimization Find the maximum of the function
f(x) = sin2(x−2)e−x2
from scipy.linalg import toeplitz
from scipy.optimize import minimize
from scipy.spatial.distance import *
import numpy as np
import scipy.stats
m = 20
n = 10
#----------------------------------------
#question 2
#----------------------------------------
def ex(x):
return (-1)*np.sin(x-2)**2*np.exp((0-1)*x**2) #求最大值 利用minimize 加负号
print((-1)*minimize(ex,0).fun)
10.3
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.
from scipy.linalg import toeplitz
from scipy.optimize import minimize
from scipy.spatial.distance import *
import numpy as np
import scipy.stats
m = 20
n = 10
#----------------------------------------
#question 3
#----------------------------------------
x = np.random.random(size = (n,m))
print(pdist(x))
m = np.random.random(size = (n,2))
print(pdist(m))