Exercise 10.1: Least squares
Generate matrix A ∈ Rm×n with m > n. Also generate some vector b ∈ Rm.
Now find x = arg minx ||Ax − b||2.
Print the norm of the residual
用numpy里的random的rand和mat生成矩阵,最后用最小二乘法和乘法函数dot和取逆函数inv算出x。
from numpy import *
from scipy.linalg import *
from scipy.stats import *
import math
m,n=0,1
while(n>m):
m=int(input("Input m "))
n=int(input("Input n "))
if(n>m):
print("Invalid input,input m,n again")
A=mat(random.rand(m,n))
b=mat(random.rand(m,1))
x=dot(dot(inv(dot(A.T,A)),A.T),b)
print(x)
Exercise 10.2: Optimization
Find the maximum of the function
f(x) = sin^2(x − 2)e^(−x^2)
由于只知道最小值的函数,要先对函数取反,再用scipy.optimize里的fmin找到最小值对应的x值,最后把x对应的函数值求出来再取反就是答案。
from numpy import *
from scipy.linalg import *
import scipy.optimize as opt
from scipy.stats import *
import math
def liangjan(x):
return -((math.sin(x-2)**2)*math.exp(-(x**2)))
x=opt.fmin(liangjan,1)
print("Maximum is : ",liangjan(x)*-1)
最后算出来的最大值是 0.9116854101234255
Exercise 10.3: Pairwise distances
Let X be a matrix with n rows and m columns. How can you compute the pairwise distances betweenevery two rows?As an example application, consider n cities, and we are given their coordinates in two columns. Nowwe 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.
用scipy.spatial.distance里的pdist算距离,再用squareform转成矩阵形式的距离打印出来。
from numpy import *
from scipy.linalg import *
from scipy.spatial.distance import *
from scipy.stats import *
import math
m=int(input("Input m "))
n=int(input("Input n "))
X=mat(random.rand(m,n))
cities=pdist(X)
ans=squareform(cities)
print(ans)