Numpy练习

背景:Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A 属于 Rn*m and B 2 Rm*m, for n = 200, m = 500.

Exercise 9.1: Matrix operations
Calculate A + A, AA^T, A^TA and AB. Write a function that computes A(B - λI) for any λ.
  • 先设置随机种子

    import numpy as np
    from scipy.linalg import toeplitz 
    import time
    
    seed = np.int64(time.time())
    # print(seed)
    np.random.seed(seed)
    # print(np.random.seed(seed))
    
  • 设置 A 矩阵

    A = np.random.normal(size=[200, 500])
    
  • 设置 B 矩阵

    B = toeplitz(list(range(1,501)))
    
  • 计算 A + A, A * A^T, A^T * A and A * B

    A2 = A + A
    AAt = A @ A.T
    AtA = A.T @ A
    AmB = A @ B
    
  • 验证结果

    def cmp(A, B, lam):
        temp = B - lam * np.eye(500)
        return A @ temp
    print(cmp(A, B, 3))
    


Exercise 9.2: Solving a linear system
Generate a vector b with m entries and solve Bx = b.

  • 只需要在上面的基础上加上一下两行代码即可

    b = np.array(list(range(1,501)))
    x = np.linalg.solve(B,b)
    


Exercise 9.3: Norms
Compute the Frobenius norm of A: kAkF and the innity norm of B: kBk1. Also nd the largest and
smallest singular values of B.
  • 进行计算

    na = np.linalg.norm(A,'fro')  
    nb = np.linalg.norm(B,np.inf)  
    
    u, s, vh = np.linalg.svd(B,full_matrices=True)  
    maxvalue = max(s)  
    minvalue = min(s)
    


Exercise 9.4: Power iteration
Generate a matrix Z, n * n, with Gaussian entries, and use the power iteration to nd 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.
  • 用幂法求主特征值和主特征向量

    n = 100  
    Z = np.random.normal(5,1,n*n).reshape(n,n)  
    def powerit(Z,n):  
        from time import clock  
        start = clock()  
        u = np.random.normal(5,1,n)  
        last = 1000  
        lam = 0  
        cnt = 0  
        while abs(last-lam) > 0.0001:  
            cnt = cnt+1  
            v = Z@u  
            big = -1  
            last = lam  
            for vv in v:  
                if abs(vv)>big:  
                    lam = vv  
                    big = abs(vv)  
            u = v/lam  
        end = clock()  
        return lam, u, cnt, end-start 
    


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?
  • 计算最大值

    for n in (10,50,100):  
        for p in (0.2,0.5,0.8):  
            print("n = %d, p = %.3f" % (n,p))  
            C = np.random.binomial(1,p,(n,n))  
            u, s, vh = np.linalg.svd(C,full_matrices=True)  
            maxvalue = max(s)  
            print(maxvalue)  
    


Exercise 9.6: Nearest neighbor
Write a function that takes a value z and an array A and nds 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 nd this value 
manually. In particular, use brackets and argmin.
  • 将矩阵的每个值减去目标值,然后取绝对值,最小元素的下标即是和目标值最接近的值的下标,然后根据下标直接返回矩阵中该元素即可

    def nearest_neighbor(matrixA, val_z):  
        idx = np.argmin(np.abs(matrixA - val_z))  
        return matrixA[idx//np.shape(matrixA)[0]][idx%np.shape(matrixA)[1]] 
    
    test_matrix = np.random.random(size=[50, 50])  
    res = nearest_neighbor(test_matrix, 0.5)  
    flag = True  
    for i in range(50):  
        for j in range(50):  
            if np.abs(test_matrix[i][j] - 0.5) < np.abs(res-0.5):  
                flag = False  
    
    if not flag:  
        print("The function is wrong")  
    else:  
        print("The function is right")  
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值