Exercise 10.1: Least squares
description:
solution:
import numpy as np
m = 20
n = 10
A = np.random.randint(10, 20, (m, n))
b = np.random.randint(10, 20, (m, 1))
x = np.linalg.lstsq(A, b, rcond=None)[0]
print(x)
E = np.dot(A, x) - b
print(np.linalg.norm(E))
————————————————————————————————————————
Exercise 10.2: Optimization
description:
solution:
因为f(x)恒大于0,这里先找到-f(x)的最小值,即找到f(x)的最大值。
import math
from scipy.optimize import minimize_scalar
def f(x):
return -1 * (math.sin(x - 2) ** 2) * (math.e ** (-x * x))
solution = minimize_scalar(f)
print('x:', solution.x)
print('maximum of f(x):', -1 * f(solution.x))
————————————————————————————————————————
Exercise 10.3: Pairwise distances
description:
solution:
import numpy as np
from scipy.spatial.distance import pdist
m = 5
n = 10
x = np.random.randint(0, 10, (n, m))
print(x)
print(pdist(x, 'euclidean'))