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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容