我已经做了一个简单的pytorch模型,有3个ANN层,它应该采取一批3通道图像,即torch.size(128,3,32,32)。但是在定义模型之后,当我尝试训练已经传递给gpu的train_dataloader时,它显示AttributeError:“list”对象没有属性“flatten”我该怎么办?代码如下:
class ImageClassificationBase(nn.Module):
def training_step(self, batch):
images, labels = batch
predicted_label = self(images)
loss = F.cross_entropy(predicted_label, labels)
return loss
def validation_step(self, batch):
images, labels = batch
predicted_label = self(batch)
loss = F.cross_entropy(predicted_label, labels)
acc = accuracy(predicted_label, labels)
return {'val_loss' : loss.detach(), 'val_acc' : acc}
def validation_epoch_end(self,val_output):
batch_losses = [x['val_loss'] for x in val_output]
epoch_loss = torch.stack(batch_losses).mean()
batch_acc = [x['val_acc'] for x in val_output]
epoch_acc = torch.stack(batch_acc).mean()
return {'val_loss' : epoch_loss.item(), 'val_acc' : epoch_acc.item()}
def epoch_end(self, epoch, result):
print(f"Epoch [{epoch}], val_loss : {result['val_loss']:0.4f}, val_acc : {result['val_acc']:0.4f}")
def evaluate(model, val_dataloader):
outputs = [model.validation_step(batch) for batch in val_dataloader]
return model.validation_epoch_end(outputs)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def to_device(data, device):
if isinstance(data, (list, tuple)):
return [to_device(x, device) for x in data]
return data.to(device, non_blocking = True)
class DeviceDataLoader():
def __init__(self, dataloader, device):
self.dataloader = dataloader
self.device = device
def __iter__(self):
for batch in self.dataloader:
yield to_device(batch, self.device)
def __len__(self):
return len(self.dataloader)
train_loader = DeviceDataLoader(train_dataloader, device)
val_loader = DeviceDataLoader(val_dataloader, device)
test_loader = DeviceDataLoader(test_dataloader, device)
class CIFAR10Model(ImageClassificationBase):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
self.fc1 = nn.Linear(32 * 32 * 3, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, 10)
def forward(self, xb):
x = self.flatten(xb)
x = self.fc1(x)
x = torch.relu(x)
x = self.fc2(x)
x = torch.relu(x)
x = self.fc3(x)
return x
model1 = to_device(CIFAR10Model(), device)
fit(10, 0.01, model, train_loader, val_loader)
字符串
我试着在另一个colab文件上尝试代码,尝试重新启动。但它仍然显示AttributeError:“list”对象没有属性“flatten”
1条答案
按热度按时间h7appiyu1#
没有关于哪一行抛出异常的所有信息,以及模型的输入是什么,我建议将此更改为
字符串
至
型
这将把类型为
list
(或任何类似列表的)的输入转换为torchTensor。