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 .


Exercise 9.1: Matrix operations
Calculate A + A , A A T , A T A and A B . Write a function that computes A ( B λ I ) for any λ .
Answer:

import numpy as np

A = np.random.randn(200, 500)
B = np.random.randn(500, 500)

def fun(l):
    return np.dot(A, np.dot(B, l * np.eye(500)))

res1 = A + A
res2 = np.dot(A, A.T)
res3 = np.dot(A.T, A)
res4 = np.dot(A, B)
l = int(input("lambda: "))
res5 = fun(l)
  • numpy.numpy.randn(r, c) 返回 r × c 的标准正态(高斯)分布的矩阵
  • numpy.dot(A, B) 函数计算矩阵A和矩阵B的积
  • A.T 返回矩阵A的逆矩阵
  • numpy.eye(n) 返回 n × n 大小的单位矩阵

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

b = np.random.random((m,))
x = np.linalg.solve(B, b)
  • numpy.random.random() 函数返回 [ 0.0 , 1.0 ) 之间的随机数
  • numpy.linalg.solve(A, b) 函数求解全秩线性矩阵方程Ax = b的解x

Exercise 9.3: Norms
Compute the Frobenius norm of A : A F and the infi nity norm of B : B . Also find the largest and
smallest singular values of B .
Answer:

res1 = np.linalg.norm(A, 'fro')
res2 = np.linalg.norm(B, np.inf)
res3 = np.linalg.norm(B, 2)
res4 = np.linalg.norm(B, -2)
  • numpy.linalg.norm(x, ord=None) 函数的作用是:根据ord 参数的值,该函数能够返回八个不同矩阵范数中的一个其中,fro 返回弗罗贝纽斯(Frobenius)范数,numpy.inf 返回无限(infinity)矢范数,2-2 分别返回最大和最小奇异值(largest and smallest singular values)。

Exercise 9.4: Power iteration
Generate a matrix Z , n × n , with Gaussian entries, and use the power iteration to fi nd the largest
eigenvalue and corresponding eigenvector of Z .
Answer:

Z = np.random.randn(n, n)
res1, res2 = np.linalg.eig(Z)
  • numpy.linalg.eig(Z) 函数返回两个值,第一个是矩阵 Z 的特征值,第二个是矩阵 Z 的特征向量。

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 .
Answer:

p = 0.7
n = 5
C = np.random.binomial(1, p, (n,n))
u, sigma, vt = np.linalg.svd(C)
  • numpy.random.binomial(n, p, (n,m)) 函数返回一个 n × m 的矩阵,其中每个数值是二项分布 ( n N ) p k ( 1 p ) 1 k N 的值,也就是可能成功的次数。或者说,得出的矩阵的数值的分布符合参数为 n p 的二项分布。
  • numpy.linalg.svd(A) 函数对矩阵 A 进行奇异值分解,其中sigma 是奇异值数组。

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.

Answer:

import numpy as np
def find_nearest(array,value):
    idx = (np.abs(array-value)).argmin()
    return array[idx]

value = 0.5

A = np.random.random(10)
print(find_nearest(A, value))
  • numpy.abs(A) 函数返回矩阵 A 的绝对。
  • A.argmin() 函数返回矩阵 A 的最小值的下标。

猜你喜欢

转载自blog.csdn.net/james_154_best/article/details/80357627