欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

第十一周作业

程序员文章站 2022-05-12 12:37:38
...

第十一周作业

import numpy as np
import scipy.linalg
import matplotlib.pyplot as plt
 
#initialize
n, m = 200, 500
A = np.mat(np.random.normal(size = (200, 500)))
B = np.mat(scipy.linalg.toeplitz([np.random.normal(0, 1) for i in range(m)]))
 
def f1(Lambda):
	return A * (B - Lambda * np.eye(m))
 
#Excercise 9.1
AaddA = A + A
AAT = A * A.T
ATA = A.T * A
AB = A * B
f1(1)
 
#Exercise 9.2
b = [1 for i in range(m)]
scipy.linalg.solve(B, b)
 
#Exercise 9.3
FrobeniusNormOfA = scipy.linalg.norm(A, 'fro')
infinityNormOfB = scipy.linalg.norm(B, np.inf)
SmallestingularValueOfB = min(scipy.linalg.svdvals(B))
LargestingularValueOfB = max(scipy.linalg.svdvals(B))
 
#Exercise 9.4
 
Z = np.random.normal(size = (500, 500))
bk = np.random.normal(size = (500, ))
i = 0
while 1:
	bk1 = np.dot(Z, bk)
	bk1 /= scipy.linalg.norm(bk1)
	i += 1
	if abs(scipy.linalg.norm(bk, np.inf) - scipy.linalg.norm(bk1, np.inf)) < 10e-6: break
	bk = bk1
print(i)
 
#Exercise 9.5
#Analyse the relationship between the N and the largest singular value
p = 0.5
nValues, LargestingularValues = [], []
for i in range(10):
	N = (i + 1) * 50
	nValues.append(N)
	C = [[1 if np.random.random() > p else 0 for k in range(N)] for j in range(N)]	
	U, sigma, VT=scipy.linalg.svd(C)
	LargestingularValues.append(max(sigma))
plt.scatter(nValues, LargestingularValues, s = 100) 
plt.xlabel("N", fontsize=14)  
plt.ylabel("largest singular value", fontsize=14)
plt.show()
 
#Analyse the relationship between the p and the largest singular value
N = 100
pValues, LargestingularValues = [], []
for i in range(10):
	p = (i + 1) * 0.1
	pValues.append(p)
	C = [[1 if np.random.random() > p else 0 for k in range(N)] for j in range(N)]	
	U, sigma, VT=scipy.linalg.svd(C)
	LargestingularValues.append(max(sigma))
plt.scatter(pValues, LargestingularValues, s = 100) 
plt.xlabel("p", fontsize=14)  
plt.ylabel("largest singular value", fontsize=14)
plt.show()
 
#Exercise 9.6
def f2(z, A):
	return A[np.argmin([abs(A[i] - z) for i in range(len(A))])]
 
f2(0.5, [np.random.normal(0, 1) for i in range(500)])