numpy练习

本文通过多个实例演示了如何利用Python进行矩阵运算,包括基本操作、求解线性方程组、计算范数等,并介绍了幂迭代法寻找最大特征值及奇异值分解的应用。

先生成A,B矩阵,令n,m分别为200,500

import numpy
from scipy.linalg import toeplitz
A = numpy.random.normal(size=(200, 500))
B = toeplitz(range(1, 501))
Exercise 9.1: Matrix operations 

Calculate A + A, A·AT, AT·A and A·B. Write a function that computes A(B − λI) for any λ. 

answer1 = numpy.add(A, A)
answer2 = numpy.dot(A, A.T)
answer3 = numpy.dot(A.T, A)
answer4 = numpy.dot(A, B)


def compute(A, B, r):
    return (A.dot(B - r * numpy.eye(len(B)))) # 以B的维数生成一个单位矩阵

Ex 9-2 Solving a linear system

solution = np.linalg.solve(matrix_b, vector_b)
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.


frobenius_norm_A = np.linalg.norm(matrix_a, 'fro')


infinity_norm_B = np.linalg.norm(matrix_b, np.inf)

#b的最大最小值
max_element_of_B = matrix_b.max()
min_element_of_B = matrix_b.min()
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.


def powerIter(Z, e):
    b_k = numpy.asmatrix(numpy.random.rand(Z.shape[1])).T
    b_k_bak = b_k
    iteration = 0
    start_time = time.clock()
    while iteration == 0 or abs(numpy.linalg.norm(b_k - b_k_bak)) >= e:
        b_k1 = numpy.dot(Z, b_k)
        b_k1_norm = numpy.linalg.norm(b_k1)
        b_k_bak = b_k
        b_k = b_k1 / b_k1_norm
        iteration += 1
    end_time = time.clock()
    print("iteration = ", iteration, end='')
    print(", time = ", end_time - start_time, "s.")
    return b_k

Z = numpy.asmatrix(numpy.random.random_integers(1, 100, size=(500, 500)))
print(powerIter(Z, 10e-5))

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?


numpy实际上提供了svd函数来计算奇异值,故使用它测试

import numpy as np
def generate_matrix(row,col,p):
    re = np.ones((row,col))
    for i in range(row):
        for j in range(col):
            if np.random.rand() < p :
                re[i][j] =1
            else:
                re[i][j] = 0
    return re


for n in [100,200,300,400,500]:
    for p in [0.1,0.2,0.5,0.8]:
        C = generate_matrix(n, n, p)
        u, s, vh = np.linalg.svd(C)
        max_singular_value = np.max(s)
        print('n:', n, '  p:', p, '  s:', max_singular_value, '\n')

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.

mport numpy as np

n=200

def find_closest(A, z):
    C = np.abs(A - z)
    idx = np.argmin(C)
    return A[idx // A.shape[0]][idx % A.shape[0]]


A = np.random.rand(n, n)
print(A)
print(find_closest(A, 1)) 


### NumPy 练习题及答案 #### 打印当前 Numpy 版本 为了确认安装的 NumPy 库版本,可以使用如下代码: ```python import numpy as np print(np.__version__) ``` 这段代码会输出当前环境中所使用的 NumPy 的具体版本号[^1]。 #### 获取特定范围内的数组元素 对于获取一个一维数组中满足条件的子集操作,可以通过布尔索引来实现。下面的例子展示了如何选取介于5到10之间的数值(包括边界值): ```python array = np.arange(15) nums = array[(array >= 5) & (array <= 10)] ``` 这里创建了一个包含从0至14共15个连续整数的一维数组,并从中筛选出了大于等于5且小于等于10的所有元素[^2]。 #### 在二维数组中随机放置指定数量的元素 当需要在一个已知大小的二维矩阵里随机分布若干个相同或不同的值时,可采用以下函数来完成这一任务: ```python def place_elements_randomly(shape, p, value=1): ''' 在给定形状的2D数组中随机放置p个元素,默认为1 参数说明: shape: 一个元组,指定了2D数组的尺寸; p: 整数,表示要放置的元素数目; value: 要填充的目标值,缺省情况下设为1. 返回值: 修改过的2D数组对象. ''' arr = np.zeros(shape, dtype=int) all_positions = np.arange(arr.size) chosen_positions = np.random.choice(all_positions, p, replace=False) np.put(arr, chosen_positions, value) return arr ``` 此方法接收三个参数:目标数组的维度`shape`,待插入项的数量`p`以及这些项目的实际取值`value`(如果未特别指出则默认设置成1),最终返回经过更新处理的新版二维数组实例[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值