def cassandra_fit(cass_ds, net, epochs=3): cs = 0 # current split = training cass_ds.current_split = cs num_batches = cass_ds.num_batches[cs] # loop through the epochs for e in range(epochs): cass_ds.rewind_splits(cs, shuffle=True) eddl.reset_loss(net) # loop through batches for b in trange(num_batches): x, y = cass_ds.load_batch() x.div_(255.0) tx, ty = [x], [y] eddl.train_batch(net, tx, ty) # print loss eddl.print_loss(net, b) print()
def main(args): num_classes = 1 size = [192, 192] # size of images thresh = 0.5 if args.out_dir: os.makedirs(args.out_dir, exist_ok=True) in_ = eddl.Input([3, size[0], size[1]]) out = SegNet(in_, num_classes) out_sigm = eddl.Sigmoid(out) net = eddl.Model([in_], [out_sigm]) eddl.build(net, eddl.adam(0.0001), ["cross_entropy"], ["mean_squared_error"], eddl.CS_GPU([1]) if args.gpu else eddl.CS_CPU()) eddl.summary(net) eddl.setlogfile(net, "skin_lesion_segmentation") training_augs = ecvl.SequentialAugmentationContainer([ ecvl.AugResizeDim(size), ecvl.AugMirror(0.5), ecvl.AugFlip(0.5), ecvl.AugRotate([-180, 180]), ecvl.AugAdditivePoissonNoise([0, 10]), ecvl.AugGammaContrast([0.5, 1.5]), ecvl.AugGaussianBlur([0, 0.8]), ecvl.AugCoarseDropout([0, 0.3], [0.02, 0.05], 0.5) ]) validation_augs = ecvl.SequentialAugmentationContainer( [ecvl.AugResizeDim(size)]) dataset_augs = ecvl.DatasetAugmentations( [training_augs, validation_augs, None]) print("Reading dataset") d = ecvl.DLDataset(args.in_ds, args.batch_size, dataset_augs) x = Tensor([args.batch_size, d.n_channels_, size[0], size[1]]) y = Tensor([args.batch_size, d.n_channels_gt_, size[0], size[1]]) num_samples_train = len(d.GetSplit()) num_batches_train = num_samples_train // args.batch_size d.SetSplit(ecvl.SplitType.validation) num_samples_validation = len(d.GetSplit()) num_batches_validation = num_samples_validation // args.batch_size indices = list(range(args.batch_size)) evaluator = utils.Evaluator() print("Starting training") for e in range(args.epochs): print("Epoch {:d}/{:d} - Training".format(e + 1, args.epochs), flush=True) d.SetSplit(ecvl.SplitType.training) eddl.reset_loss(net) s = d.GetSplit() random.shuffle(s) d.split_.training_ = s d.ResetAllBatches() for b in range(num_batches_train): print("Epoch {:d}/{:d} (batch {:d}/{:d}) - ".format( e + 1, args.epochs, b + 1, num_batches_train), end="", flush=True) d.LoadBatch(x, y) x.div_(255.0) y.div_(255.0) tx, ty = [x], [y] eddl.train_batch(net, tx, ty, indices) eddl.print_loss(net, b) print() print("Saving weights") eddl.save(net, "isic_segmentation_checkpoint_epoch_%s.bin" % e, "bin") d.SetSplit(ecvl.SplitType.validation) evaluator.ResetEval() print("Epoch %d/%d - Evaluation" % (e + 1, args.epochs), flush=True) for b in range(num_batches_validation): n = 0 print("Epoch {:d}/{:d} (batch {:d}/{:d}) ".format( e + 1, args.epochs, b + 1, num_batches_validation), end="", flush=True) d.LoadBatch(x, y) x.div_(255.0) y.div_(255.0) eddl.forward(net, [x]) output = eddl.getOutput(out_sigm) for k in range(args.batch_size): img = output.select([str(k)]) gt = y.select([str(k)]) img_np = np.array(img, copy=False) gt_np = np.array(gt, copy=False) iou = evaluator.BinaryIoU(img_np, gt_np, thresh=thresh) print("- IoU: %.6g " % iou, end="", flush=True) if args.out_dir: # C++ BinaryIoU modifies image as a side effect img_np[img_np >= thresh] = 1 img_np[img_np < thresh] = 0 img_t = ecvl.TensorToView(img) img_t.colortype_ = ecvl.ColorType.GRAY img_t.channels_ = "xyc" img.mult_(255.) # orig_img orig_img = x.select([str(k)]) orig_img.mult_(255.) orig_img_t = ecvl.TensorToImage(orig_img) orig_img_t.colortype_ = ecvl.ColorType.BGR orig_img_t.channels_ = "xyc" tmp, labels = ecvl.Image.empty(), ecvl.Image.empty() ecvl.CopyImage(img_t, tmp, ecvl.DataType.uint8) ecvl.ConnectedComponentsLabeling(tmp, labels) ecvl.CopyImage(labels, tmp, ecvl.DataType.uint8) contours = ecvl.FindContours(tmp) ecvl.CopyImage(orig_img_t, tmp, ecvl.DataType.uint8) tmp_np = np.array(tmp, copy=False) for cseq in contours: for c in cseq: tmp_np[c[0], c[1], 0] = 0 tmp_np[c[0], c[1], 1] = 0 tmp_np[c[0], c[1], 2] = 255 filename = d.samples_[d.GetSplit()[n]].location_[0] head, tail = os.path.splitext(os.path.basename(filename)) bname = "%s.png" % head output_fn = os.path.join(args.out_dir, bname) ecvl.ImWrite(output_fn, tmp) if e == 0: gt_t = ecvl.TensorToView(gt) gt_t.colortype_ = ecvl.ColorType.GRAY gt_t.channels_ = "xyc" gt.mult_(255.) gt_filename = d.samples_[d.GetSplit()[n]].label_path_ gt_fn = os.path.join(args.out_dir, os.path.basename(gt_filename)) ecvl.ImWrite(gt_fn, gt_t) n += 1 print() print("MIoU: %.6g" % evaluator.MeanMetric())
def main(args): num_classes = 1 size = [512, 512] # size of images thresh = 0.5 best_dice = -1 if args.out_dir: os.makedirs(args.out_dir, exist_ok=True) in_ = eddl.Input([1, size[0], size[1]]) out = SegNetBN(in_, num_classes) out_sigm = eddl.Sigmoid(out) net = eddl.Model([in_], [out_sigm]) eddl.build(net, eddl.adam(0.0001), ["cross_entropy"], ["mean_squared_error"], eddl.CS_GPU([1], mem='low_mem') if args.gpu else eddl.CS_CPU()) eddl.summary(net) eddl.setlogfile(net, "pneumothorax_segmentation_training") if args.ckpts and os.path.exists(args.ckpts): print("Loading checkpoints '{}'".format(args.ckpts)) eddl.load(net, args.ckpts, 'bin') training_augs = ecvl.SequentialAugmentationContainer([ ecvl.AugResizeDim(size), ecvl.AugMirror(0.5), ecvl.AugRotate([-10, 10]), ecvl.AugBrightness([0, 30]), ecvl.AugGammaContrast([0, 3]), ]) validation_augs = ecvl.SequentialAugmentationContainer( [ecvl.AugResizeDim(size)]) dataset_augs = ecvl.DatasetAugmentations( [training_augs, validation_augs, None]) print("Reading dataset") d = ecvl.DLDataset(args.in_ds, args.batch_size, dataset_augs, ecvl.ColorType.GRAY) # Prepare tensors which store batch x = Tensor([args.batch_size, d.n_channels_, size[0], size[1]]) y = Tensor([args.batch_size, d.n_channels_gt_, size[0], size[1]]) # Retrieve indices of images with a black ground truth # which are not include in a split train_split = d.GetSplit(ecvl.SplitType.training) val_split = d.GetSplit(ecvl.SplitType.validation) test_split = d.GetSplit(ecvl.SplitType.test) all_split = set(train_split + val_split + test_split) images_list = set(range(len(d.samples_))) # Obtain images with black ground truth black_images = images_list - all_split # Add a 25% of training samples with black ground truth. num_samples_train = math.floor(len(train_split) * 1.25) num_batches_train = num_samples_train // args.batch_size # Add a 25% of validation samples with black ground truth. num_samples_validation = math.floor(len(val_split) * 1.25) num_batches_validation = num_samples_validation // args.batch_size black_images = list(black_images) black_training = black_images[0:-(num_samples_validation - len(val_split))] black_validation = black_images[-(num_samples_validation - len(val_split)):] indices = list(range(args.batch_size)) evaluator = utils.Evaluator() print("Starting training") for e in range(args.epochs): print("Epoch {:d}/{:d} - Training".format(e + 1, args.epochs), flush=True) d.SetSplit(ecvl.SplitType.training) eddl.reset_loss(net) s = d.GetSplit() random.shuffle(s) d.split_.training_ = s random.shuffle(black_training) d.ResetAllBatches() # Indices to track mask and black vector in PneumothoraxLoadBatch m_i = 0 b_i = 0 for i, b in enumerate(range(num_batches_train)): d, images, labels, _, m_i, b_i = PneumothoraxLoadBatch( d, black_training, m_i, b_i) x, y = fill_tensors(images, labels, x, y) x.div_(255.0) y.div_(255.0) eddl.train_batch(net, [x], [y], indices) if i % args.log_interval == 0: print("Epoch {:d}/{:d} (batch {:d}/{:d}) - ".format( e + 1, args.epochs, b + 1, num_batches_train), end="", flush=True) eddl.print_loss(net, b) print() d.SetSplit(ecvl.SplitType.validation) evaluator.ResetEval() print("Epoch %d/%d - Evaluation" % (e + 1, args.epochs), flush=True) m_i = 0 b_i = 0 for b in range(num_batches_validation): n = 0 print("Epoch {:d}/{:d} (batch {:d}/{:d}) ".format( e + 1, args.epochs, b + 1, num_batches_validation), end="", flush=True) d, images, labels, names, m_i, b_i = PneumothoraxLoadBatch( d, black_validation, m_i, b_i) x, y = fill_tensors(images, labels, x, y) x.div_(255.0) y.div_(255.0) eddl.forward(net, [x]) output = eddl.getOutput(out_sigm) # Compute Dice metric and optionally save the output images for k in range(args.batch_size): pred = output.select([str(k)]) gt = y.select([str(k)]) pred_np = np.array(pred, copy=False) gt_np = np.array(gt, copy=False) # DiceCoefficient modifies image as a side effect dice = evaluator.DiceCoefficient(pred_np, gt_np, thresh=thresh) print("- Dice: {:.6f} ".format(dice), end="", flush=True) if args.out_dir: # Save original image fused together with prediction and # ground truth pred_np *= 255 pred_ecvl = ecvl.TensorToImage(pred) pred_ecvl.colortype_ = ecvl.ColorType.GRAY pred_ecvl.channels_ = "xyc" ecvl.ResizeDim(pred_ecvl, pred_ecvl, (1024, 1024), ecvl.InterpolationType.nearest) filename_gt = names[n + 1] gt_ecvl = ecvl.ImRead(filename_gt, ecvl.ImReadMode.GRAYSCALE) filename = names[n] # Image as BGR img_ecvl = ecvl.ImRead(filename) ecvl.Stack([img_ecvl, img_ecvl, img_ecvl], img_ecvl) img_ecvl.channels_ = "xyc" img_ecvl.colortype_ = ecvl.ColorType.BGR image_np = np.array(img_ecvl, copy=False) pred_np = np.array(pred_ecvl, copy=False) gt_np = np.array(gt_ecvl, copy=False) pred_np = pred_np.squeeze() gt_np = gt_np.squeeze() # Prediction summed in R channel image_np[:, :, -1] = np.where(pred_np == 255, pred_np, image_np[:, :, -1]) # Ground truth summed in G channel image_np[:, :, 1] = np.where(gt_np == 255, gt_np, image_np[:, :, 1]) n += 2 head, tail = os.path.splitext(os.path.basename(filename)) bname = "{}.png".format(head) filepath = os.path.join(args.out_dir, bname) ecvl.ImWrite(filepath, img_ecvl) print() mean_dice = evaluator.MeanMetric() if mean_dice > best_dice: print("Saving weights") eddl.save( net, "pneumothorax_segnetBN_adam_lr_0.0001_" "loss_ce_size_512_{}.bin".format(e + 1), "bin") best_dice = mean_dice print("Mean Dice Coefficient: {:.6g}".format(mean_dice))
# Training for batch_idx in range(n_train_batches): stdout.write( f"Epoch {epoch}/{epochs} (batch {batch_idx:>4}/{n_train_batches}) - " ) stdout.flush() start_time = time() dataset.LoadBatch(x, y) # Load data eddlT.div_(x, 255.0) # Preprocessing eddl.train_batch(net, [x], [y]) # Perform training eddl.print_loss(net, batch_idx) stdout.write(f"- Elapsed time: {time()-start_time:.2f} seconds\n") stdout.flush() print("Saving model...") eddl.save_net_to_onnx_file(net, "padchest_VGG16_adam_lr-0.0001.onnx") # Validation dataset.SetSplit(ecvl.SplitType.validation) # Set validation split eddl.reset_loss(net) # Reset errors print("Starting validation:") for batch_idx in range(n_validation_batches): stdout.write( f"Validation - Epoch {epoch}/{epochs} (batch {batch_idx:>4}/{n_validation_batches}) " )
def main(args): num_classes = 8 size = [224, 224] # size of images in_ = eddl.Input([3, size[0], size[1]]) out = VGG16(in_, num_classes) net = eddl.Model([in_], [out]) eddl.build(net, eddl.sgd(0.001, 0.9), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU([1]) if args.gpu else eddl.CS_CPU()) eddl.summary(net) eddl.setlogfile(net, "skin_lesion_classification") training_augs = ecvl.SequentialAugmentationContainer([ ecvl.AugResizeDim(size), ecvl.AugMirror(.5), ecvl.AugFlip(.5), ecvl.AugRotate([-180, 180]), ecvl.AugAdditivePoissonNoise([0, 10]), ecvl.AugGammaContrast([0.5, 1.5]), ecvl.AugGaussianBlur([0, 0.8]), ecvl.AugCoarseDropout([0, 0.3], [0.02, 0.05], 0.5) ]) validation_augs = ecvl.SequentialAugmentationContainer([ ecvl.AugResizeDim(size), ]) dataset_augs = ecvl.DatasetAugmentations( [training_augs, validation_augs, None]) print("Reading dataset") d = ecvl.DLDataset(args.in_ds, args.batch_size, dataset_augs) x = Tensor([args.batch_size, d.n_channels_, size[0], size[1]]) y = Tensor([args.batch_size, len(d.classes_)]) num_samples_train = len(d.GetSplit()) num_batches_train = num_samples_train // args.batch_size d.SetSplit(ecvl.SplitType.validation) num_samples_val = len(d.GetSplit()) num_batches_val = num_samples_val // args.batch_size indices = list(range(args.batch_size)) metric = eddl.getMetric("categorical_accuracy") print("Starting training") for e in range(args.epochs): print("Epoch {:d}/{:d} - Training".format(e + 1, args.epochs), flush=True) if args.out_dir: current_path = os.path.join(args.out_dir, "Epoch_%d" % e) for c in d.classes_: c_dir = os.path.join(current_path, c) os.makedirs(c_dir, exist_ok=True) d.SetSplit(ecvl.SplitType.training) eddl.reset_loss(net) total_metric = [] s = d.GetSplit() random.shuffle(s) d.split_.training_ = s d.ResetAllBatches() for b in range(num_batches_train): print("Epoch {:d}/{:d} (batch {:d}/{:d}) - ".format( e + 1, args.epochs, b + 1, num_batches_train), end="", flush=True) d.LoadBatch(x, y) x.div_(255.0) tx, ty = [x], [y] eddl.train_batch(net, tx, ty, indices) eddl.print_loss(net, b) print() print("Saving weights") eddl.save(net, "isic_classification_checkpoint_epoch_%s.bin" % e, "bin") print("Epoch %d/%d - Evaluation" % (e + 1, args.epochs), flush=True) d.SetSplit(ecvl.SplitType.validation) for b in range(num_batches_val): n = 0 print("Epoch {:d}/{:d} (batch {:d}/{:d}) - ".format( e + 1, args.epochs, b + 1, num_batches_val), end="", flush=True) d.LoadBatch(x, y) x.div_(255.0) eddl.forward(net, [x]) output = eddl.getOutput(out) sum_ = 0.0 for k in range(args.batch_size): result = output.select([str(k)]) target = y.select([str(k)]) ca = metric.value(target, result) total_metric.append(ca) sum_ += ca if args.out_dir: result_a = np.array(result, copy=False) target_a = np.array(target, copy=False) classe = np.argmax(result_a).item() gt_class = np.argmax(target_a).item() single_image = x.select([str(k)]) img_t = ecvl.TensorToView(single_image) img_t.colortype_ = ecvl.ColorType.BGR single_image.mult_(255.) filename = d.samples_[d.GetSplit()[n]].location_[0] head, tail = os.path.splitext(os.path.basename(filename)) bname = "%s_gt_class_%s.png" % (head, gt_class) cur_path = os.path.join(current_path, d.classes_[classe], bname) ecvl.ImWrite(cur_path, img_t) n += 1 print("categorical_accuracy:", sum_ / args.batch_size) total_avg = sum(total_metric) / len(total_metric) print("Total categorical accuracy:", total_avg)
def main(args): num_classes = 10 size = [28, 28] # size of images ctype = ecvl.ColorType.GRAY in_ = eddl.Input([1, size[0], size[1]]) out = LeNet(in_, num_classes) net = eddl.Model([in_], [out]) eddl.build(net, eddl.sgd(0.001, 0.9), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU([1]) if args.gpu else eddl.CS_CPU()) eddl.summary(net) eddl.setlogfile(net, "mnist") training_augs = ecvl.SequentialAugmentationContainer([ ecvl.AugRotate([-5, 5]), ecvl.AugAdditivePoissonNoise([0, 10]), ecvl.AugGaussianBlur([0, 0.8]), ecvl.AugCoarseDropout([0, 0.3], [0.02, 0.05], 0), ]) dataset_augs = ecvl.DatasetAugmentations([training_augs, None, None]) print("Reading dataset") d = ecvl.DLDataset(args.in_ds, args.batch_size, dataset_augs, ctype) x_train = Tensor([args.batch_size, d.n_channels_, size[0], size[1]]) y_train = Tensor([args.batch_size, len(d.classes_)]) num_samples = len(d.GetSplit()) num_batches = num_samples // args.batch_size indices = list(range(args.batch_size)) print("Training") for i in range(args.epochs): eddl.reset_loss(net) s = d.GetSplit() random.shuffle(s) d.split_.training_ = s d.ResetCurrentBatch() for j in range(num_batches): print("Epoch %d/%d (batch %d/%d) - " % (i + 1, args.epochs, j + 1, num_batches), end="", flush=True) d.LoadBatch(x_train, y_train) x_train.div_(255.0) tx, ty = [x_train], [y_train] eddl.train_batch(net, tx, ty, indices) eddl.print_loss(net, j) print() print("Saving weights") eddl.save(net, "mnist_checkpoint.bin", "bin") print("Evaluation") d.SetSplit(ecvl.SplitType.test) num_samples = len(d.GetSplit()) num_batches = num_samples // args.batch_size for i in range(num_batches): print("batch %d / %d - " % (i, num_batches), end="", flush=True) d.LoadBatch(x_train, y_train) x_train.div_(255.0) eddl.evaluate(net, [x_train], [y_train])
def main(args): eddl.download_drive() in_1 = eddl.Input([3, 584, 584]) in_2 = eddl.Input([1, 584, 584]) layer = eddl.Concat([in_1, in_2]) layer = eddl.RandomCropScale(layer, [0.9, 1.0]) layer = eddl.CenteredCrop(layer, [512, 512]) img = eddl.Select(layer, ["0:3"]) mask = eddl.Select(layer, ["3"]) # DA net danet = eddl.Model([in_1, in_2], []) eddl.build(danet) if args.gpu: eddl.toGPU(danet, mem="low_mem") eddl.summary(danet) # SegNet in_ = eddl.Input([3, 512, 512]) out = eddl.Sigmoid(UNetWithPadding(in_)) segnet = eddl.Model([in_], [out]) eddl.build( segnet, eddl.adam(0.00001), # Optimizer ["mse"], # Losses ["mse"], # Metrics eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem) ) eddl.summary(segnet) print("Reading training data") # x_train_f = Tensor.fromarray(np.load("drive_trX.npy").astype(np.float32)) x_train_f = Tensor.load("drive_trX.bin") x_train = x_train_f.permute([0, 3, 1, 2]) x_train.info() x_train.div_(255.0) print("Reading test data") # y_train = Tensor.fromarray(np.load("drive_trY.npy").astype(np.float32)) y_train = Tensor.load("drive_trY.bin") y_train.info() y_train.reshape_([20, 1, 584, 584]) y_train.div_(255.0) xbatch = Tensor([args.batch_size, 3, 584, 584]) ybatch = Tensor([args.batch_size, 1, 584, 584]) print("Starting training") for i in range(args.epochs): print("\nEpoch %d/%d" % (i + 1, args.epochs)) eddl.reset_loss(segnet) for j in range(args.num_batches): eddl.next_batch([x_train, y_train], [xbatch, ybatch]) # DA net eddl.forward(danet, [xbatch, ybatch]) xbatch_da = eddl.getOutput(img) ybatch_da = eddl.getOutput(mask) # SegNet eddl.train_batch(segnet, [xbatch_da], [ybatch_da]) eddl.print_loss(segnet, j) if i == args.epochs - 1: yout = eddl.getOutput(out).select(["0"]) yout.save("./out_%d.jpg" % j) print() print("All done")