Numpy

Numpy Exercises

这里写图片描述

注:为方便测试,在测试过程中,以下程序生成的矩阵均采用较小的维度

Exercise 9.1: Matrix operations

import numpy as np
from scipy.linalg import toeplitz
import random

n = 200
m = 500

def MyPrint(ans):
    print (ans)
    print ("")

def CalculateAnswer(A, B):
    """Do calculation"""
    ans1 = A + A
    print ("A + A")
    MyPrint(ans1)

    ans2 = A.dot(A.T)
    print ("A * A.T")
    MyPrint(ans2)

    ans3 = (A.T).dot(A)
    print ("A.T * A")
    MyPrint(ans3)

    ans4 = A.dot(B)
    print ("A * B")
    MyPrint(ans4)

    I = np.identity(m)
    k = int(input("Input any λ for A(B − λI)\n"))
    ans5 = A.dot(B - k * I)
    print ("A * (B - kI)")
    MyPrint(ans5)

# Generate matrix A with random Gaussian entries
A = np.random.normal(0, 1, n * m).reshape(n, m)
print ("Matrix A")
MyPrint(A)

# Generate Toeplitz matrix B
B_data_col = []
B_data_row = []
for i in range(0, m):
    rand = random.randint(1, m)
    B_data_col.append(rand)
    rand = random.randint(1, m)
    B_data_row.append(rand)
B = toeplitz(B_data_col, B_data_row)
print ("Matrix B")
MyPrint(B)

# Another method to generate toeplitz matrix
# B = np.zeros((m, m))
# i, j = np.indices(B.shape)
# for index in range(-m + 1, m):
#   B[i == j + index] = random.randint(1, m)
# print ("Matrix B")
# MyPrint(B)

CalculateAnswer(A, B)

Test Exercise 9.1

这里写图片描述

Exercise 9.2: Solving a linear system

import numpy as np
from scipy.linalg import toeplitz
import random

m = 500

def MyPrint(ans):
    print (ans)
    print ("")

def CalculateAnswer(B):
    """Bx = b"""
    arr = []
    for i in range(0, m):
        rand = random.randint(1, m)
        arr.append(rand)
    b = np.array(arr)
    print ("b")
    MyPrint (b)

    x = np.linalg.solve(B, b)
    print ("x")
    MyPrint (x)

# Generate Toeplitz matrix B
B_data_col = []
B_data_row = []
for i in range(0, m):
    rand = random.randint(1, m)
    B_data_col.append(rand)
    rand = random.randint(1, m)
    B_data_row.append(rand)
B = toeplitz(B_data_col, B_data_row)
print ("Matrix B")
MyPrint(B)

CalculateAnswer(B)

Test Exercise 9.2

这里写图片描述

Exercise 9.3: Norms

import numpy as np
from scipy.linalg import toeplitz
import random

n = 200
m = 500

def MyPrint(ans):
    print (ans)
    print ("")

def CalculateAnswer(A ,B):
    """Compute the Frobenius norm of A and the infinity norm of B"""
    print ("the Frobenius norm of A")
    MyPrint(np.linalg.norm(A))

    print ("the Infinity norm of B")
    MyPrint(np.linalg.norm(B, np.inf))

    print ("largest and smallest singular values of B")
    U, sigma, VT = np.linalg.svd(B)
    print ("largest value", max(sigma))
    print ("smallest value", min(sigma))

# Generate matrix A with random Gaussian entries
A = np.random.normal(0, 1, n * m).reshape(n, m)
print ("Matrix A")
MyPrint(A)

# Generate Toeplitz matrix B
B_data_col = []
B_data_row = []
for i in range(0, m):
    rand = random.randint(1, m)
    B_data_col.append(rand)
    rand = random.randint(1, m)
    B_data_row.append(rand)
B = toeplitz(B_data_col, B_data_row)
print ("Matrix B")
MyPrint(B)

CalculateAnswer(A, B)

Test Exercise 9.3

这里写图片描述

Exercise 9.4: Power iteration

import numpy as np
import time

n = 3

def eigenvalue(Z, v):
    Zv = Z.dot(v)
    return v.dot(Zv)

def power_iteration(Z):
    n, d = Z.shape
    v = np.ones(d) / np.sqrt(d)
    ev = eigenvalue(Z, v)
    iteration_count = 0

    while True:
        iteration_count += 1
        Zv = Z.dot(v)
        v_new = Zv / np.linalg.norm(Zv)
        ev_new = eigenvalue(Z, v_new)
        if np.abs(ev - ev_new) < 0.01:
            break
        v = v_new
        ev = ev_new

    return ev_new, v_new, iteration_count

Z = np.random.normal(10, 10, n * n).reshape(n, n)
print ("Matrix Z")
print (Z)
print ("")

t_prev = time.clock()
eigenvalue, eigenvector, iteration_count = power_iteration(Z)
t = time.clock()

print ("Eigenvalue:", eigenvalue)
print ("Eigenvector:", eigenvector)
print ("Iteration count:", iteration_count)
print ("Time cost:", t - t_prev)

Test Exercise 9.4

这里写图片描述

Exercise 9.5: Singular values

import numpy as np
from scipy import linalg
import random

n = 200
p = 1 / 3

def MyPrint(ans):
    print (ans)
    print ("")

def random_pick():
    """Generate a random number dependent on p"""
    x = random.uniform(0, 1)
    cumulative_probability = 0.0
    for item, item_probability in zip([1, 0], [p, 1 - p]):
        cumulative_probability += item_probability
        if x < cumulative_probability: break
    return item

def CalculateAnswer(C):
    """Compute the singular values of C"""
    U, s, Vh = linalg.svd(C)
    print ("singular values")
    MyPrint(s)
    print ("max singular value", max(s))
    print ("Conclusion: max singular value nearly equals to n * p")

# Generate matrix C with entry 1 and 0
C_data = []
for i in range(0, n * n):
    C_data.append(random_pick())
C = np.reshape(C_data, (n, n))
print ("Matric C")
MyPrint(C)

CalculateAnswer(C)

Test Exercise 9.5

这里写图片描述

Exercise 9.6: Nearest neighbor

import numpy as np
import random

n = 100         # 数组大小100
m = 500         # 数组元素范围1-500

def Myprint(ans):
    print (ans)
    print ("")

A = []
for i in range(0, n):
    A_data = random.randint(1, m)
    A.append(A_data)
A = np.array(A)
print ("Array A")
Myprint(A)

z = random.randint(1, m)
print ("Value z =", z)
Z = np.array([z for i in range(0, n)])
A_temp = abs(A - Z)

print ("The element in A that is closet to z:", A[np.argmin(A_temp)])

Test Exercise 9.6

这里写图片描述

提供的引用内容中未提及Numpy桥的相关信息,不过可以从一般情况介绍Numpy桥。 Numpy桥通常是指在不同系统、框架或者编程语言之间建立起连接,使得它们能够与Numpy进行交互,实现数据的传递和操作。在Python生态系统中,Numpy是一个用于高效数值计算的基础库,很多机器学习框架、数据分析工具等都依赖于Numpy进行数组操作。 ### 介绍 Numpy桥是一种机制或者接口,它允许其他系统或者框架利用Numpy的功能。例如,在深度学习框架中,如TensorFlow、PyTorch等,Numpy桥可以让这些框架与Numpy数组进行无缝转换。这意味着可以将Numpy数组传递给深度学习模型进行训练或者推理,也可以将模型的输出转换回Numpy数组进行后续的分析。 ### 用途 - **数据交换**:方便不同工具之间的数据传递。比如在数据分析阶段使用Pandas处理数据,Pandas底层依赖Numpy数组,通过Numpy桥可以将处理好的数据传递给机器学习模型进行训练。 ```python import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression # 创建一个Pandas DataFrame data = {'x': [1, 2, 3, 4, 5], 'y': [2, 4, 6, 8, 10]} df = pd.DataFrame(data) # 通过Numpy桥将DataFrame转换为Numpy数组 X = df['x'].values.reshape(-1, 1) y = df['y'].values # 使用Numpy数组进行机器学习模型训练 model = LinearRegression() model.fit(X, y) ``` - **代码复用**:可以复用基于Numpy开发的大量数值计算代码。不同的科学计算库可能有不同的数组表示方式,通过Numpy桥可以在不改变原有代码的基础上,将这些库与Numpy集成。 - **性能优化**:Numpy本身经过高度优化,使用Numpy桥可以利用Numpy的高效计算能力,提高整个系统的性能。 ### 相关信息 许多开源项目都提供了与Numpy的桥接功能。例如,在Python中,像Scikit - learn、Matplotlib等库都可以直接使用Numpy数组作为输入。在其他编程语言中,也有一些工具可以实现与Numpy的交互,如R语言中的reticulate包可以在R环境中调用Python的Numpy库。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值