Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A∈Rn×m A ∈ R n × m and B∈Rm×m B ∈ R m × m , for n=200 n = 200 , m=500 m = 500 .
Exercise 9.1: Matrix operations
Calculate A+A A + A , AAT A A T , ATA A T A and AB A B . 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×c r × c 的标准正态(高斯)分布的矩阵numpy.dot(A, B)
函数计算矩阵A和矩阵B的积A.T
返回矩阵A的逆矩阵numpy.eye(n)
返回 n×n n × n 大小的单位矩阵Exercise 9.2: Solving a linear system
Generate a vector b with m entries and solve Bx=b B x = 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的解xExercise 9.3: Norms
Compute the Frobenius norm of A A : ∥A∥F ‖ A ‖ F and the infi nity norm of B B : ∥B∥∞ ‖ B ‖ ∞ . Also find the largest and
smallest singular values of B B .
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 Z Z , n×n n × n , with Gaussian entries, and use the power iteration to fi nd the largest
eigenvalue and corresponding eigenvector of Z Z .
Answer:
Z = np.random.randn(n, n)
res1, res2 = np.linalg.eig(Z)
numpy.linalg.eig(Z)
函数返回两个值,第一个是矩阵 Z Z 的特征值,第二个是矩阵 Z Z 的特征向量。Exercise 9.5: Singular values
Generate an n×n n × n matrix, denoted by C C , where each entry is 1 with probability p p and 0 otherwise. Use
the linear algebra library of Scipy to compute the singular values of C C .
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))
函数返回一个 n×m n × m 的矩阵,其中每个数值是二项分布 (nN)pk(1−p)1−k ( n N ) p k ( 1 − p ) 1 − k 中 N N 的值,也就是可能成功的次数。或者说,得出的矩阵的数值的分布符合参数为 n n 和 p p 的二项分布。numpy.linalg.svd(A)
函数对矩阵 A A 进行奇异值分解,其中sigma
是奇异值数组。
Exercise 9.6: Nearest neighbor
Write a function that takes a value z z and an array A A and finds the element in A A that is closest to z z . 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 A 的绝对。A.argmin()
函数返回矩阵 A A 的最小值的下标。