先生成A,B矩阵,令n,m分别为200,500
import numpy
from scipy.linalg import toeplitz
A = numpy.random.normal(size=(200, 500))
B = toeplitz(range(1, 501))
Exercise 9.1: Matrix operations
Calculate A + A, A·AT, AT·A and A·B. Write a function that computes A(B − λI) for any λ.
answer1 = numpy.add(A, A)
answer2 = numpy.dot(A, A.T)
answer3 = numpy.dot(A.T, A)
answer4 = numpy.dot(A, B)
def compute(A, B, r):
return (A.dot(B - r * numpy.eye(len(B)))) # 以B的维数生成一个单位矩阵
Ex 9-2 Solving a linear system
solution = np.linalg.solve(matrix_b, vector_b)
Exercise 9.3: Norms
Compute the Frobenius norm of A: kAkF and the infinity norm of B: kBk∞. Also find the largest and smallest singular values of B.
frobenius_norm_A = np.linalg.norm(matrix_a, 'fro')
infinity_norm_B = np.linalg.norm(matrix_b, np.inf)
#b的最大最小值
max_element_of_B = matrix_b.max()
min_element_of_B = matrix_b.min()
Exercise 9.4: Power iteration
Generate a matrix Z, n × n, with Gaussian entries, and use the power iteration to find the largest eigenvalue and corresponding eigenvector of Z. How many iterations are needed till convergence?
Optional: use the time.clock() method to compare computation time when varying n.
def powerIter(Z, e):
b_k = numpy.asmatrix(numpy.random.rand(Z.shape[1])).T
b_k_bak = b_k
iteration = 0
start_time = time.clock()
while iteration == 0 or abs(numpy.linalg.norm(b_k - b_k_bak)) >= e:
b_k1 = numpy.dot(Z, b_k)
b_k1_norm = numpy.linalg.norm(b_k1)
b_k_bak = b_k
b_k = b_k1 / b_k1_norm
iteration += 1
end_time = time.clock()
print("iteration = ", iteration, end='')
print(", time = ", end_time - start_time, "s.")
return b_k
Z = numpy.asmatrix(numpy.random.random_integers(1, 100, size=(500, 500)))
print(powerIter(Z, 10e-5))
Exercise 9.5: Singular values
Generate an n × n matrix, denoted by C, where each entry is 1 with probability p and 0 otherwise. Use the linear algebra library of Scipy to compute the singular values of C. What can you say about the relationship between n, p and the largest singular value?
numpy实际上提供了svd函数来计算奇异值,故使用它测试
import numpy as np
def generate_matrix(row,col,p):
re = np.ones((row,col))
for i in range(row):
for j in range(col):
if np.random.rand() < p :
re[i][j] =1
else:
re[i][j] = 0
return re
for n in [100,200,300,400,500]:
for p in [0.1,0.2,0.5,0.8]:
C = generate_matrix(n, n, p)
u, s, vh = np.linalg.svd(C)
max_singular_value = np.max(s)
print('n:', n, ' p:', p, ' s:', max_singular_value, '\n')
Exercise 9.6: Nearest neighbor
Write a function that takes a value z and an array A and finds the element in A that is closest to 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.
mport numpy as np
n=200
def find_closest(A, z):
C = np.abs(A - z)
idx = np.argmin(C)
return A[idx // A.shape[0]][idx % A.shape[0]]
A = np.random.rand(n, n)
print(A)
print(find_closest(A, 1))