class CardiacDetectionModel(pl.LightningModule):
def init(self):
super().init()self.model = torchvision.models.resnet18(pretrained=True) self.model.conv1 = torch.nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) self.model.fc = torch.nn.Linear(in_features=512 ,out_features=4) self.optimizer = torch.optim.Adam(self.model.parameters(), lr=1e-4) self.loss_fn = torch.nn.MSELoss() def forward(self, data): return self.model(data) def training_step(self, batch, batch_idx): x_ray, label = batch label = label.float() pred = self(x_ray) loss = self.loss_fn(pred, label) self.log("Train Loss", loss) if batch_idx % 50 == 0: self.log_images(x_ray.cpu(), pred.cpu(), label.cpu(), "Train") return loss def validation_step(self, batch, batch_idx): x_ray, label = batch label = label.float() pred = self(x_ray) loss = self.loss_fn(pred, label) self.log("Val Loss", loss) if batch_idx % 50 == 0: self.log_images(x_ray.cpu(), pred.cpu(), label.cpu(), "Val") return loss def log_images(self, x_ray, pred, label, name): results = [] for i in range(4): coords_labels = label[i] coords_pred = pred[i] img = ((x_ray[i] * 0.252)+0.494).numpy()[0] x0, y0 = coords_labels[0].int().item(), coords_labels[1].int().item() x1, y1 = coords_labels[2].int().item(), coords_labels[3].int().item() img = cv2.rectangle(img, (x0, y0), (x1, y1), (0, 0, 0), 2) x0, y0 = coords_pred[0].int().item(), coords_pred[1].int().item() x1, y1 = coords_pred[2].int().item(), coords_pred[3].int().item() img = cv2.rectangle(img, (x0, y0), (x1, y1), (1, 1, 1), 2) results.append(torch.tensor(img).unsqueeze(0)) grid = torchvision.utils.make_grid(results, 2) self.logger.experiment.add_image(name, grid, self.global_step) def configure_optimizers(self): #注意してください ここでは必ずリストを返す必要があります(オプティマイザーを1つにまとめるだけです :) return [self.optimizer]
モデルオブジェクトの作成
model = CardiacDetectionModel() # モデルをインスタンシエートする
When instantiating the model, if I use google colab, there is no error, but if I use kaggle’s kernel, there is an error.