scipy练习
Exercise 10.1: Least squares
Generate matrix A∈Rm×n A ∈ R m × n with m>n m > n . Also generate some vector b∈Rm b ∈ R m . Now find x=argminx∥Ax=b∥2 x = arg min x ‖ A x = b ‖ 2 . Print the norm of the residual.
import numpy
import scipy.linalg
m, n = 200, 100
A = numpy.random.randint(low=0, high=100, size=(m, n)) + numpy.random.rand(m, n)
b = numpy.random.randint(low=0, high=100, size=(m, 1)) + numpy.random.rand(m, 1)
x_hat = scipy.linalg.lstsq(A, b)[0]
residual = numpy.dot(A, x_hat) - b
print(numpy.linalg.norm(residual, ord=2))
Exercise 10.2: Optimization
Find the maximum of the function
>>f(x)=sin2(x−2)e−x2>> >> f ( x ) = sin 2 ( x − 2 ) e − x 2 >>
import math
import numpy
from scipy import optimize
from matplotlib import pyplot
def f(x):
return numpy.power(numpy.sin(x-2), 2) * numpy.power(math.e, -numpy.power(x, 2))
x = numpy.arange(-2.5, 2.5, 0.01)
y = f(x)
pyplot.plot(x, y)
max_x = optimize.minimize_scalar(lambda x: -f(x)).x
pyplot.scatter(max_x, f(max_x))
pyplot.text(max_x, f(max_x), (max_x, f(max_x)), ha='center')
pyplot.show()
Exercise 10.3: Pairwise distances
Let X X be a matrix with rows and m m columns. How can you compute the pairwise distances between every two rows?
As an example application, consider 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 scipy.spatial
import numpy
m, n = 3, 2
X = numpy.random.randint(low=0, high=10, size=(m, n))
print(X)
distances = scipy.spatial.distance_matrix(X, X)
print(distances)