scipy习题答案(仅供参考)

Exercise 10.1: Least squares
Generate matrix ∈ Rm×with m > n. Also generate some vector ∈ Rm. Now find = arg minAx − b2.
Print the norm of the residual.

import numpy as np
import scipy as sp
m = 20
n = 15
A = np.random.random((m,n))
b = np.random.random((m,))
x, residual, rank, s = sp.linalg.lstsq(A,b)
b1 = A.dot(x)
print(sp.linalg.norm(b - b1))
运行结果:
0.3462921048521962


Exercise 10.2: Optimization
Find the maximum of the function    :f(x) = sin2(− 2)ex2

from scipy.optimize import fmin
def func(x):
    return -(np.sin(x-2))**2*(np.exp(-x**2))

opt = fmin(func,0)
print(-f(opt)[0])
运行结果:
Optimization terminated successfully.
         Current function value: -0.911685
         Iterations: 20
         Function evaluations: 40
0.9116854117069156


Exercise 10.3: Pairwise distances
Let be a matrix with rows and columns. How can you compute the pairwise distances between every two rows?
As an example application, consider 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.

n = 5
m = 3
A = np.random.rand(n,m)
X = scipy.spatial.distance.pdist(A)  
Y = scipy.spatial.distance.squareform(X)  
print(Y)
运行结果:
[[0.         1.03161295 0.79745052 0.54036634 0.49914287]
 [1.03161295 0.         0.89030578 1.18083032 0.67161284]
 [0.79745052 0.89030578 0.         0.84625376 0.9042936 ]
 [0.54036634 1.18083032 0.84625376 0.         0.69062377]
 [0.49914287 0.67161284 0.9042936  0.69062377 0.        ]]

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值