Learning Numpy, a lib of python with matrix and other calculation.
Prepare
Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A ∈Rn×m and B ∈Rm×m, for n = 200, m = 500.
Code
1 | import numpy |
Result
1 | [[-0.49837536 -0.3247838 0.50678674 ..., -1.2703934 0.76603943 |
Knowledge
- random.normal() to create a matrix with Gaussian entries.
- toepltitz() to create a toepltitz matrix.
- random.seed() , without argument, set random seed by system time.
Exercise 9.1: Matrix operations
Calculate A + A, AA’, A’A and AB. Write a function that computes A(B − λI) for any λ.
Code
1 | A_add_A = A + A |
Result
1 | ---------- A+A ----------- |
Knowledge
- matmul() to calculate the mul of 2 matrics.
- eye(k) to calculate a diagonal matrix, k*k
- transpose() to return matrix’s Inverse matrix
Exercise 9.2: Solving a linear system
Generate a vector b with m entries and solve Bx = b
Code
1 | b = numpy.random.normal(size=m) |
Result
1 | --------- E_9_2 ---------- |
Knowledge
- numpy.linalg.solve(a, b) to calculate the result of ax = b
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.
Code
1 | A_FN = numpy.linalg.norm(A, 'fro') |
Result
1 | ---------- A_FN ------------ |
Knowledge
- 矩阵范数:norm, numpy.linalg.norm()
- 奇异值分解:singular values, numpy.linalg.svd()
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.
Code
1 | import time |
Result
1 | ------------ E_9_4 ---------------- |
Knowledge
- eigenvalue: 特征值
- 幂迭代法:x(k) = x(k-1)*A
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?
Code
1 | p = 0.1 |
Result
1 | -------------- E_9_5 ------------------ |
Knowledge
- random.binomial(n, p, size), n is 0~n, p is probability, size is size
- we can find that
max_singular = 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.
Code
1 | def closest( X, z): |
Result
1 | -------------- Closest --------------- |
Knowledge
- argmin(X) to return X’s minimum’s index