高级编程技术作业_18 scipy练习题

这篇博客展示了如何利用scipy库解决三个高级编程技术问题:1) 最小二乘法求解Ax-b的最优解并计算残差范数;2) 优化问题中最大化目标函数的示例;3) 计算矩阵中每对行之间的欧氏距离。通过代码实现,强调了scipy的功能应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Exercise 10.1: Least squares

Generate matrix A 2 Rmn with m > n. Also generate some vector b 2 Rm.
Now nd x = arg minx kAx �� bk2.
Print the norm of the residual.

代码展示

import numpy as np
from scipy import linalg

m = 6
n = 5
A = np.mat(np.random.rand(m,n))
b = np.mat(np.random.rand(m,1))

x = linalg.lstsq(A,b)[0]

norm = linalg.norm(A.dot(x)-b, ord=2)

print("A=",A)
print("\nb=",b)
print("\nsolution=",x)
print("\nnorm=",norm)

运行结果
A= [[0.7224207 0.36410643 0.45697718 0.2742294 0.49262217]
[0.33141127 0.07697228 0.86524478 0.5532029 0.97940514]
[0.38922893 0.56453673 0.77706287 0.0448745 0.36353075]
[0.59885064 0.3126778 0.57036671 0.40783491 0.59128013]
[0.09054347 0.74915138 0.65523353 0.82922898 0.65026449]
[0.14499319 0.10757928 0.92837588 0.1238894 0.61040316]]

b= [[0.15459247]
[0.25208535]
[0.46024235]
[0.14527383]
[0.47331631]
[0.0995887 ]]

solution= [[-0.67976103]
[ 1.53524102]
[-1.21838531]
[-1.5626144 ]
[ 2.29837656]]

norm= 0.10137353709297185

Exercise 10.2: Optimization

代码展示

import numpy as np
from scipy import linalg

m = 6
n = 5
A = np.mat(np.random.rand(m,n))
b = np.mat(np.random.rand(m,1))

x = linalg.lstsq(A,b)[0]

norm = linalg.norm(A.dot(x)-b, ord=2)

print("A=",A)
print("\nb=",b)
print("\nsolution=",x)
print("\nnorm=",norm)

运行结果

X= 0.21624122114794078
Maximize: -0.9116854118471323

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.

代码展示

import numpy as np
from scipy.spatial import distance

m = 5
n = 4
x = np.random.rand(m,n)
y = distance.pdist(x)
z = distance.squareform(y)
print("distance=",z)

运行结果
distance= [[0. 0.99544534 0.69025783 0.43715256 1.1468476 ]
[0.99544534 0. 0.88091227 1.04215157 0.71381617]
[0.69025783 0.88091227 0. 0.66632103 0.6734988 ]
[0.43715256 1.04215157 0.66632103 0. 0.95983582]
[1.1468476 0.71381617 0.6734988 0.95983582 0. ]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值