import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
# 10-1 reference: https://docs.scipy.org/doc/scipy-1.1.0/reference/tutorial/linalg.html
from scipy.linalg import lstsq
m = 10
n = 5
A = np.random.randint(10, size=(m ,n))
b = np.random.randint(10, size=m)
x, residual, rank, s = lstsq(A, b)
print('A =', A)
print('x =', x)
print('A*x =', A.dot(x))
print('b =', b)
print('residual =', residual)
A = [[7 0 6 0 5]
[8 1 7 0 1]
[7 0 5 3 0]
[0 6 3 9 6]
[6 2 2 3 7]
[6 4 9 0 4]
[8 7 0 1 3]
[0 2 1 8 6]
[8 0 9 6 1]
[7 3 0 4 7]]
x = [-0.21398376 -0.22535051 0.54616875 0.08852853 0.55954735]
A*x = [ 4.57686293 2.44550802 1.49854304 4.44044405 3.54015095 4.96840354
-1.52215309 4.16098006 4.29436723 2.0970077 ]
b = [9 3 2 5 0 3 0 6 3 1]
residual = 45.42120287262695
# 10-2 reference: https://docs.scipy.org/doc/scipy-1.1.0/reference/generated/scipy.optimize.minimize_scalar.html#scipy.optimize.minimize_scalar
from scipy.optimize import minimize_scalar
def f(x):
return np.sin(x-2)**2 * np.exp(-x**2)
x_max = minimize_scalar(lambda x: -f(x)).x
print('x_max = ', x_max)
x = np.arange(0, 2, 0.001)
plt.plot(x, f(x), 'b-', label='$\sin^2(x-2)e^{-x^2}$')
plt.plot(x_max, f(x_max), 'ro', label='x_max')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.show()
x_max = 0.21624132858697098
# 10-3 reference: https://docs.scipy.org/doc/scipy-1.1.0/reference/spatial.distance.html
from scipy.spatial.distance import pdist, squareform
n = 6
m = 2
X = np.random.randint(10, size=(n, m))
print(X)
print(squareform(pdist(X)))
[[9 9]
[5 7]
[6 6]
[0 9]
[8 1]
[6 9]]
[[ 0. 4.47213595 4.24264069 9. 8.06225775 3. ]
[ 4.47213595 0. 1.41421356 5.38516481 6.70820393 2.23606798]
[ 4.24264069 1.41421356 0. 6.70820393 5.38516481 3. ]
[ 9. 5.38516481 6.70820393 0. 11.3137085 6. ]
[ 8.06225775 6.70820393 5.38516481 11.3137085 0. 8.24621125]
[ 3. 2.23606798 3. 6. 8.24621125 0. ]]