【Pytorch】NameError: name ‘Variable‘ is not defined

时间:2024-04-30 07:09:56

报错


NameError                                 Traceback (most recent call last)
Cell In[20], line 4
      2 for epoch in range(num_epochs):
      3     if torch.cuda.is_available():
----> 4         inputs = Variable(x_train).cuda()
      5         target = Variable(y_train).cuda()
      6     else:

NameError: name 'Variable' is not defined

解答

在PyTorch中,Variable类在较早的版本中用于包装张量,但从PyTorch 0.4版本开始,推荐使用torch.Tensortorch.autograd.Variable。在PyTorch 0.4版本之后,Variable类已经被torch.Tensor类取代,并且在较新的版本中已经被弃用。

import torch
import torch.nn as nn
import torch.optim as optim

# 假设你已经定义了模型和优化器
# model = ...
# optimizer = ...

# 假设x_train和y_train是已经准备好的训练数据
# x_train = ...
# y_train = ...

# 将数据转换为torch.Tensor
x_train_tensor = torch.tensor(x_train, dtype=torch.float32)
y_train_tensor = torch.tensor(y_train, dtype=torch.float32)

# 检查是否有可用的GPU,并将张量移动到GPU上
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x_train_tensor = x_train_tensor.to(device)
y_train_tensor = y_train_tensor.to(device)

# 现在你可以使用x_train_tensor和y_train_tensor作为模型的输入
# 例如,在训练循环中:
# for epoch in range(num_epochs):
#     optimizer.zero_grad()
#     outputs = model(x_train_tensor)
#     loss = criterion(outputs, y_train_tensor)
#     loss.backward()
#     optimizer.step()

在这个修改后的代码中,使用torch.tensor来创建张量。