Exercise:学习使用Numpy

本文中涉及了矩阵的加、减、乘、转置等操作。主要是使用矩阵类的内置属性和方法以及numpy提供的方法来进行相关的操作:
有需要的读者可以根据个人需要对照下方题目表涉及的方法进行查阅。


前置生成相关矩阵

import numpy as np
from scipy.linalg import toeplitzn = 5m = 5A = np.random.randn(n,m)print( A )#print( np.linalg.inv(A) )r = np.random.randint(10 ,size = m)c = np.random.randint(10 , size = m )
B = toeplitz(r,c)
#B = np.random.randn(m,m)print( B )
9.1
#*****Matrix operations
print( "A+A is:\n" , A+A )
print( "A*A is:\n" ,np.dot(A,A.T) )
print( "AT*A is:\n" ,np.dot(A.T, A) )
print( "A*B is:\n" ,np.dot(A,B) )


def calculate( A,B,num ) :
    I = np.eye( m )
    C = B-num*I
    print('A*(B-num*I) is:\n' , np.dot(A,C) )


calculate( A,B, 1)
9.2
#*****Solving a linear system
def solve( B , b ):
    return np.linalg.solve(B,b)

b = np.random.randint(10, size = m )
print( "Solve Bx=b:\n" , solve(B,b) )

9.3
#*****Norms
print("A的fro范数:", np.linalg.norm( A , ord = 'fro' )) #fro 范数
print("B的无穷范数: ", np.linalg.norm( B , ord = np.inf ) ) #无穷范数
print("B的最大奇异值:", np.linalg.norm(B,2) )
print("B的最小奇异值:", np.linalg.norm(B,-2) )

9.4
#*****Power iteration
import time
def find_eig( Z , n ):
    num = 0
    u_k = np.ones(n)
    v_k_norm = 0
    v_k = np.zeros(0)

    #begin iteration
    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.0001 ):
            break
    
    end = time.clock()
    print("the largest eigenvalue:", v_k_norm)  
    print("the corresponding eigenvector:", u_k)
Z = np.random.randn(n,n)
find_eig( Z , n )

9.5
#******Singular values
def singular_val( p , n ):
    C = np.random.binomial( 1,p,(n,n) ) #二项分布
    val = np.linalg.norm( C , 2 ) #the max singular value
    print ("the max singular value: " ,val )
    print( "n*p is :" , n*p )
    if ( abs(n*p-val) < 0.01 ):
        print( "They are equal")
    else :
        print( "They are not equal" )

9.6
#*******Nearest neighbor

def nearest_neighbor(A , z ):
    bigger = (A[A>z]).min()
    less = (A[A<=z]).max()
    if ( abs(less-z) < abs(bigger-z) ):
        print( less )
    else :
        print( bigger )
        
nearest_neighbor( A, 0 )


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值