import scipy.linalg as lina
import numpy as np
m = 10
n = 6
A = np.random.random_sample((m, n))
x = np.random.random_sample((n,))
b = A.dot(x) + np.random.normal(0, 1, (m,))
x_ = lina.inv(A.T.dot(A)).dot(A.T).dot(b)
print(lina.norm(A.dot(x_) - b))
结果:
2.7711555872938862
[Finished in 3.8s]
import scipy.optimize as so
from math import sin, exp
def f(x):
return -(sin(x - 2) ** 2) * exp(-(x ** 2))
a = so.fminbound(f, 0, 1)
print("the max of f(x) = ", -f(a),"when x = ", a)
结果:
the max of f(x) = 0.9116854118471066 when x = 0.216241170568
[Finished in 1.8s]
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 nn 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 numpy as np
import scipy.spatial.distance as dis
m = 10
n = 6
X = np.random.rand(m, n)
Y = dis.pdist(X)
z = dis.squareform(Y)
print(z)
结果:
[[ 0. 1.06563785 0.8991295 1.11523718 0.68486272 0.84821488
0.69147257 0.76578426 0.84108407 0.97179401]
[ 1.06563785 0. 1.05035582 1.25618603 1.13114483 0.95785648
0.84361886 1.15080478 0.79948917 0.67902661]
[ 0.8991295 1.05035582 0. 0.85992237 1.3830768 1.26597884
1.23922916 1.26570587 1.10687948 1.257172 ]
[ 1.11523718 1.25618603 0.85992237 0. 1.37042936 1.62495922
1.20311556 1.2376298 1.17202273 1.45872162]
[ 0.68486272 1.13114483 1.3830768 1.37042936 0. 0.79638965
0.80060998 0.90885248 0.75235086 1.00716696]
[ 0.84821488 0.95785648 1.26597884 1.62495922 0.79638965 0.
0.95381021 1.0311819 0.63747946 0.86866474]
[ 0.69147257 0.84361886 1.23922916 1.20311556 0.80060998 0.95381021
0. 0.67373532 0.76295439 0.78899356]
[ 0.76578426 1.15080478 1.26570587 1.2376298 0.90885248 1.0311819
0.67373532 0. 0.97081342 0.74455982]
[ 0.84108407 0.79948917 1.10687948 1.17202273 0.75235086 0.63747946
0.76295439 0.97081342 0. 0.97669933]
[ 0.97179401 0.67902661 1.257172 1.45872162 1.00716696 0.86866474
0.78899356 0.74455982 0.97669933 0. ]]
[Finished in 1.6s]