Python Scipy习题

Exercise 10.1: Least squares

Generate matrix A R m n with m > n . Also generate some vector b R m .
Now find x = arg min x | | A x b | | 2 .
Print the norm of the residual.

代码:

import numpy as np
from scipy import linalg

m, n = 5, 4
A = np.mat(np.random.rand(m, n))
b = np.mat(np.random.rand(m, 1))

x, res, rnk, s = linalg.lstsq(A, b)

norm = linalg.norm(A.dot(x) - b, ord = 2)

print("A =\n",A)
print("b =\n",b)
print("Solution =\n", x)
print("Norm =", res / n)

运行效果:
这里写图片描述

Exercise 10.2: Optimization

Find the maximum of the function f ( x ) = s i n 2 ( x 2 ) e x 2 .

代码:

import numpy as np
from scipy import optimize
from matplotlib import pyplot as plt

def func(x):
    return -np.sin(x - 2) ** 2 * np.exp(-x * x)

maximum = optimize.fmin(func, 0)
print(maximum)

运行效果:
这里写图片描述

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

m, n = 5, 2
x = np.random.rand(m, n)
print("X =\n", x)
y = distance.pdist(x)
z = distance.squareform(y)
print("Distance =\n", z)

运行效果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_36326096/article/details/80599964