高级编程技术(Python)作业15

Exercises for Scipy
Exercise 10.1
Solution:

import numpy as np
import scipy.linalg

m = 10
n = 5

A = np.random.standard_normal((m, n))
b = np.random.standard_normal((m, 1))
x = scipy.linalg.lstsq(A, b)[0]
norm_residual = scipy.linalg.norm(b - A @ x)

print("norm of the residual is ", norm_residual)

Output:

norm of the residual is  0.8638181831376697

注释:
注意要import scipy.linalg而不是只import scipy。
Exercise 10.2
Solution:

import scipy.optimize as opt
import numpy as np


def func(x):
    return -np.power(np.sin(x-2), 2) * np.power(np.e, -np.power(x, 2))


maximum = opt.fmin(func, 1, full_output=True)
print('f(%f) = %f' % (maximum[0], -maximum[1]))

Output:

Optimization terminated successfully.
         Current function value: -0.911685
         Iterations: 16
         Function evaluations: 32
f(0.216211) = 0.911685

注释:
scipy之中并没有求最大值的函数,只有求最小值的函数,我们需要将函数取反,求出最小值之后,再把结果取反输出出来。

Exercise 10.3
Solution:

import numpy as np
import scipy.spatial as spa

m = 5
n = 5
X = np.random.randint(10, size=(m, n))
print("X with %d rows and %d columns: \n" % (n, m), X)
dis = spa.distance.pdist(X)
length = len(dis)

for i in range(length, 0, -1):
    temp = []
    if i == length:
        for j in range(0, length):
            if j != i - 1:
                temp.append(round(dis[j], 2))
        temp.insert(length-i, 0)
        nice_table = np.mat([temp])
    else:
        for j in range(0, length):
            if j != i - 1:
                temp.append(round(dis[j], 2))
        temp.insert(length-i, 0)
        temp = np.array(temp)
        nice_table = np.row_stack((nice_table, temp))

print("\npairwise distance table: \n", nice_table)

Output:

X with 5 rows and 5 columns: 
 [[8 7 0 0 0]
 [0 0 9 9 2]
 [6 0 2 7 3]
 [1 4 0 3 2]
 [5 7 2 9 3]]

pairwise distance table: 
 [[ 0.   16.7  10.72  8.43 10.15  9.49 11.58 11.14  7.87  7.35]
 [16.7   0.   10.72  8.43 10.15  9.49 11.58 11.14  7.87  8.12]
 [16.7  10.72  0.    8.43 10.15  9.49 11.58 11.14  7.35  8.12]
 [16.7  10.72  8.43  0.   10.15  9.49 11.58  7.87  7.35  8.12]
 [16.7  10.72  8.43 10.15  0.    9.49 11.14  7.87  7.35  8.12]
 [16.7  10.72  8.43 10.15 11.58  0.   11.14  7.87  7.35  8.12]
 [16.7  10.72  8.43  9.49 11.58 11.14  0.    7.87  7.35  8.12]
 [16.7  10.72 10.15  9.49 11.58 11.14  7.87  0.    7.35  8.12]
 [16.7   8.43 10.15  9.49 11.58 11.14  7.87  7.35  0.    8.12]
 [10.72  8.43 10.15  9.49 11.58 11.14  7.87  7.35  8.12  0.  ]]

注释:
此题目的按照题目的意思形象化的话,每一行都相当于每个城市的坐标,这个坐标是m维的,总共有n个城市,于是X就是n行m列的矩阵。
然后使用scipy.spatial.distance.pdist()求出每两个城市之间的欧氏距离(即每两行的2范数),输出为一个按顺序输出每两个点距离的列表。
最后我们再对这个列表做相关操作,处理成题目要求的nice table。

猜你喜欢

转载自blog.csdn.net/weixin_38311046/article/details/80570890