作业——exercise

9 Numpy

Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A ∈Rn×m and B ∈Rm×m, for n = 200, m = 500.

导入模块:

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)


 Exercise 9.1: Matrix operations Calculate

         A + A, AAT,ATA and AB. Write a function that computes A(B−λI) for any λ.

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):



Exercise 9.2: Solving a linear system

    Generate a vector b with m entries and solve Bx = b.
def compute2(b):
    x = np.linalg.solve(B,b)
    print (x)

compute2(np.random.randint(1, 8, m))



Exercise 9.3: Norms Compute

    the Frobenius norm of A: ||A||F and the infinity norm of B: ||B||∞. Also find the largest and smallest singular values of B.
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))


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 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)








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?
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的增大,最大奇异值也增大。


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.
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))

猜你喜欢

转载自blog.csdn.net/ad_jadson/article/details/80412315