Exercise 10.1: Least squares
find
x=argmin||Ax−b||
x
=
a
r
g
m
i
n
|
|
A
x
−
b
|
|
and Print the norm of the residual.
代码
import numpy
import matplotlib.pyplot as plt
from scipy import linalg
def creat_A(row, col):
return numpy.random.random([row, col]);
def creat_b(row):
return numpy.random.random([row, 1]);
if __name__ == '__main__':
m = 15;
n = 10;
A=creat_A(m, n);
b = creat_b(m);
#x=numpy.array(linalg.lstsq(A, b))[0];
r=numpy.array(linalg.lstsq(A, b))[1]
#输出误差
print(r)
输出
[0.42044226]
Exercise 10.2: Optimization
Find the maximum of the function
代码
import numpy
import matplotlib.pyplot as plt
import scipy.optimize as optimize
def f(x):
return -(numpy.sin(x-2))**2 * numpy.exp(-x**2)
if __name__ == '__main__':
res = optimize.minimize(f, 0, method='nelder-mead',options={'xtol': 1e-8, 'disp': True})
输出
Optimization terminated successfully.
Current function value: -0.911685
Iterations: 33
Function evaluations: 66
Exercise 10.3: Pairwise distances
Let
X
X
<script type="math/tex" id="MathJax-Element-6">X</script> be a matrix with n rows and m columns. How can you compute the pairwise distances between
every two rows?
代码
import numpy as np
from scipy import linalg
from scipy import optimize
from scipy.spatial.distance import pdist
m=5
n=5
A=np.random.random([n, m])
max_dis = max(pdist(A));
print(max_dis)
输出
1.3005898911889262