【高级编程技术】【作业】【第十三周】【1】

scipy练习

Scipy - 简书

Exercise 10.1: Least squares

Generate matrix ARm×n A ∈ R m × n with m>n m > n . Also generate some vector bRm b ∈ R m . Now find x=argminxAx=b2 x = arg ⁡ min x ‖ A x = b ‖ 2 . Print the norm of the residual.

import numpy
import scipy.linalg

m, n = 200, 100
A = numpy.random.randint(low=0, high=100, size=(m, n)) + numpy.random.rand(m, n)
b = numpy.random.randint(low=0, high=100, size=(m, 1)) + numpy.random.rand(m, 1)
x_hat = scipy.linalg.lstsq(A, b)[0]
residual = numpy.dot(A, x_hat) - b
print(numpy.linalg.norm(residual, ord=2))

Exercise 10.2: Optimization

Find the maximum of the function

>>f(x)=sin2(x2)ex2>> >> f ( x ) = sin 2 ⁡ ( x − 2 ) e − x 2 >>

import math
import numpy
from scipy import optimize
from matplotlib import pyplot

def f(x):
    return numpy.power(numpy.sin(x-2), 2) * numpy.power(math.e, -numpy.power(x, 2))
x = numpy.arange(-2.5, 2.5, 0.01)
y = f(x)
pyplot.plot(x, y)
max_x = optimize.minimize_scalar(lambda x: -f(x)).x
pyplot.scatter(max_x, f(max_x))
pyplot.text(max_x, f(max_x), (max_x, f(max_x)), ha='center')
pyplot.show()

Exercise 10.3: Pairwise distances

Let X X be a matrix with n rows and m 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 scipy.spatial
import numpy

m, n = 3, 2
X = numpy.random.randint(low=0, high=10, size=(m, n))
print(X)
distances = scipy.spatial.distance_matrix(X, X)
print(distances)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值