Numpy Exercises

本文通过多个练习探讨了矩阵运算的基本概念和技术,包括矩阵加法、乘法、求解线性方程组、计算范数、奇异值分解、幂迭代法及最近邻查找等。此外还讨论了这些操作在不同条件下的应用效果。
部署运行你感兴趣的模型镜像

Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A ∈Rn×m and B ∈Rm×m, for n = 200, m = 500.
Exercise 9.1: Matrix operations Calculate A + A, AA>,A>A and AB. Write a function that computes A(B−λI) for any λ. 

#9.1
def computes(A, B, arg):
	return np.dot(A, B - np.dot(arg, np.eye(np.size(B,0),np.size(B,1))))


A = np.random.normal(0, 1, (200, 500))
B = toeplitz(np.random.random(500))

AaddA = A + A
np.savetxt('AaddA.txt', AaddA)
AAT = np.dot(A, A.T)
np.savetxt('AAT.txt', AaddA)
ATA = np.dot(A.T, A)
np.savetxt('ATA.txt', AaddA)
AB = np.dot(A, B)
np.savetxt('AB.txt', AaddA)

print("Solving A(B−λI)")
arg = float(input('Input the λ:'))
exp = computes(A, B, arg)
np.savetxt('exp.txt', exp)

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

#9.2
b = np.random.random(500)
x = np.linalg.solve(B, b)
print("Solving B * x = b")
print("Residual: ", np.linalg.norm((np.dot(B, x) - b), ord = 2))

Exercise 9.3: Norms Compute the Frobenius norm of A: kAkF and the infinity norm of B: kBk∞. Also find the largest and smallest singular values of B.

#9.3
print("Frobenius norm of A:", np.linalg.norm(A, ord = 'fro'))
print("infinity norm of B:", np.linalg.norm(B, ord = np.inf))
print("The smallest singular of B:", min(np.linalg.svd(B, True, False)))


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.

#9.4
import time
def power_iteration(A):
	u = np.random.rand(A.shape[1])
	num_simulations = 0;

	while True:
		old = u[:]
		v = np.dot(A, u)
		arg = max(v) if max(v) + min(v) < 0 else min(v)
		u = v / arg
		num_simulations += 1
		if np.linalg.norm(u - old, ord = np.inf) < 10 ** (-6) or num_simulations >= 10 ** 4:
			break
	return u, arg, num_simulations

n = 100
Z = np.random.normal(0, 1, (n, n))
t1 = time.clock()
v, arg, num_simulations = power_iteration(Z)
t2 = time.clock()
print("simulations:",num_simulations, "Clock:", t2-t1, "Lambda:", arg)

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?

#9.5
'''
计算后发现最大的奇异值接近n*p
'''
from scipy.linalg import svd

for p in range(100):
	n = 100
	p = p / 100
	C = np.random.binomial(1, p, (n,n))
	U, s, Vh = svd(C)
	print(max(s))

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.

#9.6
def closest(z, A):
	return A[np.fabs(A - z).argmin()]

z = 3
A = np.random.random(10) * 10
print (closest(z, A))

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值