Generate matrices
A
, with random Gaussian entries,
B
, a Toeplitz matrix, where
A
2
R
n
×
m
and
B
2
R
m
×
m
,
for n = 200, m = 500.
Exercise 9.1: Matrix operations
Compute the Frobenius norm of A : k A k F and the infinity norm of B : k B k 1 . Also find the largest and
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 .
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?
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 .
for n = 200, m = 500.
Exercise 9.1: Matrix operations
Calculate A + A, AA>; A>A and AB. Write a function that computes A(B - λI) for any λ.
import numpy
from scipy.linalg import toeplitz
import time
def compute(A, B, lamda):
Im = numpy.identity(m)
return numpy.dot(A, (B - lamda * Im)) # 矩阵相乘用dot,直接*是列表相乘
n = 3
m = 4
A = numpy.random.randn(n, m) # 生成n行m列标准正态分布的矩阵
print(' A:')
print(A)
B = toeplitz([numpy.random.randint(1, 10)
for i in range(m)]) # 生成拓普利兹矩阵,只传第一列进去就默认第一行也是这些元素
print(' B:')
print(B)
print(" A+A:")
print(A + A)
print(" AAT:")
print(numpy.dot(A, A.T))
print(" ATA:")
print(numpy.dot(A.T, A))
print(' AB')
print(numpy.dot(A, B))
print(" A(B - lamda*I):")
print(compute(A, B, 3))
Exercise 9.2: Solving a linear systemGenerate a vector b with m entries and solve Bx = b.
b = numpy.array([[numpy.random.randint(1, 10)
for i in range(m)]]).T # 生成m行1列的向量,T表示转置
print('b:')
print(b)
print('Bx=b,so x=')
print(numpy.linalg.solve(B, b)) # 解矩阵(有可能无解?)
Exercise 9.3: NormsCompute the Frobenius norm of A : k A k F and the infinity norm of B : k B k 1 . Also find the largest and
smallest singular values of B.
print('the Frobenius norm of A:')
print(numpy.linalg.norm(A, 'fro'))
print('the infinity norm of B:')
print(numpy.linalg.norm(B, numpy.inf))
# svd分解得到的矩阵Simga的对角元素即为特征值,并且python已经作为一个行向量返回
U, Simga, VT = numpy.linalg.svd(B)
print("the largest singular value of B:")
print(max(Simga))
print("the smalest singular value of B:")
print(min(Simga), '\n')
Exercise 9.4: Power iterationGenerate 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 PowerIteration(Z): # 返回规格化后的主特征向量
# shape返回(行数,列数)元组,standard_evector为列数个元素组成的向量
standard_evector = numpy.random.rand(Z.shape[1]) # 初始化随机向量,之后作为规格化特征向量
evalue = 1 # 特征值
pre_evalue = 0 # 前一次迭代特征值
iterate_num = 0 # 迭代次数
start_time = time.clock() # 开始时间
while abs(evalue - pre_evalue) > 0.00001: # 相邻两次迭代特征值差的绝对值作为判停条件
iterate_num += 1
evector = numpy.dot(Z, standard_evector)
pre_evalue = evalue
evalue = numpy.linalg.norm(evector)
standard_evector = evector / evalue # 特征向量规格化
end_time = time.clock() # 结束时间
return standard_evector, evalue, iterate_num, end_time - start_time
n = 200
mu = 0.0
sigma = 0.1
Z = numpy.random.normal(mu, sigma, (n, n))
# Z = numpy.random.randn(n, n)#标准正态分布时间会比较长
standard_evector, evalue, iterate_num, past_time = PowerIteration(Z)
print('standard_evector:', standard_evector)
print('evalue', evalue)
print('past_time:', str(past_time) + 's')
print('iterate_num', str(iterate_num) + 'times')
Exercise 9.5: Singular valuesGenerate 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?
def generate01row(n, p): # 按概率生成一个01矩阵的一行,关键是在【0,1】区间里根据概率划分范围再取数
row = []
for i in range(n):
num = numpy.random.random()
if num <= p:
row.append(1)
else:
row.append(0)
return row
n = 10
p = 0.5
arr = numpy.array([generate01row(n, p) for i in range(n)]) #列表解析
U, Simga, VT = numpy.linalg.svd(arr)
print('\nn:', n)
print('p:', p)
print('largest singular value:', max(Simga))
Exercise 9.6: Nearest neighborWrite 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 .
def closet_value(A, z, m):
index = numpy.argmin(numpy.abs(A - z)) # 找最小绝对值,argmin作用和min一样
return A[index // m][index % m]
n = 3
m = 4
A = numpy.random.randn(n, m)
z = 1
print('A:')
print(A)
print('closet_value:')
print(closet_value(A, z, m))