PyTorch 神经网络基础:Torch 与 NumPy 的高效转换与运算

本文简要介绍了 PyTorch 与 NumPy 在数据转换与数学运算中的具体应用,涵盖两者之间的数据互相转换、常见数学运算(如绝对值、三角函数、均值计算)以及矩阵点乘等操作。通过示例代码,清晰展示了 PyTorch 与 NumPy 在实现同类操作时的异同之处,为理解与使用 PyTorch 提供了基础指导。这些操作广泛应用于机器学习和深度学习的预处理中,有助于读者快速上手并高效利用 PyTorch。

一 导入依赖

import torch
import numpy as np  # 导入 NumPy 库

二 NumPy 和 Torch 互相转换

np_data = np.arange(6).reshape((2, 3))  # 创建一个 2x3 的 NumPy 数组
torch_data = torch.from_numpy(np_data)  # 将 NumPy 数组转换为 Torch 张量
tensor2array = torch_data.numpy()  # 将 Torch 张量转换回 NumPy 数组
print(
    '\nnumpy array:', np_data,  # NumPy 数组内容: [[0 1 2], [3 4 5]]
    '\ntorch tensor:', torch_data,  # Torch 张量内容: 0  1  2 \n 3  4  5    [torch.LongTensor of size 2x3]
    '\ntensor to array:', tensor2array,  # 转换回的 NumPy 数组内容: [[0 1 2], [3 4 5]]
)

三 Torch 中的数学运算

# abs 绝对值计算
data = [-1, -2, 1, 2]  # 输入数据
tensor = torch.FloatTensor(data)  # 转换成 32 位浮点张量
print(
    '\nabs',
    '\nnumpy: ', np.abs(data),  # NumPy 计算绝对值结果: [1 2 1 2]
    '\ntorch: ', torch.abs(tensor)  # Torch 计算绝对值结果: [1 2 1 2]
)

# sin 三角函数 sin
print(
    '\nsin',
    '\nnumpy: ', np.sin(data),  # NumPy 计算正弦值结果: [-0.84147098 -0.90929743  0.84147098  0.90929743]
    '\ntorch: ', torch.sin(tensor)  # Torch 计算正弦值结果: [-0.8415 -0.9093  0.8415  0.9093]
)

# mean 均值
print(
    '\nmean',
    '\nnumpy: ', np.mean(data),  # NumPy 计算均值结果: 0.0
    '\ntorch: ', torch.mean(tensor)  # Torch 计算均值结果: 0.0
)

更多详情请参阅 PyTorch 官方文档

四 矩阵乘法

# 矩阵运算
# matrix multiplication 矩阵点乘
data = [[1, 2], [3, 4]]  # 输入矩阵
tensor = torch.FloatTensor(data)  # 转换成 32 位浮点张量
print(
    '\nmatrix multiplication (matmul)',
    '\nnumpy: ', np.matmul(data, data),  # NumPy 计算矩阵点乘结果: [[7, 10], [15, 22]]
    '\ntorch: ', torch.mm(tensor, tensor)  # Torch 计算矩阵点乘结果: [[7, 10], [15, 22]]
)

五 完整代码示例

# This is a sample Python script.

# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
import torch
import numpy as np


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press ⌘F8 to toggle the breakpoint.

    # 用 Numpy 还是 Torch
    np_data = np.arange(6).reshape((2, 3))  # 创建一个 2x3 的 NumPy 数组
    torch_data = torch.from_numpy(np_data)  # 将 NumPy 数组转换为 Torch 张量
    tensor2array = torch_data.numpy()  # 将 Torch 张量转换回 NumPy 数组
    print(
        '\nnumpy array:', np_data,  # NumPy 数组内容: [[0 1 2], [3 4 5]]
        '\ntorch tensor:', torch_data,  # Torch 张量内容: 0  1  2 \n 3  4  5    [torch.LongTensor of size 2x3]
        '\ntensor to array:', tensor2array,  # 转换回的 NumPy 数组内容: [[0 1 2], [3 4 5]]
    )

    # Torch 中的数学运算
    # abs 绝对值计算
    data = [-1, -2, 1, 2]  # 输入数据
    tensor = torch.FloatTensor(data)  # 转换成 32 位浮点张量
    print(
        '\nabs',
        '\nnumpy: ', np.abs(data),  # NumPy 计算绝对值结果: [1 2 1 2]
        '\ntorch: ', torch.abs(tensor)  # Torch 计算绝对值结果: [1 2 1 2]
    )

    # sin 三角函数 sin
    print(
        '\nsin',
        '\nnumpy: ', np.sin(data),  # NumPy 计算正弦值结果: [-0.84147098 -0.90929743  0.84147098  0.90929743]
        '\ntorch: ', torch.sin(tensor)  # Torch 计算正弦值结果: [-0.8415 -0.9093  0.8415  0.9093]
    )

    # mean 均值
    print(
        '\nmean',
        '\nnumpy: ', np.mean(data),  # NumPy 计算均值结果: 0.0
        '\ntorch: ', torch.mean(tensor)  # Torch 计算均值结果: 0.0
    )

    # 矩阵运算
    # matrix multiplication 矩阵乘法
    data = [[1, 2], [3, 4]]  # 输入矩阵
    tensor = torch.FloatTensor(data)  # 转换成 32 位浮点张量
    print(
        '\nmatrix multiplication (matmul)',
        '\nnumpy: ', np.matmul(data, data),  # NumPy 计算矩阵乘法结果: [[7, 10], [15, 22]]
        '\ntorch: ', torch.mm(tensor, tensor)  # Torch 计算矩阵乘法结果: [[7, 10], [15, 22]]
    )


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('Torch 或 NumPy')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/

复制粘贴并覆盖到你的 main.py 中运行,运行结果如下。

Hi, Torch 或 NumPy

numpy array: [[0 1 2]
 [3 4 5]] 
torch tensor: tensor([[0, 1, 2],
        [3, 4, 5]]) 
tensor to array: [[0 1 2]
 [3 4 5]]

abs 
numpy:  [1 2 1 2] 
torch:  tensor([1., 2., 1., 2.])

sin 
numpy:  [-0.84147098 -0.90929743  0.84147098  0.90929743] 
torch:  tensor([-0.8415, -0.9093,  0.8415,  0.9093])

mean 
numpy:  0.0 
torch:  tensor(0.)

matrix multiplication (matmul) 
numpy:  [[ 7 10]
 [15 22]] 
torch:  tensor([[ 7., 10.],
        [15., 22.]])

六 源码地址

代码地址,GitHubTorch 或 Numpy.py

七 参考

[1] PyTorch 官方文档

[2] 莫烦 Python

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐