Pytorch的基础操作
定义常量与变量
1.torch.tensor()
torch.tensor
是 PyTorch 中创建张量的常用方法,它可以从 Python 的列表、元组或其他类型的数据结构创建一个新的张量。张量是多维数组,在深度学习中用于存储和操作数据。在PyTorch中,常量可以通过直接赋值来定义,而变量则通过
torch.tensor
或torch.Tensor
来创建。torch.tensor
是推荐的方式,因为它会自动推断数据类型。import torch # 定义常量 constant = 5 # 定义变量 variable = torch.tensor([1, 2, 3]) # 创建一个一维张量 tensor1 = torch.tensor([1, 2, 3, 4]) print(tensor1) # 创建一个二维张量 tensor2 = torch.tensor([[1, 2], [3, 4]]) print(tensor2)
PyTorch 中张量操作的一些基本API
1. 创建张量(Tensor Creation)
torch.tensor(data)
:从数据创建张量。x = torch.tensor([1, 2, 3])
torch.zeros(size)
:创建一个指定形状的全零张量。x = torch.zeros(2, 3) # 2x3的全零张量
torch.ones(size)
:创建一个指定形状的全一张量。x = torch.ones(2, 3) # 2x3的全一张量
torch.rand(size)
:创建一个指定形状的张量,元素值在[0, 1)之间均匀分布。x = torch.rand(2, 3)
torch.randn(size)
:创建一个指定形状的张量,元素值符合标准正态分布(均值为0,方差为1)。x = torch.randn(2, 3)
2. 查看和操作张量形状
x.size()
或x.shape
:返回张量的形状。x = torch.randn(2, 3) print(x.size()) # 输出:torch.Size([2, 3])
x.view(new_shape)
:改变张量的形状(类似 NumPy 的reshape
)。 注意事项:view() 返回一个新的张量,原张量不会被修改。
view() 必须保持元素总数不变,即重塑后的张量和原张量的元素总数必须相等。
如果你不确定某一维度的大小,可以使用 -1 作为占位符,让 PyTorch 自动推算出
x = torch.randn(2, 3) #三种都一个意思 y = x.view(3, 2) # 变换形状 y = x.view(3, -1) # 变换形状 y = x.view(-1, 2) # 变换形状
x.transpose(0, 1)
:交换张量的维度。(大部分用于二维数组)x = torch.randn(2, 3) y = x.transpose(0, 1) # 交换维度
torch.permute(*dims):张量的矩阵转置(高维度) 可以接受多个维度索引 *
dims
是一个包含所有维度新顺序的整数序列。import torch # 创建一个形状为 (2, 3, 4) 的 3D 张量 x = torch.randn(2, 3, 4) # 重新排列维度顺序为 (2, 0, 1) y = x.permute(2, 0, 1) print(x.shape) # 输出: torch.Size([2, 3, 4]) print(y.shape) # 输出: torch.Size([4, 2, 3])
Tensor与numpy的相互转换
PyTorch的Tensor可以与NumPy数组相互转换。使用
numpy()
方法将Tensor转换为NumPy数组,使用torch.from_numpy()
将NumPy数组转换为Tensor。import numpy as np # Tensor转NumPy tensor = torch.tensor([1, 2, 3]) numpy_array = tensor.numpy() # NumPy转Tensor numpy_array = np.array([1, 2, 3]) tensor = torch.from_numpy(numpy_array)
reshape与最大值索引
reshape
用于改变Tensor的形状,argmax
用于获取最大值的索引。tensor = torch.tensor([[1, 2, 3], [4, 5, 6]]) # reshape reshaped_tensor = tensor.reshape(3, 2) # 最大值索引 max_index = torch.argmax(tensor)
随机数据生成
PyTorch提供了多种生成随机数据的方法,如
torch.rand
、torch.randn
、torch.randint
等。# 生成0到1之间的随机数 random_tensor = torch.rand(2, 3) # 生成标准正态分布的随机数 normal_tensor = torch.randn(2, 3) # 生成指定范围的随机整数 int_tensor = torch.randint(0, 10, (2, 3))
基本算数操作
PyTorch支持基本的算数操作,如加法、减法、乘法、除法等。
import torch as t a = t.tensor([1, 2, 3]) b = t.tensor([4, 5, 6]) # 加法 c = a + b # 乘法 d = a * b print(c) #输出 tensor([5, 7, 9]) print(d) #输出 tensor([ 4, 10, 18])
基本卷积操作
卷积操作是深度学习中常用的操作,PyTorch提供了
torch.nn.functional.conv2d
来实现卷积。import torch.nn.functional as F # 输入和卷积核 input = torch.randn(1, 1, 5, 5) kernel = torch.randn(1, 1, 3, 3) # 卷积操作 output = F.conv2d(input, kernel)
GPU检测与支持
PyTorch支持GPU加速,可以通过
torch.cuda.is_available()
检测是否有可用的GPU,并使用to('cuda')
将Tensor移动到GPU上。# 检测GPU是否可用 if torch.cuda.is_available(): device = torch.device('cuda') else: device = torch.device('cpu') # 将Tensor移动到GPU tensor = torch.tensor([1, 2, 3]).to(device)
网格化与cat
torch.meshgrid
用于生成网格坐标,torch.cat
用于沿指定维度拼接Tensor。# 生成网格坐标 x = torch.tensor([1, 2, 3]) y = torch.tensor([4, 5, 6]) grid_x, grid_y = torch.meshgrid(x, y) # 拼接Tensor a = torch.tensor([[1, 2], [3, 4]]) b = torch.tensor([[5, 6], [7, 8]]) c = torch.cat((a, b), dim=0)