Python Numpy习题

Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A ∈ R(n×m) and B ∈ R(m×m), for n = 200, m = 500.

import numpy
import scipy.linalg

n = 200
m = 500

Mu = 0
Sigma = 1
A = numpy.random.normal(Mu, Sigma, (n, m))
print(A)

base = list(range(m))
B = scipy.linalg.toeplitz(base)
print(B)

Exercise 9.1: Matrix operations

Calculate A + A, A(A^T), (A^T)A and AB. Write a function that computes A(B − λI) for any λ.

#计算A + A
result = A + A
print('A + A =\n', result)

#计算A * (A ^ T)
result = numpy.dot(A, A.T)
print('A * (A ^ T) =\n', result)

#计算(A ^ T) * A
result = numpy.dot(A.T, A)
print('(A ^ T) * A =\n', result)

#计算A * B
result = numpy.dot(A, B)
print('A * B =\n', result)

#计算A * (B - λI)
Lambda = int(input('Please input λ: '))
result = numpy.dot(A, (B - Lambda * numpy.identity(m)))
print('A * (B - λI) =\n', result)

Exercise 9.2: Solving a linear system

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

b = numpy.random.random((500, 1))
print('b =\n', b)  
x = numpy.linalg.solve(B, b)  
print('The solution of Bx = b is:\n', x)

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.

frobeniusNormOfA = numpy.linalg.norm(A, ord='fro')
print('the Frobenius norm of A:\n', frobeniusNormOfA)
infnityNormOfB = numpy.linalg.norm(B, numpy.inf)
print('the infnity norm of B:\n', infnityNormOfB)
U, sigmaSingular, VT = numpy.linalg.svd(B)  
maxSingularValue = max(sigmaSingular)  
minSingularValue = min(sigmaSingular)  
print('the largest singular value of B:\n', maxSingularValue)  
print('the smallest singular value of B:\n', minSingularValue) 

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.

def iteration(Z, n):  
    u = numpy.random.randint(0, 10, size = n)  
    times = 0  
    start = time.clock()  
    nex = 1  
    pre = 0  
    while abs(nex - pre) > 0.00001:  
        pre = nex 
        times += 1  
        v = numpy.dot(Z, u)  
        nex = max(abs(v))  
        u = v/nex  
    end = time.clock()  
    return u, nex, times, end - start  

n = 100  
m = 500  
Mu = 0.0  
Sigma = 0.1  
Z = numpy.random.normal(Mu, Sigma, (n, n))  
eigenvector, lam, num_iters, time = iteration(Z, n)  
print('the largest eigenvalue: ', lam)  
print('the corresponding eigenvector: ', eigenvector)  
print('the number of iterations: ', num_iters)  
print('the time of iterations: ', time) 

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 range(10, 200, 10):
    C = numpy.zeros((n, n))
    for p in range(1, 10, 1):
        for i in range(n):
            for j in range(n):
                C[i][j] = 1 if numpy.random.random() < p/10 else 0
        U, S, V = numpy.linalg.svd(C)  
        maxSingularValue = max(S)
        print('n =', n, ' p =', p, ' the largest singular value is', maxSingularValue)

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.

def nearestNeighbor(z, A):  
    B = abs(A - z)  
    return A[numpy.argmin(B)]  

z = numpy.random.random()
A = numpy.random.random(100) 
print('z =\n', z)  
print('A =\n', A)  
print('the nearest neighbor:\n', nearestNeighbor(z, A))  
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36326096/article/details/80413723
个人分类: 程序设计基础
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭