Scipy

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 norm,lstsq

n = 10
m = 20
A = np.random.randint(0, 100, size=(m, n))
b = np.random.randint(0, 100, size=(m, 1))

x,res, rnk, s= lstsq(A, b) 
l = norm(b-np.dot(A,x),ord=2) 

print(A)
print(b)
print(l)

result:


其中出现了

RuntimeWarning: internal gelsd driver lwork query error, required iwork dimension not returned. This is likely the result of LAPACK bug 0038, fixed in LAPACK 3.2.2 (released July 21, 2010). Falling back to 'gelss' driver.

我上网查了一下,发现不是什么大问题,不会影响结果。



Exercise 10.2: Optimization

Find the maximum of the function

f(x) = sin2(x 2)ex2

import numpy as np
from scipy import optimize

fun = lambda x : (-1)*(np.sin(x-2))**2*np.exp((-1)*(x**2)) 

temp = optimize.minimize_scalar(fun)
ans = -temp.fun
print(temp)
print("the maximum is " + str(ans))

 result:




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
import scipy.spatial.distance

n = 10
m = 20

X = np.random.randint(0,100,size=(n,m))
ans = scipy.spatial.distance.pdist(X, "euclidean")
print(X) 
print(ans)
result:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值