第十三周作业(scipy)

 Exercise 10.1: Least squares

代码

import numpy as np 
from scipy import optimize as op

m=10
n=8

A=2.5*np.random.randn(m,n)+3
b=1.5*np.random.randn(m)+4

x=op.lsq_linear(A,b)
result=np.linalg.norm(x.fun)
print(result)

输出



 Exercise 10.2: Optimization

 首先分析题目函数,其应该会在x=0的附近收敛,因此初始估计点为x=0

代码

import numpy as np 
from scipy import optimize as op
from scipy.spatial import distance as dist

fun=lambda x :(-1)*(np.sin(x-2))**2 * np.exp((-1)*(x**2))
X=op.fmin(fun,0)
print("the maximum of the function:")
print((-1)*fun(X[0]))

输出

第十三周作业(scipy)_第1张图片


 Exercise 10.3: Pairwise distances

代码

import numpy as np 
from scipy import optimize as op
from scipy.spatial import distance as dist

#输入实例并计算结果
X=np.array([[3,4],[5,6],[1,9]])
Y=dist.pdist(X)
m=X.shape[0]
I=np.zeros(((m,m)))

#将计算结果转换为矩阵形式显示,元素 Iij 表示矩阵X中第i行和第j行的距离
counter=0
for y in Y:
    a=counter//(m-1)
    b=counter%(m-1)+a+1
    I[a][b]=y
    I[b][a]=y
    counter=counter+1

print(I)

输出





你可能感兴趣的:(第十三周作业(scipy))