Exercise 9.1: Matrix operations
import numpy
from scipy.linalg import toeplitz
A = []
for i in range(0, 200):
x = numpy.random.normal(size=500)
A.append(x)
A = numpy.array(A)
B = toeplitz([i for i in range(0, 500)])
print(A + A)
print(numpy.dot(A, A.T))
print(numpy.dot(A.T, A))
print(numpy.dot(A, B))
def calculate(A, B, I, namuda):
return numpy.dot(A, B - namuda * I)
Exercise 9.2: Solving a linear system
import numpy
from scipy.linalg import toeplitz
A = []
for i in range(0, 200):
x = numpy.random.normal(size=500)
A.append(x)
A = numpy.mat(A)
B = numpy.mat(toeplitz([i for i in range(0, 500)]))
b = numpy.array([i for i in range(0, 500)])
x = numpy.dot(b, B.I)
print(x)
Exercise 9.3: Norm
import numpy
from scipy.linalg import toeplitz, svdvals
A = []
for i in range(0, 200):
x = numpy.random.normal(size=500)
A.append(x)
A = numpy.mat(A)
B = numpy.mat(toeplitz([i for i in range(0, 500)]))
Frobenius_norm = numpy.linalg.norm(A, 'fro')
infinity_norm = numpy.linalg.norm(B, numpy.inf)
value = svdvals(B)
largest_singular_value = max(value)
smallest_singular_value = min(value)
print(Frobenius_norm)
print(infinity_norm)
print(largest_singular_value)
print(smallest_singular_value)
Exercise 9.4: Power iteration
import numpy
import time
Z = []
for i in range(0, 200):
x = numpy.random.normal(size=200)
Z.append(x)
Z = numpy.mat(Z)
def max_abs(xn):
return abs(xn).max()
time.clock()
x = numpy.array([1 for i in range(0, 200)])
tol = 0.1
xn = numpy.dot(Z, x.reshape(200, 1))
xn = xn.reshape(1, 200)
xp = x
while max_abs(xn - xp)> tol:
xp = xn
y = max_abs(xn)
xn = xn / y
xn = numpy.dot(Z, xn.reshape(200, 1))
xn = xn.reshape(1, 200)
eigenvalue = 1 / max_abs(xn)
print(eigenvalue)
print(time.clock(), 'seconds')
Exercise 9.5: Singular values
import numpy
import random
from scipy.linalg import svdvals
def random_num():
if random.randint(1, 10) < 6:
return 1
else:
return 0
C = []
for i in range(0, 200):
x = []
for j in range(0, 200):
x.append(random_num())
C.append(x)
C = numpy.mat(C)
largest_singular_value = max(svdvals(C))
print(largest_singular_value)
关系:largest_singular_value = n * p
Exercise 9.6: Nearest neighbor
import numpy
def NearestNeighber(z, A):
tmp = []
for i in range(0, len(A)):
tmp.append(abs(A[i] - z))
return A[numpy.argmin(tmp)]