Numpy学习

NUMPY 练习

本文针对题目使用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.

代码如下:

n,m = 200 , 500
A = np.asmatrix(np.random.normal(0,1,(n,m)))
B = toeplitz(range(m))
print("A=")
print(A)
print("B=")
print(B)

Exercise 9.1: Matrix operations

Calculate A + A, AA>,A>A and AB. Write a function that computes A(B−λI) for any λ.
代码如下:

#ex1
print("A+A = \n" , A+A)
print( "A*A = \n" ,np.dot(A,A.T) )  
print( "AT*A = \n" ,np.dot(A.T, A) )  
print( "A*B = \n" ,np.dot(A,B) )  

def fun1(A , langta):
        return A * (B - langta * np.identity(m))

输出如下:

A=
[[ 0.07599125 0.66596144 -0.82802695 1.28213025 0.245328 ] [ 0.30979358 1.02337783 -0.2276264 -0.28964766 1.36393671]]
B=
[[0 1 2 3 4] [1 0 1 2 3] [2 1 0 1 2] [3 2 1 0 1] [4 3 2 1 0]]
A+A = 
 [[ 0.15198251 1.33192287 -1.65605389 2.56426049 0.490656 ] [ 0.61958716 2.04675566 -0.45525281 -0.57929533 2.72787342]]
A*A = 
 [[ 2.83895173 0.8567984 ] [ 0.8567984 3.13930714]]
AT*A = 
 [[ 0.10174673 0.36764313 -0.13344001 0.0076997 0.44118162] [ 0.36764313 1.49080682 -0.78438183 0.5574303 1.55920158] [-0.13344001 -0.78438183 0.7374424 -0.99570694 -0.5136062 ] [ 0.0076997 0.5574303 -0.99570694 1.72775374 -0.08051863] [ 0.44118162 1.55920158 -0.5136062 -0.08051863 1.92050917]]
A*B = 
 [[ 3.83761029 2.5482088 2.59073019 0.97719769 1.92792568] [ 5.15492887 3.59468198 4.08119075 4.11244671 3.56440734]]
langta = 2 , A-B*langta = 

[[ 3.68562778 1.21628593 4.24678408 -1.5870628 1.43726968] [ 4.53534171 1.54792631 4.53644355 4.69174203 0.83653393]]
[Finished in 1.5s]

Exercise 9.2: Solving a linear system

Generate a vector b with m entries and solve Bx = b.

代码如下:

import numpy as np
from scipy.linalg import toeplitz
from scipy.linalg import solve

n,m = 200 , 500
A = np.asmatrix(np.random.normal(0,1,(n,m)))
B = toeplitz(range(m))
#ex2
b = np.random.randint(0,m ,size = (m,1))
print("b = \n" , b)

def fun2(B , b):
        return solve(B,b)

print("Bx = b \n" , fun2(B,b))

输出:

由于输出规模太大,故选取5*5的作为测试:

A=
[[-1.90287671 0.09527566 1.49538221 0.66195349 -1.35135085] [-1.07257636 -1.23105256 -0.77695388 1.19254209 -1.19369539] [ 0.62175956 -0.3198054 1.11542569 -0.31413474 0.62493607] [-1.7385786 0.56898105 -1.16272109 -0.3314636 -0.60911191] [-1.12695307 -1.01303884 -0.16505626 0.60640908 0.40291326]]
B=
[[0 1 2 3 4] [1 0 1 2 3] [2 1 0 1 2] [3 2 1 0 1] [4 3 2 1 0]]
b = 
 [[4] [2] [4] [4] [2]]
Bx = b 
 [[-0.25] [ 2. ] [-1. ] [-1. ] [ 1.75]]
[Finished in 1.3s]

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.
代码如下:

import numpy as np
from scipy.linalg import toeplitz
from scipy.linalg import solve

n,m = 200 , 500
A = np.asmatrix(np.random.normal(0,1,(n,m)))
B = toeplitz(range(m))
#ex3
Frobenius_A = np.linalg.norm(A,'fro')
print("The Frohenius Norm of A: ",Frobenius_A , end="")
print(end="\n")
Infinity_B = np.linalg.norm(B,np.inf)
print("The Infinity Norm of B: ",Infinity_B , end="")
print(end="\n")
U, S, VT = np.linalg.svd(B)
print(S.max(), S.min())

结果如下:

The Frohenius Norm of A:  316.620822129
The Infinity Norm of B:  124750.0
86851.6689847 0.500004934835

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.
代码如下:

import numpy as np
from scipy.linalg import toeplitz
from scipy.linalg import solve
import time

Z = np.random.randn(n, n)
i = 0
x0 = np.random.randn(n)
eg_val = x0.max()
time.clock()
while True:
    i += 1
    x1 = Z.dot(x0/np.linalg.norm(x0, np.inf))
    if (i % 100000 == 0):
        print(str(i) + ': ')
        print('time elapsed:', time.clock())
    if i >= 1000000:
        break
    x0 = x1

p = abs(x0).argmax()
eg_val = x0[p]
eg_vec = x0
if np.sign(Z.dot(eg_vec)[0]) != np.sign((eg_vec*eg_val)[0]):
    eg_val = -eg_val

print('eigenvalue:', eg_val)
print('eigenvector:', eg_vec)
print(np.allclose(Z.dot(eg_vec), eg_vec*eg_val)) 

其结果如下:

100000: 
time elapsed: 2.392553391416248
200000: 
time elapsed: 4.732322869466335
300000: 
time elapsed: 7.509598828667907
400000: 
time elapsed: 9.774808432203704
500000: 
time elapsed: 12.394506673329792
600000: 
time elapsed: 14.865820256301449
700000: 
time elapsed: 17.533920179111597
800000: 
time elapsed: 19.818027670137084
900000: 
time elapsed: 22.317430430921807
1000000: 
time elapsed: 25.057974497266148
eigenvalue: 159.67787537864638
eigenvector: [-133.27047541 -132.07675892 -135.42763323 -143.82592622 -145.59219875
 -138.82176242 -142.07717836 -148.71893325 -133.80947043 -136.15495259  -138.40519322 -129.49815909 -135.40523796 -127.40299559 -144.09944191  -134.090092 -144.81126072 -143.21448892 -138.30883305 -138.13196031  -154.36611658 -149.45213647 -133.78913303 -137.31694006 -148.12920738  -148.08051919 -131.93034717 -139.1166509 -129.36582657 -154.11459685  -138.282479 -159.60026881 -131.37100226 -139.35434498 -142.71486057  -139.99887526 -134.51948153 -141.0598257 -141.98166005 -147.33578259  -119.39896101 -140.3912796 -144.98086469 -130.61040892 -129.55983272  -135.27741055 -129.22162844 -140.55279415 -133.96728903 -134.56884208  -144.08389743 -125.32917507 -145.26479187 -139.58469611 -133.0839744  -144.46422719 -145.72859237 -143.27092189 -139.76122198 -142.96765274  -125.92252696 -153.47358713 -129.65917363 -143.55497279 -127.83450405  -139.95426539 -135.64666443 -141.19063254 -138.31472799 -141.70528609  -136.80576913 -145.52082367 -148.81525734 -131.90587635 -148.30507163  -128.27782509 -137.15612526 -140.05196517 -131.16185209 -135.24931166  -146.7640153 -133.14396727 -137.85752579 -141.41762351 -134.53573354  -131.05627498 -136.03304894 -141.7171628 -134.90927391 -155.267524  -144.49229456 -137.43658998 -131.38200372 -159.67787538 -139.34079184  -133.58986438 -142.09415573 -130.4890389 -144.27222734 -130.9139107  -140.40107295 -133.81618319 -140.60770616 -135.77196403 -140.28016087  -127.33284859 -142.84197628 -134.17198991 -147.87267942 -134.20535298  -142.01474009 -140.42875143 -129.22655162 -142.15638879 -143.51674631  -137.6231031 -134.42239258 -138.25230686 -137.71264975 -122.33046015  -135.20184 -131.37893062 -135.0014697 -144.55558495 -137.8834151  -133.28595353 -151.07548826 -131.16362988 -154.32568021 -143.09134699  -134.9553581 -133.92043463 -145.08353437 -136.52936238 -141.77132278  -145.67337092 -128.59886631 -129.69456688 -138.54306417 -122.24447355  -142.72351261 -139.17953718 -132.17995279 -138.14181359 -155.77121847  -133.31327788 -157.13479209 -134.67695868 -140.03344515 -136.78166528  -127.29915461 -131.78077196 -115.27653478 -139.74671557 -121.08503485  -137.37741294 -142.46535739 -127.00832012 -140.17569647 -138.60102044  -146.3800391 -143.99432441 -136.43782797 -139.39783853 -140.99009259  -138.27283092 -143.0696287 -146.34751102 -147.51727354 -140.90943192  -133.90686814 -135.49977119 -152.42008952 -143.09779178 -144.0304898  -141.50504215 -137.27914146 -154.10798986 -143.11683145 -128.6967144  -148.55678493 -153.68637893 -146.78752608 -142.84912717 -139.31775588  -133.85781745 -145.42537207 -122.89724662 -141.38523673 -131.76941123  -143.11557596 -124.88362722 -135.6092054 -150.54712297 -140.56610842  -137.07495025 -139.35542647 -138.82059026 -138.92480201 -133.88103571] True

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?

代码如下:

import numpy as np
import random
import scipy.linalg

for i in range(10):
        n = random.randint(300, 500)
        p = random.random()
        C = np.asmatrix(np.random.binomial(1, p, (n, n)))
        print("n=",n,"p=",p, "n*p=",n*p, "SV=",scipy.linalg.svd(C)[1].max())

结果如下:

n= 347 p= 0.5103929218863105 n*p= 177.10634389454972 SV= 177.92274389
n= 455 p= 0.771873110502442 n*p= 351.2022652786111 SV= 351.470523856
n= 421 p= 0.9339217660374748 n*p= 393.18106350177686 SV= 393.353371092
n= 486 p= 0.6200045529179393 n*p= 301.3222127181185 SV= 302.074938442
n= 301 p= 0.7370511170758307 n*p= 221.85238623982505 SV= 221.744081235
n= 328 p= 0.8776394902471798 n*p= 287.86575280107496 SV= 287.934341829
n= 430 p= 0.8444270106047145 n*p= 363.1036145600272 SV= 363.521892845
n= 316 p= 0.942437614461403 n*p= 297.8102861698033 SV= 297.415815783
n= 345 p= 0.20194217929603442 n*p= 69.67005185713188 SV= 70.7873230001
n= 331 p= 0.18676968316696518 n*p= 61.82076512826548 SV= 62.6645776952

可以发现他们的结果很相近。

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.

代码如下:

import numpy as np

def find_nearest_neighbour(A, x):
    return np.argmin(abs(A-x))

n = 30
A, x = np.arange(n), np.random.rand()*n
print('A =', A)
print('x =', x)
p = find_nearest_neighbour(A, x)
print('p =', p)
print('A[p] =', A[p])

结果如下:

A = [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 25 26 27 28 29]
x = 3.3337746985725145
p = 3
A[p] = 3
[Finished in 0.7s]

你可能感兴趣的:(python)