scipy作业



第一题主要考察最小二乘法的使用


Exercise 10.2: Optimization
Find the maximum of the function
f(x) = sin2(x - 2)e-x2 

第二题主要考察求函数最值的方法


Exercise 10.3: Pairwise distances
Let X be a matrix with n rows and m columns. How can you compute the pairwise distances between
every two rows?
As an example application, consider
n cities, and we are given their coordinates in two columns. Now
we want a nice table that tells us for each two cities, how far they are apart.
Again, make sure you make use of Scipy’s functionality instead of writing your own routine.
 

第三题主要考察pdist函数的使用


代码:

import numpy as np
import scipy.linalg as sl
import scipy.optimize as so
import scipy.spatial.distance as ssd
import math

print('10.1')
# 10.1
m = 6
n = 4
A = np.random.rand(m, n)
b = np.random.rand(m, 1)
# 最小二乘法
x, residues, rank, s = sl.lstsq(A, b)
print('x:\n', x)
print('norm of the residual:\n', sl.norm(residues))


print('\n10.2')
# 10.2


def f(x):
    return -(math.sin(x - 2)**2) * (math.exp(-x * x))
# 没有求最大值的函数,刚好这个函数为正,所以求这个函数的相反数的最小值再取反就是最大值


res = so.fmin(f, 0.25, full_output=True)
print('MAX:', -res[1])


print('\n10.3')
# 10.3
n = 5
m = 3
X = np.random.rand(n, m)
Y = ssd.pdist(X)
print('pairwise distance')
print(Y)

运行结果:


猜你喜欢

转载自blog.csdn.net/qq_36325159/article/details/80551300