导入模块:
import numpy as np
import time
from scipy.linalg import toeplitz
创建建目标矩阵:
n = 200
m = 500
np.random.seed()
A = np.random.randn(n, m)
B = toeplitz(np.random.randn(m), np.random.randn(m))
print("A:\n", A)
print("B:\n", B)
print("\nA+A:\n", A + A)
print("AAT:\n", np.dot(A, np.transpose(A)))
print("ATA:\n", np.dot(np.transpose(A), A))
print("AB:\n", np.dot(A, B))
def compute1(i):
I = np.eye(len(B))
print(np.dot(A, B - i*I))
compute1(3)
计算A(B−λI):
def compute2(b):
x = np.linalg.solve(B,b)
print (x)
compute2(np.random.randint(1, 8, m))
print("\nFrobenius norm of A:", np.linalg.norm(A, 2))
print("The infinity norm of B:", np.linalg.norm(B, np.inf))
u, s, v = np.linalg.svd(B)
print("the largest singular values: ", max(s))
print("the smallest singular values: ", min(s))
def power_iteration(Z):
temp = np.random.randint(0, 10, len(Z))
c_max = 0
last = -1
iteration = 0
begin = time.clock()
while 1:
last = c_max
iteration += 1
v = np.dot(Z, temp)
c_max = 0
for vx in v:
if abs(c_max) < abs(vx):
c_max = vx
temp = v/c_max
if abs(c_max - last) < 0.0001:
break
end = time.clock()
return end - begin, iteration
Z = np.random.randn(20, 20)
iteration_time, iteration = power_iteration(Z)
eigenvalue, eigenvector = np.linalg.eig(Z)
print("\nEigenvalue: ", eigenvalue)
print("Eigenvector: \n", eigenvector)
print("Iteration: ", iteration)
print("Time cost: ", iteration_time)
C = np.random.binomial(1, 0.2, (200, 200))
u, s, v = np.linalg.svd(C)
print("\nThe singular values:\n", s)
j = 10
print('')
for i in range(0, 9):
j += 10
all_p = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
for p in all_p:
C = np.random.binomial(1, p, (j, j))
u, s, v = np.linalg.svd(C)
print(max(s), end = ' ')
print('')
由上图可知,随着n,p的增大,最大奇异值也增大。
def closest(z, E):
F = E - z
i = np.argmin(np.abs(F))
l = []
for m in range(0,len(E)):
for j in E[m]:
l.append(j)
return l[i]
print("The closest value: ", closest(2, A))