from scipy import optimize as soe
import math
deffunc(x):"""
-f(x)=-sin^2(x-2)e^(-x^2)
"""return -math.pow(math.sin(x[0]-2), 2)*math.exp(-math.pow(x[0], 2))
x0 = [0]
minimizer_kwargs = {"method": "BFGS"}
ret = soe.basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs,
niter=200)
print("global maximum: x = %.4f, f(x0) = %.4f" % (ret.x, -ret.fun))
结果:
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.
方法:利用函数pdist
import scipy.spatial.distance as ssdis
import numpy.matlib as npm
X = npm.rand((6, 6))
print('matrix X:')
print(X)
print("matrix X's Pairwise distances:")
print(ssdis.pdist(X, 'euclidean'))