深度学习中的变量类型——torch.Tensor和torch.Variable

发布时间:2023-05-18

一、torch.Tensor

torch.Tensor是PyTorch中表示张量的基础数据类型,也是PyTorch中最常用的数据类型之一。它是一个多维数组,而且可以在CPU或GPU内存中存储数据。 定义一个Tensor可以通过torch.Tensor函数或者torch.tensor函数,参数可以是list、tuple、ndarray或者标量。

import torch
a = torch.Tensor([1,2,3])
b = torch.tensor([[1, 2], [3, 4]])
c = torch.tensor(3)

Tensor的属性包括shapedtypedevicelayout等,可以通过这些属性对tensor进行操作。

print(a.shape)   #(3,)
print(b.dtype)   #torch.int64
print(c.device)  #cpu
a = a.to('cuda') #将a放到GPU上

二、torch.autograd.Variable与torch.Tensor的关系

在PyTorch 0.4版本之前,Variable是PyTorch中的一个重要组成部分,主要是为了方便定义需要求导的计算图,通过Variable记录Tensor的历史版本,从而支持反向传播计算梯度。 而从PyTorch 0.4版本开始,Variable被整合到了Tensor中,新版本中,用户可以使用requires_grad参数在创建Tensor时决定是否需要求导。

a = torch.tensor([1,2,3], requires_grad=True)
b = torch.tensor([4,5,6], requires_grad=True)
c = a + b
d = c.mean()
d.backward()
print(a.grad)
print(b.grad)

三、torch.nn.Parameter

torch.nn.Parameter是一种特殊的Tensor,它被设置为一个模型的可学习参数。与普通的Tensor不同,在计算图的生成中它是存在于nn.Module中的,并且默认有requires_grad=True属性。 创建一个nn.Parameter时,需要指定形状。通常在模型定义中调用这个函数创建需要学习的参数,例如权重和偏差。

import torch.nn as nn
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.weight = nn.Parameter(torch.randn(3, 5))
        self.bias = nn.Parameter(torch.zeros(3))
    def forward(self, x):
        return torch.mm(x, self.weight) + self.bias
net = Net()
print(net)

四、总结

本文主要介绍了在PyTorch中三种重要的变量类型:torch.Tensortorch.autograd.Variabletorch.nn.Parameter。Tensor是PyTorch中的基础数值类型,可以在CPU或GPU上存储数据;Variable是Tensor的历史版本,在0.4版本之后被整合到Tensor中,需要使用requires_grad属性来决定是否需要求导;Parameter是一种特殊的Tensor,是nn.Module中的可学习参数,通常在模型定义中被使用。