让 RESNet18 处理 float32 数据

Getting RESNet18 to work with float32 data

我有 float32 数据,我正试图让 RESNet18 使用这些数据。我在 torchvision 中使用 RESNet 模型(并使用 pytorch lightning)并将其修改为使用一层(灰度)数据,如下所示:

class ResNetMSTAR(pl.LightningModule):
def __init__(self):
  super().__init__()
  # define model and loss
  self.model = resnet18(num_classes=3)
  self.model.conv1 = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
  self.loss = nn.CrossEntropyLoss()

@auto_move_data # this decorator automatically handles moving your tensors to GPU if required
def forward(self, x):
return self.model(x)

def training_step(self, batch, batch_no):
  # implement single training step
  x, y = batch
  logits = self(x)
  loss = self.loss(logits, y)
  return loss

def configure_optimizers(self):
  # choose your optimizer
  return torch.optim.RMSprop(self.parameters(), lr=0.005)

当我尝试 运行 这个模型时,我收到以下错误:

File "/usr/local/lib64/python3.6/site-packages/torch/nn/functional.py", line 2824, in cross_entropy
    return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target' in call to _thnn_nll_loss_forward

有什么我可以做的不同的事情来防止这个错误发生吗?

问题是 y 你输入的交叉熵损失不是 LongTensor,而是 FloatTensor。 CrossEntropy 期望为目标输入 LongTensor,并引发错误。

这是一个丑陋的修复:

x, y = batch
y = y.long()

但我建议你去定义数据集的地方,并确保你正在生成长目标,这样如果你改变你的训练循环的工作方式,你就不会重现这个错误。