python numpy示例

Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A = M(n * m),B = M(m * m)

for n = 200, m = 500.  (下面我以 n = 2, m = 5 为例)


Exercise 9.1: Matrix operations

Calculate A + A, A*AT,AT* A and AB. Write a function that computes A(B-kI) for any k

import numpy as np
import random

#定义矩阵大小
n = 2
m = 5

#创建矩阵, 默认为ndarray类型
mA = np.zeros((n, m))

#生成随机矩阵元素
for x in range(n):
    for y in range(m):
        mA[x][y] = random.randint(1, 10)

mBtemp = [] 
for x in range(2*m-1):
    mBtemp.append(random.randint(1, 10))
mB = np.matrix(np.array(mBtemp[0:m]))
for x in range(1, m):
    mB = np.insert(mB, x, values=np.array(mBtemp[-1*x:] + mBtemp[0:m-x]), axis = 0)
    
     
print("A = \n", mA)
print("B = \n", mB)

#9.1 
#A + A
mAA = mA + mA
print("A + A = \n", mAA)

#A * AT,默认为matrix类型
mAAT = np.matrix(mA) * np.matrix(mA.transpose())
print("A * AT = \n", mAAT)

#AT * A
mATA = np.matrix(mA.transpose()) * np.matrix(mA)
print("AT * A = \n", mATA)

#AB
mAB = np.matrix(mA) * np.matrix(mB)
print("A * B = \n", mAB)

#A(B-kI) = AB - kA for any k
k = int(input("please input k for A(B-kI): "))
print("A(B-kI) = \n", np.array(mAB) - k*mA)

测试结果如下:


Exercise 9.2: Solving a linear system

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

import numpy as np
import random

#定义矩阵大小
m = 5

mBtemp = [] 
for x in range(2*m-1):
    mBtemp.append(random.randint(1, 10))
mB = np.matrix(np.array(mBtemp[0:m]))
for x in range(1, m):
    mB = np.insert(mB, x, values=np.array(mBtemp[-1*x:] + mBtemp[0:m-x]), axis = 0)
    
vb = []
for x in range(m):
    vb.append(random.randint(1, 10))
     
print("B = \n", mB)
print("vb = ", vb)

#invB = np.linalg.inv(mB)

print("Bx = b, x = ", np.linalg.solve(mB, vb))

运行截图如下:



Exercise 9.3: Norms
Compute the Frobenius norm of A: ||A||F and the in nity norm of B: ||B||1. Also nd the largest and

smallest singular values of B.

扫描二维码关注公众号,回复: 2321022 查看本文章
import numpy as np
import random

#定义矩阵大小
n = 2
m = 5

#创建矩阵, 默认为ndarray类型
mA = np.zeros((n, m))

#生成随机矩阵元素
for x in range(n):
    for y in range(m):
        mA[x][y] = random.randint(1, 10)

mBtemp = [] 
for x in range(2*m-1):
    mBtemp.append(random.randint(1, 10))
mB = np.matrix(np.array(mBtemp[0:m]))
for x in range(1, m):
    mB = np.insert(mB, x, values=np.array(mBtemp[-1*x:] + mBtemp[0:m-x]), axis = 0)
    
print("A = \n", mA)
print("B = \n", mB)

#矩阵范数
print("|mA|F = ", np.linalg.norm(mA))
print("|mB| = ", np.linalg.norm(mB, np.inf))

#svd分解
u, s, vh = np.linalg.svd(mB)
print("the max sigular value of B is: ", max(s))
print("the min sigular value of B is: ", 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.

import numpy as np
import random
import time

#定义矩阵大小
n = 5

#创建矩阵, 默认为ndarray类型
mZ = np.random.randn(n,n)
print("Z = \n", mZ)

t = np.random.randint(0, 10, size=n)
last = 1
k = 0
num = 0
start = time.clock()
while abs(k - last) > 0.0001:
    last = k
    num += 1
    v = np.dot(mZ, t)
    k = 0
    for vx in v:
        if abs(k) < abs(vx):
            k = vx
    t = v/k
end = time.clock()

print("the max eigenvalue is: ", k)
print("the corresponding eigenvector is: ", t)
print("iteration time is: ", end - start)
print("iteration num is: ", num)

运行截图如下:



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

#定义矩阵大小
n = 100

#创建矩阵, 默认为ndarray类型
mC = np.zeros((n, n))

#生成随机矩阵元素
p = 0
for x in range(n):
    for y in range(n):
        mC[x][y] = random.randint(0, 1)
        if mC[x][y] == 1:
            p += 1
p /= n
print("C = \n", mC)
u, s, vh = np.linalg.svd(mC)
print("C's sigular value are: \n", s)
print("n, p: ", n, p)

print("n越大, p越接近最大的奇异值")

运行截图如下:



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.

import numpy as np
import random

#定义矩阵大小
n = 10

#创建矩阵, 默认为ndarray类型
mA = np.zeros(n)

#生成随机矩阵元素
for x in range(n):
    mA[x] = random.randint(1, 100)
   
print("A = \n", mA)

z = random.randint(1, 100)
print(z)
mB = abs(mA - z)
print(mA[np.argmin(mB)])

运行截图:


猜你喜欢

转载自blog.csdn.net/qq_36974075/article/details/80388708