Exercise 10.1: Least squares Generate matrix A ∈ Rm×n with m > n. Also generate some vector b ∈ Rm. Now find x = argminxkAx−bk2. Print the norm of the residual.
import numpy as np
import scipy.linalg as li
m = 10
n = 20
A = np.random.rand(m, n)
b = np.random.rand(m, 1)
A = np.mat(A)
b = np.mat(b)
x = li.inv(A.T * A) * A.T * b
print(x)
Exercise 10.2: Optimization Find the maximum of the function
import numpy as np
import scipy.optimize as op
import math
def func(x):
return (-(math.sin(x-2)**2)*math.exp(-(x ** 2)))
a = op.fminbound(func, -10, 10)
print(-func(a))