Python Scipy习题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36326096/article/details/80599964

Exercise 10.1: Least squares

Generate matrix ARmn with m>n. Also generate some vector bRm.
Now find x=argminx||Axb||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)=sin2(x2)ex2.

代码:

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)

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

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页