Scipy练习(5.30作业)

Ex 10-1
# Ex 10-1
import numpy as np
m = 5
n = 4
A = np.random.rand(m, n)
b = np.random.rand(m, 1)
np.dot(A.T, A)
# Find least square of Ax = b
# Solve ATAx = ATb
x = np.linalg.solve(np.dot(A.T, A), A.T.dot(b))
print(np.linalg.norm(A.dot(x) - b, 2))  # Print the norm of the residual



Ex 10-2

Finding maximum of f(x) is equivalent to finding the minimum of -f(x).
scipy.optimize.fmin can be used.

# Ex 10-2
import numpy as np
from scipy import optimize
max_value = optimize.fmin(lambda x: -np.sin(x - 2) ** 2 * np.exp(-x ** 2), 0)
print(max_value[0])

Here's output:

Optimization terminated successfully.
         Current function value: -0.911685
         Iterations: 20
         Function evaluations: 40
0.21625000000000016



Ex 10-3

scipy.spatial.distance.pdist is a great function.

# Ex 10-3
import numpy as np
from scipy.spatial.distance import pdist
#Generate a random matrix with n = 5 rows, m = 3 columns
A = np.random.randint(low = 0, high = 10, size= (5, 3))
print(A)
dist = pdist(A)
print(dist)

你可能感兴趣的:(Scipy练习(5.30作业))