高级编程技术第十五次作业

时间:2021-11-21 21:57:50

Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A 2 Rnm and B 2 Rmm, 

for n = 200, m = 500.

9-1 Matrix operations

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

import numpy as np
from scipy.linalg import toeplitz

def Exercise_9_1(A, B):
	print("A + A:")
	C = A + A
	print(C)
	print("AA^:")
	print(np.dot(A, A.T))
	print("A^A:")
	print(np.dot(A.T, A))
	print("AB:")
	print(np.dot(A, B))
	func_lambda(A, B, 2.0);

def func_lambda(A, B, lamda):
	print("A(B - λI):")
	C = B - lamda * (np.eye(m))
	print(np.dot(A, C))


mu, sigma = 0, 1.0
n, m = 200, 500
A = np.random.normal(loc=mu, scale=sigma, size=(n, m))
c = [a for a in range(1, m+1)]
B = toeplitz(c, c)

Exercise_9_1(A, B)

使用np.random.normal来创建一个符合正态分布拟合的随机矩阵A,使用toeplitz来创建一个随机托普利兹矩阵B。

在本题中主要使用np.dot来实现矩阵相乘,使用np.eye来创建对角矩阵

9-2 Solving a linear system

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

import numpy as np
from scipy.linalg import toeplitz

def Exercise_9_2(B, m):
	b = np.ones((m, 1))
	print(np.linalg.solve(B, b))
	
	
mu, sigma = 0, 1.0
n, m = 200, 500
A = np.random.normal(loc=mu, scale=sigma, size=(n, m))
c = [a for a in range(1, m+1)]
B = toeplitz(c, c)

Exercise_9_2(B, m)

矩阵A、B的创建方法同上

在本题中使用np.ones创建向量b,使用np.linalg.solve函数求解线性方程组的解

9-3 Norms

Compute the Frobenius norm of A: kAkF and the innity norm of B: kBk1. Also nd the largest and smallest singular values of B.

import numpy as np
from scipy.linalg import toeplitz

def Exercise_9_3(A, B, n, m):
	A_norm = np.linalg.norm(A, 'fro')
	print("The Frobenius norm of A is ", A_norm)
	B_norm = np.linalg.norm(B, np.inf)
	print("The infinity norm of B is ", B_norm)
	lar_sin = np.linalg.norm(B, 2)
	smal_sin = np.linalg.norm(B, -2)
	print("The largest singular values of B is ", lar_sin)
	print("The smallest singular values of B is ", smal_sin)


mu, sigma = 0, 1.0
n, m = 200, 500
A = np.random.normal(loc=mu, scale=sigma, size=(n, m))
c = [a for a in range(1, m+1)]
B = toeplitz(c, c)

Exercise_9_3(A, B, n, m)

矩阵A、B的创建方法同上

在本题中使用np.linalg.norm来求范数,其中第二个变量为范数类型。(对于范数的概念不是很清楚,在写的时候参考了

https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html)

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
from scipy.linalg import toeplitz
import time

def Exercise_9_4(n):
	Z = np.random.standard_normal((n, n))
	num = 0
	u = np.ones(n)
	v_norm = 0
	v = np.zeros(n)
	
	begin = time.clock()
	while(True):
		v = np.dot(Z, u)
		v_norm_temp = v_norm
		v_norm = np.linalg.norm(v)
		u = v / v_norm
		num += 1
		if(abs(v_norm_temp - v_norm) < 0.0001):
			break;
	end = time.clock()
	
	print("the largest eigenvalue:", v_norm)
	print("the corresponding eigenvector:", u)
	print("The number of iterations:", num)
	print("computation time when varying n:", end-begin)


mu, sigma = 0, 1.0
n, m = 200, 500
A = np.random.normal(loc=mu, scale=sigma, size=(n, m))
c = [a for a in range(1, m+1)]
B = toeplitz(c, c)

Exercise_9_4(n)

在本题中使用np.random.standard_normal来创建符合高斯分布的矩阵,使用下面所示的幂迭代的方法来求最大特征值和对应的特征向量。(由于对幂迭代不是很熟悉,在写的过程中参考了很多网上的资料和代码)

高级编程技术第十五次作业

9-5 Singular values

Generate an nn 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
from scipy.linalg import toeplitz

def Exercise_9_5(n):
	p = 0.5
	C = np.random. binomial(1, p, (n, n))
	lar_sin = np.linalg.norm(C, 2)
	smal_sin = np.linalg.norm(C, -2)
	print("the smallest singular:", smal_sin)
	print("the largest singular:", lar_sin)
	print("n * p:", n*p)


mu, sigma = 0, 1.0
n, m = 200, 500
A = np.random.normal(loc=mu, scale=sigma, size=(n, m))
c = [a for a in range(1, m+1)]
B = toeplitz(c, c)

Exercise_9_5(n)

使用np.random. binomial来创建符合二项分布的矩阵,使用np.linalg.norm来计算奇异值,通过计算n乘p发现n乘p的值就是最大奇异值

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
from scipy.linalg import toeplitz

def Exercise_9_6(A):
	z = 0
	closest = fun_closest(A, z)
	print("Tthe closest value is ", closest)
	
def fun_closest(A, z):
	B = A[A > z]
	C = A[A <= z]
	_min = np.argmin(B)
	_max = np.argmax(C)
	if abs(z-B[_min]) < abs(z-C[_max]):
		return B[_min]
	else:
		return C[_max]


mu, sigma = 0, 1.0
n, m = 200, 500
A = np.random.normal(loc=mu, scale=sigma, size=(n, m))
c = [a for a in range(1, m+1)]
B = toeplitz(c, c)

Exercise_9_6(A)

这道题的思路是,新建两个矩阵B和C,B是A中比z大的数组合成的新矩阵,C是A中小于等于z 的值组合的新矩阵。要求和z最近的数,一定在B的最小值和C中的最大值这两个数中,所以只需计算这两个数谁离z最近即可

总结:总体来讲这六道题不是很简单,主要是一些关于矩阵的知识不是很了解,需要在网上找资料来学习这些知识。但是通过这几道题也能体会到numpy库的好用之处,一些例如求解线性方程组、求最大特征值等矩阵中的计算,都可以通过很短的代码来实现,这也充分体现出python在数据处理方面的强大之处。

存在的不足:在这次作业中还是有很多地方不是很了解,如范数的概念、幂迭代的实现等,好多地方都直接使用了网上的代码,在后续的学习中还是要多联系,加强对这些知识的掌握。