Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where and , for , .
Exercise 9.1: Matrix operations
Calculate
,
,
and
. Write a function that computes
for any
.
Answer:
import numpy as np
A = np.random.randn(200, 500)
B = np.random.randn(500, 500)
def fun(l):
return np.dot(A, np.dot(B, l * np.eye(500)))
res1 = A + A
res2 = np.dot(A, A.T)
res3 = np.dot(A.T, A)
res4 = np.dot(A, B)
l = int(input("lambda: "))
res5 = fun(l)
numpy.numpy.randn(r, c)
返回 的标准正态(高斯)分布的矩阵numpy.dot(A, B)
函数计算矩阵A和矩阵B的积A.T
返回矩阵A的逆矩阵numpy.eye(n)
返回 大小的单位矩阵
Exercise 9.2: Solving a linear system
Generate a vector b with m entries and solve
.
Answer:
b = np.random.random((m,))
x = np.linalg.solve(B, b)
numpy.random.random()
函数返回 之间的随机数numpy.linalg.solve(A, b)
函数求解全秩线性矩阵方程Ax = b的解x
Exercise 9.3: Norms
Compute the Frobenius norm of
:
and the infi nity norm of
:
. Also find the largest and
smallest singular values of
.
Answer:
res1 = np.linalg.norm(A, 'fro')
res2 = np.linalg.norm(B, np.inf)
res3 = np.linalg.norm(B, 2)
res4 = np.linalg.norm(B, -2)
numpy.linalg.norm(x, ord=None)
函数的作用是:根据ord
参数的值,该函数能够返回八个不同矩阵范数中的一个其中,fro
返回弗罗贝纽斯(Frobenius)范数,numpy.inf
返回无限(infinity)矢范数,2
和-2
分别返回最大和最小奇异值(largest and smallest singular values)。
Exercise 9.4: Power iteration
Generate a matrix
,
, with Gaussian entries, and use the power iteration to fi nd the largest
eigenvalue and corresponding eigenvector of
.
Answer:
Z = np.random.randn(n, n)
res1, res2 = np.linalg.eig(Z)
numpy.linalg.eig(Z)
函数返回两个值,第一个是矩阵 的特征值,第二个是矩阵 的特征向量。
Exercise 9.5: Singular values
Generate an
matrix, denoted by
, where each entry is 1 with probability
and 0 otherwise. Use
the linear algebra library of Scipy to compute the singular values of
.
Answer:
p = 0.7
n = 5
C = np.random.binomial(1, p, (n,n))
u, sigma, vt = np.linalg.svd(C)
numpy.random.binomial(n, p, (n,m))
函数返回一个 的矩阵,其中每个数值是二项分布 中 的值,也就是可能成功的次数。或者说,得出的矩阵的数值的分布符合参数为 和 的二项分布。numpy.linalg.svd(A)
函数对矩阵 进行奇异值分解,其中sigma
是奇异值数组。
Exercise 9.6: Nearest neighbor
Write a function that takes a value
and an array
and finds the element in
that is closest to
. The
function should return the closest value, not index.
Hint: Use the built-in functionality of Numpy rather than writing code to find this value manually. In particular, use brackets and argmin.
Answer:
import numpy as np
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
value = 0.5
A = np.random.random(10)
print(find_nearest(A, value))
numpy.abs(A)
函数返回矩阵 的绝对。A.argmin()
函数返回矩阵 的最小值的下标。