第十三周python作业:Scipy练习

本文通过三个实例展示了如何使用Python及Scipy库进行最小二乘法求解过拟合问题、寻找函数最大值以及计算矩阵中各行列间的欧氏距离。这些示例涵盖了从数据生成到结果解释的完整过程。

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

Exercise 10.1: Least squares

Generate matrix A Rm×n with m > n. Also generate some vector b Rm.

Now find x = arg minx Ax b2.

Print the norm of the residual.

代码:

import numpy as np
from scipy.linalg import lstsq

A = np.mat(np.random.randint(0,10,(20,10)))
b = np.mat(np.random.randint(0,10,(20,1)))
ret = lstsq(A,b)
x = np.mat(ret[0])
norm_re = np.linalg.norm(A*x-b,ord=2)
print("x= \n",x)
print("norm = ",norm_re,"\n")
样例输出:
x= 
 [[ 0.27747234]
 [ 0.01934983]
 [-0.17288909]
 [ 0.40072252]
 [ 0.25301335]
 [ 0.34450555]
 [ 0.03587142]
 [-0.16029266]
 [-0.18460015]
 [-0.14021874]]
norm =  5.7700277909560445 

Exercise 10.2: Optimization

Find the maximum of the function f(x) = sin2(x 2)ex

代码:

from scipy.optimize import fmin
import numpy as np

def f(x):
	return (-1)*(np.sin(x-2)**2)*(np.e**(-1*x**2))

res = fmin(f,1)
res_ = -1*res[0]
print(res_)
样例输出:
Optimization terminated successfully.
         Current function value: -0.911685
         Iterations: 16
         Function evaluations: 32
-0.2162109374999993


Exercise 10.3: Pairwise distances

Let X be a matrix with n rows and m columns. How can you compute the pairwise distances betweenevery two rows?

As an example application, consider n cities, and we are given their coordinates in two columns. Nowwe 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. 

代码:

from scipy.spatial.distance import pdist
import numpy as np
X = np.mat(np.random.randint(0,10,(4,3)))
dis = pdist(X,'euclidean')
print(dis)

样例输出:

[ 7.34846923 11.04536102  9.43398113  7.07106781  8.30662386  8.18535277]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值