Exercise 10.1: Least squares
from scipy import linalg, stats
import numpy as np
import math
import matplotlib.pyplot as plt
m = 20
n = 11
A = np.random.randint(-10, 10, size = (m, n))
b = np.random.randint(-5, 5, size = (m, 1))
x = np.dot(np.dot(linalg.inv(np.dot(A.T, A)), A.T), b)
print(linalg.norm(np.dot(A, x)-b, 2))
结果:
6.418629550140691
Exercise 10.2: Optimization
f = lambda x: -np.sin(x-2)**2*np.exp(-x**2)
xMin = scipy.optimize.fmin(f, 1)[0]
print(-f(xMin))
# Draw the figure
xRange = np.linspace(-10, 10.1, 200)
plt.plot(xRange, -f(xRange), 'r-')
plt.plot([xMin, xMin], [0, 1], 'b-')
plt.show()
结果:
0.9116854101234255
Exercise 10.3: Pairwise distances
from scipy.spatial.distance import pdist
import numpy as np
import matplotlib.pyplot as plt
n = 30
m = 20
x = np.random.randint(-10, 10, size = (n, m))
y = pdist(x, 'euclidean')
print(y.shape)
print(y)
结果:
[[406878857]
[9061638936]
[4123109733]
[3017536442]
[3457689274]
[98785395]
[45487182]
[4691422140]
[701032119]
[804693202]]
[[0.60.2577795886.4291617570.6540869369.24593851
144.05901568110.5124427483.94045509116.5332570680.98765338]
[60.257779580.82.0182906479.3536388668.04410334
103.8364098113.6221809388.97752525109.5216873584.5103544]
[86.4291617582.018290640.56.3560112179.21489759
96.3794583973.55949973107.22872749104.43179592125.81335382]
[70.6540869379.3536388656.356011210.60.40695324
98.3819089175.6240702487.7838253981.1664955592.07062507]
[69.2459385168.0441033479.2148975960.406953240.
110.2633211970.8096038790.4046459126.91335627115.02173708]
[144.05901568103.836409896.3794583998.38190891110.26332119
0.107.41508274122.3315167999.24212815137.1422619]
[110.51244274113.6221809373.5594997375.6240702470.80960387
107.415082740.92.48243076125.44720005148.54628908]
[83.9404550988.97752525107.2287274987.7838253990.4046459
122.3315167992.482430760.89.8776946785.01176389]
[116.53325706109.52168735104.4317959281.16649555126.91335627
99.24212815125.4472000589.877694670.75.94076639]
[80.9876533884.5103544125.8133538292.07062507115.02173708
137.1422619148.5462890885.0117638975.940766390.]]