Python学习——Scipy作业

Scipy Exercises

Exercise 10.1: Least squares

Generate matrix ARmn A ∈ R m ∗ n with m > n. Also generate some vector bRm b ∈ R m .
Now find x=argminx||Axb||2 x = a r g m i n x | | A x − b | | 2 .
Print the norm of the residual.

分析:直接用scipy.linalg中的lstsq与norm函数即可,注意此时b要求是m*1的矩阵,因此要reshape一下。

import numpy as np
import scipy.linalg as la

m, n = 20, 10
A = np.random.randn(m, n)
b = np.random.randn(m).reshape(m, 1)
res = la.lstsq(A, b)
x = res[0]
print(x)
residual = la.norm(np.dot(A, x) - b, ord=2)
print(residual)

Exercise 10.2: Optimization

Find the maximum of the function

f(x)=sin2(x2)ex2 f ( x ) = s i n 2 ( x − 2 ) e − x 2

分析:注意这些最优化方法求的都是最小值,要求最大值就把函数计算的值取反

import numpy as np
import scipy.optimize as opt

def func(nums):
    return (np.sin(nums - 2) ** 2) * (np.e ** (-nums ** 2))
func_inv =  lambda x: -func(x)

res1 = opt.brute(func_inv, ((-5, 5),), full_output=1)
res2 = opt.fmin(func_inv, 0, full_output=1)
max1, max2 = -res1[1], -res2[1]
print(max1, max2)

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 as dist

n, m = 6, 3
X = np.random.randint(5, 20, size=(n, m))
D = dist.cdist(X, X)
print(D)

你可能感兴趣的:(Python课程作业)