Python学习——numpy作业

Numpy Exercises

Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A 2 Rn×m and B 2 Rm×m,for n = 200, m = 500.

import numpy as np
from scipy.linalg import toeplitz
n, m = 200, 500
A = np.random.randn(n, m)
b = [i+0.0 for i in range(1,m+1)]
B = toeplitz(b, b)

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 λ.

print(A+A)
print(np.dot(A,A.T))
print(np.dot(A.T,A))
print(np.dot(A,B))

def func(para):
    I = np.identity(m)
    return np.dot(A, B - para * I)

Exercise 9.2: Solving a linear system

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

分析:可以直接用numpy.linalg.solve,也可以用B的逆矩阵乘以b,两者等价

b = np.random.random(m)
print(np.linalg.solve(B, b))
print(np.dot(np.linalg.inv(B), b))

Exercise 9.3: Norms

Compute the Frobenius norm of A: ||A||F and the infinity norm of B: ||B||inf. Also find the largest and smallest singular values of B.

norm_A_fro = np.linalg.norm(A, ord='fro')
norm_B_inf = np.linalg.norm(B, ord=np.inf)
norm_B_minf = np.linalg.norm(B, ord=-np.inf)
svalue_max = np.linalg.norm(B, ord=2)
svalue_min = np.linalg.norm(B, ord=-2)

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.

分析:用线性代数中的power method进行迭代。主要步骤是:
1. 设置两个变量value1和value2用于迭代估计最大特征值
2. 初始时任取一个向量x作为特征向量,value2等于x的无穷范数
3. abs(value2 - value1) >= epsilon时认作没有收敛,继续循环
4. value1 = 上一次循环的value2
5. value2 = Z * x的无穷范数,x = (Z * x) / value2
6. 重复循环

n, epsilon, count = 100, 1e-4, 0
Z = np.random.randn(n, n)
x = np.ones(n)
value1 = np.inf
value2 = np.linalg.norm(x, ord=np.inf)

while abs(value2 - value1) >= epsilon:
    value1 = value2
    x = np.dot(Z, x)
    value2 = np.linalg.norm(x, ord=np.inf)
    x /= value2
    count += 1

print('largest eigenvalue:', value2)
print('corresponding eigenvector:')
print(x)
print('iteration times:', count)

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?

sing_table = []
for n in range(40,100,10):
    table_col = []
    for p in range(1,10):
        p /= 10.0
        C = np.random.binomial(n=1, p=p, size=n*n).reshape(n, n)
        table_col.append(np.linalg.norm(C, ord=2))
    sing_table.append(table_col)

sing_table = np.array(sing_table).T
print(sing_table)

输出:
[[ 4.27057369  6.19375657  6.82175228  7.57845168  9.23268529 10.21253568]
 [ 9.18551903 11.20865576 13.88790313 14.73108609 17.18865214 19.12329962]
 [12.83356127 15.88150719 18.31520405 22.07088872 24.6668816  27.78363647]
 [17.31365374 20.614359   24.57300062 28.90820256 31.79675608 36.3371934 ]
 [21.43382898 25.21208462 30.7592297  35.83351816 40.38102873 45.10732296]
 [24.60675637 30.03937133 36.05475514 42.62737259 47.74068612 53.99557765]
 [28.64853621 34.73678696 42.12983825 48.43294023 56.72570039 63.74310802]
 [32.67861665 39.62037151 48.00608325 55.78345091 63.58952463 72.54947942]
 [35.59936978 45.06015149 53.87581488 63.23927642 71.9091151  80.99407064]]

n增大和p增大都会使最大奇异值增大

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 findMin(A, z):
    tmp_mat = abs(A - z)
    min_idx = np.unravel_index(np.argmin(tmp_mat), tmp_mat.shape)
    return A[min_idx]

A = np.random.normal(10, 100, 100).reshape(10, 10)
z = 20
print(findMin(A, z))

你可能感兴趣的:(Python课程作业)