Python学习笔记——numpy

numpy是python中一个类似于c语言中math的函数库,可以简化许多数学方法的使用。以下是练习题和代码:

Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A ∈Rn×m and B ∈Rm×m, 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 λ. Exercise 9.2: Solving a linear system Generate a vector b with m entries and solve Bx = b.
Exercise 9.3: Norms Compute the Frobenius norm of A: kAkF and the infinity norm of B: kBk∞. Also find the largest and smallest singular values of B.
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.
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?
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.

import numpy as np  
from scipy.linalg import toeplitz  
import time  
  
#9.1  
def ex9_1(A, B, n, m):  
    print("A + A:")  
    C = A + A  
    print(C)  
      
    print("AA^:")  
    print(np.dot(A, A.T))  
      
    print("A^A:")  
    print(np.dot(A.T, A))  
      
    print("AB:")  
    print(np.dot(A, B))  
      
    print("A(B − λI):")  
    C = B - lamda * (np.eye(m))  
    print(np.dot(A, C))  

    print("\n")

    
#9.2  
def ex9_2(A, B, n, m):  
    b = np.ones((m, 1))  
    x = np.linalg.solve(B, b)  
    print(x)
    
    print("\n")
  
#9.3  
def ex9_3(A, B, n, m):
    A_F = np.linalg.norm(A, 'fro')  
    print("the Frobenius norm:", A_F)  
      
    B_F = np.linalg.norm(B, np.inf)  
    print("the infinity norm:", B_F)  
          
    lar_sin = np.linalg.norm(B, 2)  
    smal_sin = np.linalg.norm(B, -2)  
    print("the largest singular:", lar_sin)  
    print("the smallest singular:", smal_sin)

    print("\n")
      
#9.4  
def ex9_4(A, B, n, m):  
    Z = np.random.standard_normal((n, n))
    num = 0  
    u_k = np.ones(n)  
    v_k_norm = 0  
    v_k = np.zeros(n)  
      
    begin = time.clock()  
    while(True):  
        v_k = np.dot(Z, u_k)  
        v_k_norm_temp = v_k_norm  
        v_k_norm = np.linalg.norm(v_k)  
        u_k = v_k / v_k_norm  
        num += 1  
        if(abs(v_k_norm_temp - v_k_norm) < 0.0005):  
            break;  
    end = time.clock()  
      
    print("the largest eigenvalue:", v_k_norm)  
    print("the corresponding eigenvector:", u_k)  
    print("The number of iterations:", num)
    print("computation time when varying n:", end-begin)

    print("\n")
  
#9.5  
def ex9_5(A, B, n, m):  
    p = 0.5  
    C = np.random. binomial(1, p, (n, n))  
        
    lar_sin = np.linalg.norm(C, 2)  
    smal_sin = np.linalg.norm(C, -2)  
    print("the smallest singular:", smal_sin)  
    print("the largest singular:", lar_sin)  
      
    print("n * p:", n*p)  
    print("the largest singular is closed with n * p \nso that we can say they are equal!")  

    print("\n")
    
#9.6  
def ex9_6(A, B, n, m):   
    z = -5  
      
    B, C = A[A>z], A[A<=z]  
    ceil, floor = 0, 0  
      
    if(len(B)):  
        ceil = np.argmin(B)  
    else:  
        return C[np.argmax(C)]  
      
    if(len(C)):  
        floor = np.argmax(C)  
    else:  
        return B[ceil]  
          
    if(abs(B[ceil]-z) < abs(C[floor]-z)):  
        return B[ceil]  
    else:  
        return C[floor]
    
    print("the closest value:", closest)

    print("\n")


#赋初值
mu, sigma = 0, 1.0
n, m = 200, 500  
A = np.random.normal(loc=mu, scale=sigma, size=(n, m))  
c = [a for a in range(1, m+1)]  
B = toeplitz(c, c)  
  
ex_9_1(A, B, n, m)  
ex_9_2(A, B, n, m)  
ex_9_3(A, B, n, m)
ex_9_4(A, B, n, m)  
ex_9_5(A, B, n, m)  
ex_9_6(A, B, n, m)  
2018/5/22


猜你喜欢

转载自blog.csdn.net/ltc8600/article/details/80402975