Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A∈Rn×mA∈Rn×m and B∈Rm×mB∈Rm×m, for n=200n=200, m=500m=500.
Exercise 9.1: Matrix operations
Calculate A+AA+A, AATAAT, ATAATA and ABAB. Write a function that computes A(B−λI)A(B−λI) 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)返回r×cr×c 的标准正态(高斯)分布的矩阵numpy.dot(A, B)函数计算矩阵A和矩阵B的积A.T返回矩阵A的逆矩阵numpy.eye(n)返回n×nn×n大小的单位矩阵
Exercise 9.2: Solving a linear system
Generate a vector b with m entries and solveBx=bBx=b.
Answer:
b = np.random.random((m,))
x = np.linalg.solve(B, b)
numpy.random.random()函数返回[0.0,1.0)[0.0,1.0)之间的随机数numpy.linalg.solve(A, b)函数求解全秩线性矩阵方程Ax = b的解x
Exercise 9.3: Norms
Compute the Frobenius norm of AA: and the infinity norm of BB: . Also find the largest and
smallest singular values of BB.
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 , n×nn×n, with Gaussian entries, and use the power iteration to find the largest
eigenvalue and corresponding eigenvector of ZZ.
Answer:
Z = np.random.randn(n, n)
res1, res2 = np.linalg.eig(Z)
numpy.linalg.eig(Z)函数返回两个值,第一个是矩阵 的特征值,第二个是矩阵ZZ 的特征向量。
Exercise 9.5: Singular values
Generate an matrix, denoted by CC, where each entry is 1 with probability and 0 otherwise. Use
the linear algebra library of Scipy to compute the singular values of CC.
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))函数返回一个 的矩阵,其中每个数值是二项分布(nN)pk(1−p)1−k(nN)pk(1−p)1−k 中NN的值,也就是可能成功的次数。或者说,得出的矩阵的数值的分布符合参数为 和pp 的二项分布。numpy.linalg.svd(A)函数对矩阵进行奇异值分解,其中sigma是奇异值数组。
Exercise 9.6: Nearest neighbor
Write a function that takes a value zz and an array and finds the element in AA 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)函数返回矩阵AA 的绝对。A.argmin()函数返回矩阵 的最小值的下标。
359

被折叠的 条评论
为什么被折叠?



