├── Images
├── FCBformer.jpg
├── Comparison.png
└── FCB_benefit.png
├── requirements.txt
├── Metrics
├── losses.py
└── performance_metrics.py
├── Data
├── dataset.py
└── dataloaders.py
├── eval.py
├── predict.py
├── Models
├── models.py
└── pvt_v2.py
├── train.py
├── README.md
└── LICENSE
/Images/FCBformer.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ESandML/FCBFormer/HEAD/Images/FCBformer.jpg
--------------------------------------------------------------------------------
/Images/Comparison.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ESandML/FCBFormer/HEAD/Images/Comparison.png
--------------------------------------------------------------------------------
/Images/FCB_benefit.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ESandML/FCBFormer/HEAD/Images/FCB_benefit.png
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | numpy==1.22.3
2 | opencv-python==4.5.5.64
3 | scikit-image==0.19.2
4 | scikit-learn==1.0.2
5 | timm==0.5.4
6 | torch==1.9.0+cu111
7 | torchvision==0.10.0+cu111
8 |
--------------------------------------------------------------------------------
/Metrics/losses.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 |
4 |
5 | class SoftDiceLoss(nn.Module):
6 | def __init__(self, smooth=1):
7 | super(SoftDiceLoss, self).__init__()
8 | self.smooth = smooth
9 |
10 | def forward(self, logits, targets):
11 | num = targets.size(0)
12 |
13 | probs = torch.sigmoid(logits)
14 | m1 = probs.view(num, -1)
15 | m2 = targets.view(num, -1)
16 | intersection = m1 * m2
17 |
18 | score = (
19 | 2.0
20 | * (intersection.sum(1) + self.smooth)
21 | / (m1.sum(1) + m2.sum(1) + self.smooth)
22 | )
23 | score = 1 - score.sum() / num
24 | return score
25 |
26 |
--------------------------------------------------------------------------------
/Metrics/performance_metrics.py:
--------------------------------------------------------------------------------
1 | import torch
2 |
3 |
4 | class DiceScore(torch.nn.Module):
5 | def __init__(self, smooth=1):
6 | super(DiceScore, self).__init__()
7 | self.smooth = smooth
8 |
9 | def forward(self, logits, targets, sigmoid=True):
10 | num = targets.size(0)
11 |
12 | probs = torch.sigmoid(logits)
13 | m1 = probs.view(num, -1) > 0.5
14 | m2 = targets.view(num, -1) > 0.5
15 | intersection = m1 * m2
16 |
17 | score = (
18 | 2.0
19 | * (intersection.sum(1) + self.smooth)
20 | / (m1.sum(1) + m2.sum(1) + self.smooth)
21 | )
22 | score = score.sum() / num
23 | return score
24 |
25 |
--------------------------------------------------------------------------------
/Data/dataset.py:
--------------------------------------------------------------------------------
1 | import random
2 | from skimage.io import imread
3 |
4 | import torch
5 | from torch.utils import data
6 | import torchvision.transforms.functional as TF
7 |
8 |
9 | class SegDataset(data.Dataset):
10 | def __init__(
11 | self,
12 | input_paths: list,
13 | target_paths: list,
14 | transform_input=None,
15 | transform_target=None,
16 | hflip=False,
17 | vflip=False,
18 | affine=False,
19 | ):
20 | self.input_paths = input_paths
21 | self.target_paths = target_paths
22 | self.transform_input = transform_input
23 | self.transform_target = transform_target
24 | self.hflip = hflip
25 | self.vflip = vflip
26 | self.affine = affine
27 |
28 | def __len__(self):
29 | return len(self.input_paths)
30 |
31 | def __getitem__(self, index: int):
32 | input_ID = self.input_paths[index]
33 | target_ID = self.target_paths[index]
34 |
35 | x, y = imread(input_ID), imread(target_ID)
36 |
37 | x = self.transform_input(x)
38 | y = self.transform_target(y)
39 |
40 | if self.hflip:
41 | if random.uniform(0.0, 1.0) > 0.5:
42 | x = TF.hflip(x)
43 | y = TF.hflip(y)
44 |
45 | if self.vflip:
46 | if random.uniform(0.0, 1.0) > 0.5:
47 | x = TF.vflip(x)
48 | y = TF.vflip(y)
49 |
50 | if self.affine:
51 | angle = random.uniform(-180.0, 180.0)
52 | h_trans = random.uniform(-352 / 8, 352 / 8)
53 | v_trans = random.uniform(-352 / 8, 352 / 8)
54 | scale = random.uniform(0.5, 1.5)
55 | shear = random.uniform(-22.5, 22.5)
56 | x = TF.affine(x, angle, (h_trans, v_trans), scale, shear, fill=-1.0)
57 | y = TF.affine(y, angle, (h_trans, v_trans), scale, shear, fill=0.0)
58 | return x.float(), y.float()
59 |
60 |
--------------------------------------------------------------------------------
/Data/dataloaders.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import random
3 | import multiprocessing
4 |
5 | from sklearn.model_selection import train_test_split
6 | from torchvision import transforms
7 | from torch.utils import data
8 |
9 | from Data.dataset import SegDataset
10 |
11 |
12 | def split_ids(len_ids):
13 | train_size = int(round((80 / 100) * len_ids))
14 | valid_size = int(round((10 / 100) * len_ids))
15 | test_size = int(round((10 / 100) * len_ids))
16 |
17 | train_indices, test_indices = train_test_split(
18 | np.linspace(0, len_ids - 1, len_ids).astype("int"),
19 | test_size=test_size,
20 | random_state=42,
21 | )
22 |
23 | train_indices, val_indices = train_test_split(
24 | train_indices, test_size=test_size, random_state=42
25 | )
26 |
27 | return train_indices, test_indices, val_indices
28 |
29 |
30 | def get_dataloaders(input_paths, target_paths, batch_size):
31 |
32 | transform_input4train = transforms.Compose(
33 | [
34 | transforms.ToTensor(),
35 | transforms.Resize((352, 352), antialias=True),
36 | transforms.GaussianBlur((25, 25), sigma=(0.001, 2.0)),
37 | transforms.ColorJitter(
38 | brightness=0.4, contrast=0.5, saturation=0.25, hue=0.01
39 | ),
40 | transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
41 | ]
42 | )
43 |
44 | transform_input4test = transforms.Compose(
45 | [
46 | transforms.ToTensor(),
47 | transforms.Resize((352, 352), antialias=True),
48 | transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
49 | ]
50 | )
51 |
52 | transform_target = transforms.Compose(
53 | [transforms.ToTensor(), transforms.Resize((352, 352)), transforms.Grayscale()]
54 | )
55 |
56 | train_dataset = SegDataset(
57 | input_paths=input_paths,
58 | target_paths=target_paths,
59 | transform_input=transform_input4train,
60 | transform_target=transform_target,
61 | hflip=True,
62 | vflip=True,
63 | affine=True,
64 | )
65 |
66 | test_dataset = SegDataset(
67 | input_paths=input_paths,
68 | target_paths=target_paths,
69 | transform_input=transform_input4test,
70 | transform_target=transform_target,
71 | )
72 |
73 | val_dataset = SegDataset(
74 | input_paths=input_paths,
75 | target_paths=target_paths,
76 | transform_input=transform_input4test,
77 | transform_target=transform_target,
78 | )
79 |
80 | train_indices, test_indices, val_indices = split_ids(len(input_paths))
81 |
82 | train_dataset = data.Subset(train_dataset, train_indices)
83 | val_dataset = data.Subset(val_dataset, val_indices)
84 | test_dataset = data.Subset(test_dataset, test_indices)
85 |
86 | train_dataloader = data.DataLoader(
87 | dataset=train_dataset,
88 | batch_size=batch_size,
89 | shuffle=True,
90 | drop_last=True,
91 | num_workers=multiprocessing.Pool()._processes,
92 | )
93 |
94 | test_dataloader = data.DataLoader(
95 | dataset=test_dataset,
96 | batch_size=1,
97 | shuffle=False,
98 | num_workers=multiprocessing.Pool()._processes,
99 | )
100 |
101 | val_dataloader = data.DataLoader(
102 | dataset=val_dataset,
103 | batch_size=1,
104 | shuffle=False,
105 | num_workers=multiprocessing.Pool()._processes,
106 | )
107 |
108 | return train_dataloader, test_dataloader, val_dataloader
109 |
110 |
111 |
112 |
--------------------------------------------------------------------------------
/eval.py:
--------------------------------------------------------------------------------
1 | import os
2 | import glob
3 | import argparse
4 | import numpy as np
5 |
6 | from sklearn.metrics import jaccard_score, f1_score, precision_score, recall_score
7 | from skimage.io import imread
8 | from skimage.transform import resize
9 |
10 | from Data.dataloaders import split_ids
11 |
12 |
13 | def eval(args):
14 |
15 | if args.test_dataset == "Kvasir":
16 | prediction_files = sorted(
17 | glob.glob(
18 | "./Predictions/Trained on {}/Tested on {}/*".format(
19 | args.train_dataset, args.test_dataset
20 | )
21 | )
22 | )
23 | depth_path = args.root + "masks/*"
24 | target_paths = sorted(glob.glob(depth_path))
25 | elif args.test_dataset == "CVC":
26 | prediction_files = sorted(
27 | glob.glob(
28 | "./Predictions/Trained on {}/Tested on {}/*".format(
29 | args.train_dataset, args.test_dataset
30 | )
31 | )
32 | )
33 | depth_path = args.root + "Ground Truth/*"
34 | target_paths = sorted(glob.glob(depth_path))
35 |
36 | _, test_indices, _ = split_ids(len(target_paths))
37 |
38 | test_files = sorted(
39 | [target_paths[test_indices[i]] for i in range(len(test_indices))]
40 | )
41 |
42 | dice = []
43 | IoU = []
44 | precision = []
45 | recall = []
46 |
47 | for i in range(len(test_files)):
48 | pred = np.ndarray.flatten(imread(prediction_files[i]) / 255) > 0.5
49 | gt = (
50 | resize(imread(test_files[i]), (int(352), int(352)), anti_aliasing=False)
51 | > 0.5
52 | )
53 |
54 | if len(gt.shape) == 3:
55 | gt = np.mean(gt, axis=2)
56 | gt = np.ndarray.flatten(gt)
57 |
58 | dice.append(f1_score(gt, pred))
59 | IoU.append(jaccard_score(gt, pred))
60 | precision.append(precision_score(gt, pred))
61 | recall.append(recall_score(gt, pred))
62 |
63 | if i + 1 < len(test_files):
64 | print(
65 | "\rTest: [{}/{} ({:.1f}%)]\tModel scores: Dice={:.6f}, mIoU={:.6f}, precision={:.6f}, recall={:.6f}".format(
66 | i + 1,
67 | len(test_files),
68 | 100.0 * (i + 1) / len(test_files),
69 | np.mean(dice),
70 | np.mean(IoU),
71 | np.mean(precision),
72 | np.mean(recall),
73 | ),
74 | end="",
75 | )
76 | else:
77 | print(
78 | "\rTest: [{}/{} ({:.1f}%)]\tModel scores: Dice={:.6f}, mIoU={:.6f}, precision={:.6f}, recall={:.6f}".format(
79 | i + 1,
80 | len(test_files),
81 | 100.0 * (i + 1) / len(test_files),
82 | np.mean(dice),
83 | np.mean(IoU),
84 | np.mean(precision),
85 | np.mean(recall),
86 | )
87 | )
88 |
89 |
90 | def get_args():
91 | parser = argparse.ArgumentParser(
92 | description="Make predictions on specified dataset"
93 | )
94 | parser.add_argument(
95 | "--train-dataset", type=str, required=True, choices=["Kvasir", "CVC"]
96 | )
97 | parser.add_argument(
98 | "--test-dataset", type=str, required=True, choices=["Kvasir", "CVC"]
99 | )
100 | parser.add_argument("--data-root", type=str, required=True, dest="root")
101 |
102 | return parser.parse_args()
103 |
104 |
105 | def main():
106 | args = get_args()
107 | eval(args)
108 |
109 |
110 | if __name__ == "__main__":
111 | main()
112 |
113 |
--------------------------------------------------------------------------------
/predict.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import os
3 | import argparse
4 | import time
5 | import numpy as np
6 | import glob
7 | import cv2
8 |
9 | import torch
10 | import torch.nn as nn
11 |
12 | from Data import dataloaders
13 | from Models import models
14 | from Metrics import performance_metrics
15 |
16 |
17 | def build(args):
18 | if torch.cuda.is_available():
19 | device = torch.device("cuda")
20 | else:
21 | device = torch.device("cpu")
22 |
23 | if args.test_dataset == "Kvasir":
24 | img_path = args.root + "images/*"
25 | input_paths = sorted(glob.glob(img_path))
26 | depth_path = args.root + "masks/*"
27 | target_paths = sorted(glob.glob(depth_path))
28 | elif args.test_dataset == "CVC":
29 | img_path = args.root + "Original/*"
30 | input_paths = sorted(glob.glob(img_path))
31 | depth_path = args.root + "Ground Truth/*"
32 | target_paths = sorted(glob.glob(depth_path))
33 | _, test_dataloader, _ = dataloaders.get_dataloaders(
34 | input_paths, target_paths, batch_size=1
35 | )
36 |
37 | _, test_indices, _ = dataloaders.split_ids(len(target_paths))
38 | target_paths = [target_paths[test_indices[i]] for i in range(len(test_indices))]
39 |
40 | perf = performance_metrics.DiceScore()
41 |
42 | model = models.FCBFormer()
43 |
44 | state_dict = torch.load(
45 | "./Trained models/FCBFormer_{}.pt".format(args.train_dataset)
46 | )
47 | model.load_state_dict(state_dict["model_state_dict"])
48 |
49 | model.to(device)
50 |
51 | return device, test_dataloader, perf, model, target_paths
52 |
53 |
54 | @torch.no_grad()
55 | def predict(args):
56 | device, test_dataloader, perf_measure, model, target_paths = build(args)
57 |
58 | if not os.path.exists("./Predictions"):
59 | os.makedirs("./Predictions")
60 | if not os.path.exists("./Predictions/Trained on {}".format(args.train_dataset)):
61 | os.makedirs("./Predictions/Trained on {}".format(args.train_dataset))
62 | if not os.path.exists(
63 | "./Predictions/Trained on {}/Tested on {}".format(
64 | args.train_dataset, args.test_dataset
65 | )
66 | ):
67 | os.makedirs(
68 | "./Predictions/Trained on {}/Tested on {}".format(
69 | args.train_dataset, args.test_dataset
70 | )
71 | )
72 |
73 | t = time.time()
74 | model.eval()
75 | perf_accumulator = []
76 | for i, (data, target) in enumerate(test_dataloader):
77 | data, target = data.to(device), target.to(device)
78 | output = model(data)
79 | perf_accumulator.append(perf_measure(output, target).item())
80 | predicted_map = np.array(output.cpu())
81 | predicted_map = np.squeeze(predicted_map)
82 | predicted_map = predicted_map > 0
83 | cv2.imwrite(
84 | "./Predictions/Trained on {}/Tested on {}/{}".format(
85 | args.train_dataset, args.test_dataset, os.path.basename(target_paths[i])
86 | ),
87 | predicted_map * 255,
88 | )
89 | if i + 1 < len(test_dataloader):
90 | print(
91 | "\rTest: [{}/{} ({:.1f}%)]\tAverage performance: {:.6f}\tTime: {:.6f}".format(
92 | i + 1,
93 | len(test_dataloader),
94 | 100.0 * (i + 1) / len(test_dataloader),
95 | np.mean(perf_accumulator),
96 | time.time() - t,
97 | ),
98 | end="",
99 | )
100 | else:
101 | print(
102 | "\rTest: [{}/{} ({:.1f}%)]\tAverage performance: {:.6f}\tTime: {:.6f}".format(
103 | i + 1,
104 | len(test_dataloader),
105 | 100.0 * (i + 1) / len(test_dataloader),
106 | np.mean(perf_accumulator),
107 | time.time() - t,
108 | )
109 | )
110 |
111 |
112 | def get_args():
113 | parser = argparse.ArgumentParser(
114 | description="Make predictions on specified dataset"
115 | )
116 | parser.add_argument(
117 | "--train-dataset", type=str, required=True, choices=["Kvasir", "CVC"]
118 | )
119 | parser.add_argument(
120 | "--test-dataset", type=str, required=True, choices=["Kvasir", "CVC"]
121 | )
122 | parser.add_argument("--data-root", type=str, required=True, dest="root")
123 |
124 | return parser.parse_args()
125 |
126 |
127 | def main():
128 | args = get_args()
129 | predict(args)
130 |
131 |
132 | if __name__ == "__main__":
133 | main()
134 |
135 |
--------------------------------------------------------------------------------
/Models/models.py:
--------------------------------------------------------------------------------
1 | from functools import partial
2 | import numpy as np
3 |
4 | import torch
5 | from torch import nn
6 |
7 | from Models import pvt_v2
8 | from timm.models.vision_transformer import _cfg
9 |
10 |
11 | class RB(nn.Module):
12 | def __init__(self, in_channels, out_channels):
13 | super().__init__()
14 |
15 | self.in_layers = nn.Sequential(
16 | nn.GroupNorm(32, in_channels),
17 | nn.SiLU(),
18 | nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
19 | )
20 |
21 | self.out_layers = nn.Sequential(
22 | nn.GroupNorm(32, out_channels),
23 | nn.SiLU(),
24 | nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
25 | )
26 |
27 | if out_channels == in_channels:
28 | self.skip = nn.Identity()
29 | else:
30 | self.skip = nn.Conv2d(in_channels, out_channels, kernel_size=1)
31 |
32 | def forward(self, x):
33 | h = self.in_layers(x)
34 | h = self.out_layers(h)
35 | return h + self.skip(x)
36 |
37 |
38 | class FCB(nn.Module):
39 | def __init__(
40 | self,
41 | in_channels=3,
42 | min_level_channels=32,
43 | min_channel_mults=[1, 1, 2, 2, 4, 4],
44 | n_levels_down=6,
45 | n_levels_up=6,
46 | n_RBs=2,
47 | in_resolution=352,
48 | ):
49 |
50 | super().__init__()
51 |
52 | self.enc_blocks = nn.ModuleList(
53 | [nn.Conv2d(in_channels, min_level_channels, kernel_size=3, padding=1)]
54 | )
55 | ch = min_level_channels
56 | enc_block_chans = [min_level_channels]
57 | for level in range(n_levels_down):
58 | min_channel_mult = min_channel_mults[level]
59 | for block in range(n_RBs):
60 | self.enc_blocks.append(
61 | nn.Sequential(RB(ch, min_channel_mult * min_level_channels))
62 | )
63 | ch = min_channel_mult * min_level_channels
64 | enc_block_chans.append(ch)
65 | if level != n_levels_down - 1:
66 | self.enc_blocks.append(
67 | nn.Sequential(nn.Conv2d(ch, ch, kernel_size=3, padding=1, stride=2))
68 | )
69 | enc_block_chans.append(ch)
70 |
71 | self.middle_block = nn.Sequential(RB(ch, ch), RB(ch, ch))
72 |
73 | self.dec_blocks = nn.ModuleList([])
74 | for level in range(n_levels_up):
75 | min_channel_mult = min_channel_mults[::-1][level]
76 |
77 | for block in range(n_RBs + 1):
78 | layers = [
79 | RB(
80 | ch + enc_block_chans.pop(),
81 | min_channel_mult * min_level_channels,
82 | )
83 | ]
84 | ch = min_channel_mult * min_level_channels
85 | if level < n_levels_up - 1 and block == n_RBs:
86 | layers.append(
87 | nn.Sequential(
88 | nn.Upsample(scale_factor=2, mode="nearest"),
89 | nn.Conv2d(ch, ch, kernel_size=3, padding=1),
90 | )
91 | )
92 | self.dec_blocks.append(nn.Sequential(*layers))
93 |
94 | def forward(self, x):
95 | hs = []
96 | h = x
97 | for module in self.enc_blocks:
98 | h = module(h)
99 | hs.append(h)
100 | h = self.middle_block(h)
101 | for module in self.dec_blocks:
102 | cat_in = torch.cat([h, hs.pop()], dim=1)
103 | h = module(cat_in)
104 | return h
105 |
106 |
107 | class TB(nn.Module):
108 | def __init__(self):
109 |
110 | super().__init__()
111 |
112 | backbone = pvt_v2.PyramidVisionTransformerV2(
113 | patch_size=4,
114 | embed_dims=[64, 128, 320, 512],
115 | num_heads=[1, 2, 5, 8],
116 | mlp_ratios=[8, 8, 4, 4],
117 | qkv_bias=True,
118 | norm_layer=partial(torch.nn.LayerNorm, eps=1e-6),
119 | depths=[3, 4, 18, 3],
120 | sr_ratios=[8, 4, 2, 1],
121 | )
122 |
123 | checkpoint = torch.load("pvt_v2_b3.pth")
124 | backbone.default_cfg = _cfg()
125 | backbone.load_state_dict(checkpoint)
126 | self.backbone = torch.nn.Sequential(*list(backbone.children()))[:-1]
127 |
128 | for i in [1, 4, 7, 10]:
129 | self.backbone[i] = torch.nn.Sequential(*list(self.backbone[i].children()))
130 |
131 | self.LE = nn.ModuleList([])
132 | for i in range(4):
133 | self.LE.append(
134 | nn.Sequential(
135 | RB([64, 128, 320, 512][i], 64), RB(64, 64), nn.Upsample(size=88)
136 | )
137 | )
138 |
139 | self.SFA = nn.ModuleList([])
140 | for i in range(3):
141 | self.SFA.append(nn.Sequential(RB(128, 64), RB(64, 64)))
142 |
143 | def get_pyramid(self, x):
144 | pyramid = []
145 | B = x.shape[0]
146 | for i, module in enumerate(self.backbone):
147 | if i in [0, 3, 6, 9]:
148 | x, H, W = module(x)
149 | elif i in [1, 4, 7, 10]:
150 | for sub_module in module:
151 | x = sub_module(x, H, W)
152 | else:
153 | x = module(x)
154 | x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
155 | pyramid.append(x)
156 |
157 | return pyramid
158 |
159 | def forward(self, x):
160 | pyramid = self.get_pyramid(x)
161 | pyramid_emph = []
162 | for i, level in enumerate(pyramid):
163 | pyramid_emph.append(self.LE[i](pyramid[i]))
164 |
165 | l_i = pyramid_emph[-1]
166 | for i in range(2, -1, -1):
167 | l = torch.cat((pyramid_emph[i], l_i), dim=1)
168 | l = self.SFA[i](l)
169 | l_i = l
170 |
171 | return l
172 |
173 |
174 | class FCBFormer(nn.Module):
175 | def __init__(self, size=352):
176 |
177 | super().__init__()
178 |
179 | self.TB = TB()
180 |
181 | self.FCB = FCB(in_resolution=size)
182 | self.PH = nn.Sequential(
183 | RB(64 + 32, 64), RB(64, 64), nn.Conv2d(64, 1, kernel_size=1)
184 | )
185 | self.up_tosize = nn.Upsample(size=size)
186 |
187 | def forward(self, x):
188 | x1 = self.TB(x)
189 | x2 = self.FCB(x)
190 | x1 = self.up_tosize(x1)
191 | x = torch.cat((x1, x2), dim=1)
192 | out = self.PH(x)
193 |
194 | return out
195 |
196 |
--------------------------------------------------------------------------------
/train.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 | import argparse
4 | import time
5 | import numpy as np
6 | import glob
7 |
8 | import torch
9 | import torch.nn as nn
10 |
11 | from Data import dataloaders
12 | from Models import models
13 | from Metrics import performance_metrics
14 | from Metrics import losses
15 |
16 |
17 | def train_epoch(model, device, train_loader, optimizer, epoch, Dice_loss, BCE_loss):
18 | t = time.time()
19 | model.train()
20 | loss_accumulator = []
21 | for batch_idx, (data, target) in enumerate(train_loader):
22 | data, target = data.to(device), target.to(device)
23 | optimizer.zero_grad()
24 | output = model(data)
25 | loss = Dice_loss(output, target) + BCE_loss(torch.sigmoid(output), target)
26 | loss.backward()
27 | optimizer.step()
28 | loss_accumulator.append(loss.item())
29 | if batch_idx + 1 < len(train_loader):
30 | print(
31 | "\rTrain Epoch: {} [{}/{} ({:.1f}%)]\tLoss: {:.6f}\tTime: {:.6f}".format(
32 | epoch,
33 | (batch_idx + 1) * len(data),
34 | len(train_loader.dataset),
35 | 100.0 * (batch_idx + 1) / len(train_loader),
36 | loss.item(),
37 | time.time() - t,
38 | ),
39 | end="",
40 | )
41 | else:
42 | print(
43 | "\rTrain Epoch: {} [{}/{} ({:.1f}%)]\tAverage loss: {:.6f}\tTime: {:.6f}".format(
44 | epoch,
45 | (batch_idx + 1) * len(data),
46 | len(train_loader.dataset),
47 | 100.0 * (batch_idx + 1) / len(train_loader),
48 | np.mean(loss_accumulator),
49 | time.time() - t,
50 | )
51 | )
52 |
53 | return np.mean(loss_accumulator)
54 |
55 |
56 | @torch.no_grad()
57 | def test(model, device, test_loader, epoch, perf_measure):
58 | t = time.time()
59 | model.eval()
60 | perf_accumulator = []
61 | for batch_idx, (data, target) in enumerate(test_loader):
62 | data, target = data.to(device), target.to(device)
63 | output = model(data)
64 | perf_accumulator.append(perf_measure(output, target).item())
65 | if batch_idx + 1 < len(test_loader):
66 | print(
67 | "\rTest Epoch: {} [{}/{} ({:.1f}%)]\tAverage performance: {:.6f}\tTime: {:.6f}".format(
68 | epoch,
69 | batch_idx + 1,
70 | len(test_loader),
71 | 100.0 * (batch_idx + 1) / len(test_loader),
72 | np.mean(perf_accumulator),
73 | time.time() - t,
74 | ),
75 | end="",
76 | )
77 | else:
78 | print(
79 | "\rTest Epoch: {} [{}/{} ({:.1f}%)]\tAverage performance: {:.6f}\tTime: {:.6f}".format(
80 | epoch,
81 | batch_idx + 1,
82 | len(test_loader),
83 | 100.0 * (batch_idx + 1) / len(test_loader),
84 | np.mean(perf_accumulator),
85 | time.time() - t,
86 | )
87 | )
88 |
89 | return np.mean(perf_accumulator), np.std(perf_accumulator)
90 |
91 |
92 | def build(args):
93 | if torch.cuda.is_available():
94 | device = torch.device("cuda")
95 | else:
96 | device = torch.device("cpu")
97 |
98 | if args.dataset == "Kvasir":
99 | img_path = args.root + "images/*"
100 | input_paths = sorted(glob.glob(img_path))
101 | depth_path = args.root + "masks/*"
102 | target_paths = sorted(glob.glob(depth_path))
103 | elif args.dataset == "CVC":
104 | img_path = args.root + "Original/*"
105 | input_paths = sorted(glob.glob(img_path))
106 | depth_path = args.root + "Ground Truth/*"
107 | target_paths = sorted(glob.glob(depth_path))
108 | train_dataloader, _, val_dataloader = dataloaders.get_dataloaders(
109 | input_paths, target_paths, batch_size=args.batch_size
110 | )
111 |
112 | Dice_loss = losses.SoftDiceLoss()
113 | BCE_loss = nn.BCELoss()
114 |
115 | perf = performance_metrics.DiceScore()
116 |
117 | model = models.FCBFormer()
118 |
119 | if args.mgpu == "true":
120 | model = nn.DataParallel(model)
121 | model.to(device)
122 | optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr)
123 |
124 | return (
125 | device,
126 | train_dataloader,
127 | val_dataloader,
128 | Dice_loss,
129 | BCE_loss,
130 | perf,
131 | model,
132 | optimizer,
133 | )
134 |
135 |
136 | def train(args):
137 | (
138 | device,
139 | train_dataloader,
140 | val_dataloader,
141 | Dice_loss,
142 | BCE_loss,
143 | perf,
144 | model,
145 | optimizer,
146 | ) = build(args)
147 |
148 | if not os.path.exists("./Trained models"):
149 | os.makedirs("./Trained models")
150 |
151 | prev_best_test = None
152 | if args.lrs == "true":
153 | if args.lrs_min > 0:
154 | scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
155 | optimizer, mode="max", factor=0.5, min_lr=args.lrs_min, verbose=True
156 | )
157 | else:
158 | scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
159 | optimizer, mode="max", factor=0.5, verbose=True
160 | )
161 | for epoch in range(1, args.epochs + 1):
162 | try:
163 | loss = train_epoch(
164 | model, device, train_dataloader, optimizer, epoch, Dice_loss, BCE_loss
165 | )
166 | test_measure_mean, test_measure_std = test(
167 | model, device, val_dataloader, epoch, perf
168 | )
169 | except KeyboardInterrupt:
170 | print("Training interrupted by user")
171 | sys.exit(0)
172 | if args.lrs == "true":
173 | scheduler.step(test_measure_mean)
174 | if prev_best_test == None or test_measure_mean > prev_best_test:
175 | print("Saving...")
176 | torch.save(
177 | {
178 | "epoch": epoch,
179 | "model_state_dict": model.state_dict()
180 | if args.mgpu == "false"
181 | else model.module.state_dict(),
182 | "optimizer_state_dict": optimizer.state_dict(),
183 | "loss": loss,
184 | "test_measure_mean": test_measure_mean,
185 | "test_measure_std": test_measure_std,
186 | },
187 | "Trained models/FCBFormer_" + args.dataset + ".pt",
188 | )
189 | prev_best_test = test_measure_mean
190 |
191 |
192 | def get_args():
193 | parser = argparse.ArgumentParser(description="Train FCBFormer on specified dataset")
194 | parser.add_argument("--dataset", type=str, required=True, choices=["Kvasir", "CVC"])
195 | parser.add_argument("--data-root", type=str, required=True, dest="root")
196 | parser.add_argument("--epochs", type=int, default=200)
197 | parser.add_argument("--batch-size", type=int, default=16)
198 | parser.add_argument("--learning-rate", type=float, default=1e-4, dest="lr")
199 | parser.add_argument(
200 | "--learning-rate-scheduler", type=str, default="true", dest="lrs"
201 | )
202 | parser.add_argument(
203 | "--learning-rate-scheduler-minimum", type=float, default=1e-6, dest="lrs_min"
204 | )
205 | parser.add_argument(
206 | "--multi-gpu", type=str, default="false", dest="mgpu", choices=["true", "false"]
207 | )
208 |
209 | return parser.parse_args()
210 |
211 |
212 | def main():
213 | args = get_args()
214 | train(args)
215 |
216 |
217 | if __name__ == "__main__":
218 | main()
219 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://paperswithcode.com/sota/medical-image-segmentation-on-kvasir-seg?p=fcn-transformer-feature-fusion-for-polyp)
2 |
3 | [](https://paperswithcode.com/sota/medical-image-segmentation-on-cvc-clinicdb?p=fcn-transformer-feature-fusion-for-polyp)
4 |
5 | # FCBFormer
6 |
7 | Official code repository for: FCN-Transformer Feature Fusion for Polyp Segmentation (MIUA 2022 paper)
8 |
9 | Authors: [Edward Sanderson](https://scholar.google.com/citations?user=ea4c7r0AAAAJ&hl=en&oi=ao) and [Bogdan J. Matuszewski](https://scholar.google.co.uk/citations?user=QlUO_oAAAAAJ&hl=en)
10 |
11 | Links to the paper:
12 | + [Springer (Open Access)](https://link.springer.com/chapter/10.1007/978-3-031-12053-4_65)
13 | + [arXiv](https://arxiv.org/abs/2208.08352)
14 |
15 | ## 1. Overview
16 |
17 | ### 1.1 Abstract
18 |
19 | Colonoscopy is widely recognised as the gold standard procedure for the early detection of colorectal cancer (CRC). Segmentation is valuable for two significant clinical applications, namely lesion detection and classification, providing means to improve accuracy and robustness. The manual segmentation of polyps in colonoscopy images is timeconsuming. As a result, the use of deep learning (DL) for automation of polyp segmentation has become important. However, DL-based solutions can be vulnerable to overfitting and the resulting inability to generalise to images captured by different colonoscopes. Recent transformer-based architectures for semantic segmentation both achieve higher performance and generalise better than alternatives, however typically predict a segmentation map of $\frac{h}{4} × \frac{w}{4}$ spatial dimensions for a $h \times w$ input image. To
20 | this end, we propose a new architecture for full-size segmentation which leverages the strengths of a transformer in extracting the most important features for segmentation in a primary branch, while compensating for its limitations in full-size prediction with a secondary fully convolutional branch. The resulting features from both branches are then fused for final prediction of a $h × w$ segmentation map. We demonstrate our method’s state-of-the-art performance with respect to the mDice, mIoU, mPrecision, and mRecall metrics, on both the Kvasir-SEG and CVC-ClinicDB dataset benchmarks. Additionally, we train the model on each of these datasets and evaluate on the other to demonstrate its superior generalisation performance.
21 |
22 | ### 1.2 Architecture
23 |
24 |
25 |
26 |
27 | Figure 1: Illustration of the proposed FCBFormer architecture
28 |
29 |
30 |
31 | ### 1.3 Qualitative results
32 |
33 |
34 |
35 |
36 | Figure 2: Comparison of predictions of FCBFormer against baselines. FF is FCBFormer, PN is PraNet, MN is MSRF-Net, R++ is ResUNet++, UN is U-Net
37 |
38 |
39 |
40 |
41 |
42 |
43 | Figure 3: Visualisation of the benefit of the fully convolutional branch (FCB)
44 |
45 |
46 |
47 | ## 2. Usage
48 |
49 | ### 2.1 Preparation
50 |
51 | + Create and activate virtual environment:
52 |
53 | ```
54 | python3 -m venv ~/FCBFormer-env
55 | source ~/FCBFormer-env/bin/activate
56 | ```
57 |
58 | + Clone the repository and navigate to new directory:
59 |
60 | ```
61 | git clone https://github.com/ESandML/FCBFormer
62 | cd ./FCBFormer
63 | ```
64 |
65 | + Install the requirements:
66 |
67 | ```
68 | pip install -r requirements.txt
69 | ```
70 |
71 | + Download and extract the [Kvasir-SEG](https://datasets.simula.no/downloads/kvasir-seg.zip) and the [CVC-ClinicDB](https://www.dropbox.com/s/p5qe9eotetjnbmq/CVC-ClinicDB.rar?dl=0) datasets.
72 |
73 | + Download the [PVTv2-B3](https://github.com/whai362/PVT/releases/download/v2/pvt_v2_b3.pth) weights to `./`
74 |
75 | ### 2.2 Training
76 |
77 | Train FCBFormer on the train split of a dataset:
78 |
79 | ```
80 | python train.py --dataset=[train data] --data-root=[path]
81 | ```
82 |
83 | + Replace `[train data]` with training dataset name (options: `Kvasir`; `CVC`).
84 |
85 | + Replace `[path]` with path to parent directory of `/images` and `/masks` directories (training on Kvasir-SEG); or parent directory of `/Original` and `/Ground Truth` directories (training on CVC-ClinicDB).
86 |
87 | + To train on multiple GPUs, include `--multi-gpu=true`.
88 |
89 | ### 2.3 Prediction
90 |
91 | Generate predictions from a trained model for a test split. Note, the test split can be from a different dataset to the train split:
92 |
93 | ```
94 | python predict.py --train-dataset=[train data] --test-dataset=[test data] --data-root=[path]
95 | ```
96 |
97 | + Replace `[train data]` with training dataset name (options: `Kvasir`; `CVC`).
98 |
99 | + Replace `[test data]` with testing dataset name (options: `Kvasir`; `CVC`).
100 |
101 | + Replace `[path]` with path to parent directory of `/images` and `/masks` directories (testing on Kvasir-SEG); or parent directory of `/Original` and `/Ground Truth` directories (testing on CVC-ClinicDB).
102 |
103 | ### 2.4 Evaluation
104 |
105 | Evaluate pre-computed predictions from a trained model for a test split. Note, the test split can be from a different dataset to the train split:
106 |
107 | ```
108 | python eval.py --train-dataset=[train data] --test-dataset=[test data] --data-root=[path]
109 | ```
110 |
111 | + Replace `[train data]` with training dataset name (options: `Kvasir`; `CVC`).
112 |
113 | + Replace `[test data]` with testing dataset name (options: `Kvasir`; `CVC`).
114 |
115 | + Replace `[path]` with path to parent directory of `/images` and `/masks` directories (testing on Kvasir-SEG); or parent directory of `/Original` and `/Ground Truth` directories (testing on CVC-ClinicDB).
116 |
117 | ## 3. License
118 |
119 | This repository is released under the Apache 2.0 license as found in the [LICENSE](https://github.com/ESandML/FCBFormer/blob/main/LICENSE) file.
120 |
121 | ## 4. Pretrained weights
122 |
123 |
124 |
125 | | Training data | Download |
126 | |---------------|---------------------|
127 | | Kvasir-SEG |[Google Drive](https://drive.google.com/file/d/1ILaudmcBvuuQ-FNZx7xjsCFZ5vZG7VSx/view?usp=drive_link)|
128 | | CVC-ClinicDB |[Google Drive](https://drive.google.com/file/d/1_6MzRjm3fp0x_ec9QHTDdBmKXVs68-r-/view?usp=drive_link)|
129 |
130 | ## 5. Citation
131 |
132 | If you use this work, please consider citing us:
133 |
134 | ```bibtex
135 | @inproceedings{sanderson2022fcn,
136 | title={FCN-Transformer Feature Fusion for Polyp Segmentation},
137 | author={Sanderson, Edward and Matuszewski, Bogdan J},
138 | booktitle={Annual Conference on Medical Image Understanding and Analysis},
139 | pages={892--907},
140 | year={2022},
141 | organization={Springer}
142 | }
143 | ```
144 |
145 | ## 6. Commercial use
146 |
147 | We allow commerical use of this work, as permitted by the [LICENSE](https://github.com/ESandML/FCBFormer/blob/main/LICENSE). However, where possible, please inform us of this use for the facilitation of our impact case studies.
148 |
149 | ## 7. Acknowledgements
150 |
151 | This work was supported by the Science and Technology Facilities Council [grant number ST/S005404/1].
152 |
153 | This work was in part performed using a DiRAC Director’s Discretionary award. The work was carried out on the Cambridge Service for Data Driven Discovery (CSD3), part of which is operated by the University of Cambridge Research Computing on behalf of the STFC DiRAC HPC Facility (www.dirac.ac.uk). The DiRAC component of CSD3 was funded by BEIS capital funding via STFC capital grants ST/P002307/1 and ST/R002452/1 and STFC operations grant ST/R00689X/1. DiRAC is part of the National e-Infrastructure.
154 |
155 | This work makes use of data from the Kvasir-SEG dataset, available at https://datasets.simula.no/kvasir-seg/.
156 |
157 | This work makes use of data from the CVC-ClinicDB dataset, available at https://polyp.grand-challenge.org/CVCClinicDB/.
158 |
159 | This repository includes code (`./Models/pvt_v2.py`) ported from the [PVT/PVTv2](https://github.com/whai362/PVT) repository.
160 |
161 | ## 8. Additional information
162 |
163 | Links: [AIdDeCo Project](https://www.uclan.ac.uk/research/activity/machine-learning-cancer-detection), [CVML Group](https://www.uclan.ac.uk/research/activity/cvml)
164 |
165 | Contact: esanderson4@uclan.ac.uk
166 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/Models/pvt_v2.py:
--------------------------------------------------------------------------------
1 | #Ported from https://github.com/whai362/PVT (unmodified)
2 |
3 | import torch
4 | import torch.nn as nn
5 | import torch.nn.functional as F
6 | from functools import partial
7 |
8 | from timm.models.layers import DropPath, to_2tuple, trunc_normal_
9 | from timm.models.registry import register_model
10 | from timm.models.vision_transformer import _cfg
11 | import math
12 |
13 |
14 | class Mlp(nn.Module):
15 | def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0., linear=False):
16 | super().__init__()
17 | out_features = out_features or in_features
18 | hidden_features = hidden_features or in_features
19 | self.fc1 = nn.Linear(in_features, hidden_features)
20 | self.dwconv = DWConv(hidden_features)
21 | self.act = act_layer()
22 | self.fc2 = nn.Linear(hidden_features, out_features)
23 | self.drop = nn.Dropout(drop)
24 | self.linear = linear
25 | if self.linear:
26 | self.relu = nn.ReLU(inplace=True)
27 | self.apply(self._init_weights)
28 |
29 | def _init_weights(self, m):
30 | if isinstance(m, nn.Linear):
31 | trunc_normal_(m.weight, std=.02)
32 | if isinstance(m, nn.Linear) and m.bias is not None:
33 | nn.init.constant_(m.bias, 0)
34 | elif isinstance(m, nn.LayerNorm):
35 | nn.init.constant_(m.bias, 0)
36 | nn.init.constant_(m.weight, 1.0)
37 | elif isinstance(m, nn.Conv2d):
38 | fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
39 | fan_out //= m.groups
40 | m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
41 | if m.bias is not None:
42 | m.bias.data.zero_()
43 |
44 | def forward(self, x, H, W):
45 | x = self.fc1(x)
46 | if self.linear:
47 | x = self.relu(x)
48 | x = self.dwconv(x, H, W)
49 | x = self.act(x)
50 | x = self.drop(x)
51 | x = self.fc2(x)
52 | x = self.drop(x)
53 | return x
54 |
55 |
56 | class Attention(nn.Module):
57 | def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1, linear=False):
58 | super().__init__()
59 | assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
60 |
61 | self.dim = dim
62 | self.num_heads = num_heads
63 | head_dim = dim // num_heads
64 | self.scale = qk_scale or head_dim ** -0.5
65 |
66 | self.q = nn.Linear(dim, dim, bias=qkv_bias)
67 | self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
68 | self.attn_drop = nn.Dropout(attn_drop)
69 | self.proj = nn.Linear(dim, dim)
70 | self.proj_drop = nn.Dropout(proj_drop)
71 |
72 | self.linear = linear
73 | self.sr_ratio = sr_ratio
74 | if not linear:
75 | if sr_ratio > 1:
76 | self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
77 | self.norm = nn.LayerNorm(dim)
78 | else:
79 | self.pool = nn.AdaptiveAvgPool2d(7)
80 | self.sr = nn.Conv2d(dim, dim, kernel_size=1, stride=1)
81 | self.norm = nn.LayerNorm(dim)
82 | self.act = nn.GELU()
83 | self.apply(self._init_weights)
84 |
85 | def _init_weights(self, m):
86 | if isinstance(m, nn.Linear):
87 | trunc_normal_(m.weight, std=.02)
88 | if isinstance(m, nn.Linear) and m.bias is not None:
89 | nn.init.constant_(m.bias, 0)
90 | elif isinstance(m, nn.LayerNorm):
91 | nn.init.constant_(m.bias, 0)
92 | nn.init.constant_(m.weight, 1.0)
93 | elif isinstance(m, nn.Conv2d):
94 | fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
95 | fan_out //= m.groups
96 | m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
97 | if m.bias is not None:
98 | m.bias.data.zero_()
99 |
100 | def forward(self, x, H, W):
101 | B, N, C = x.shape
102 | q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
103 |
104 | if not self.linear:
105 | if self.sr_ratio > 1:
106 | x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
107 | x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
108 | x_ = self.norm(x_)
109 | kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
110 | else:
111 | kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
112 | else:
113 | x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
114 | x_ = self.sr(self.pool(x_)).reshape(B, C, -1).permute(0, 2, 1)
115 | x_ = self.norm(x_)
116 | x_ = self.act(x_)
117 | kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
118 | k, v = kv[0], kv[1]
119 |
120 | attn = (q @ k.transpose(-2, -1)) * self.scale
121 | attn = attn.softmax(dim=-1)
122 | attn = self.attn_drop(attn)
123 |
124 | x = (attn @ v).transpose(1, 2).reshape(B, N, C)
125 | x = self.proj(x)
126 | x = self.proj_drop(x)
127 |
128 | return x
129 |
130 |
131 | class Block(nn.Module):
132 |
133 | def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
134 | drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1, linear=False):
135 | super().__init__()
136 | self.norm1 = norm_layer(dim)
137 | self.attn = Attention(
138 | dim,
139 | num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
140 | attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio, linear=linear)
141 | # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
142 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
143 | self.norm2 = norm_layer(dim)
144 | mlp_hidden_dim = int(dim * mlp_ratio)
145 | self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop, linear=linear)
146 |
147 | self.apply(self._init_weights)
148 |
149 | def _init_weights(self, m):
150 | if isinstance(m, nn.Linear):
151 | trunc_normal_(m.weight, std=.02)
152 | if isinstance(m, nn.Linear) and m.bias is not None:
153 | nn.init.constant_(m.bias, 0)
154 | elif isinstance(m, nn.LayerNorm):
155 | nn.init.constant_(m.bias, 0)
156 | nn.init.constant_(m.weight, 1.0)
157 | elif isinstance(m, nn.Conv2d):
158 | fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
159 | fan_out //= m.groups
160 | m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
161 | if m.bias is not None:
162 | m.bias.data.zero_()
163 |
164 | def forward(self, x, H, W):
165 | x = x + self.drop_path(self.attn(self.norm1(x), H, W))
166 | x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
167 |
168 | return x
169 |
170 |
171 | class OverlapPatchEmbed(nn.Module):
172 | """ Image to Patch Embedding
173 | """
174 |
175 | def __init__(self, img_size=224, patch_size=7, stride=4, in_chans=3, embed_dim=768):
176 | super().__init__()
177 |
178 | img_size = to_2tuple(img_size)
179 | patch_size = to_2tuple(patch_size)
180 |
181 | assert max(patch_size) > stride, "Set larger patch_size than stride"
182 |
183 | self.img_size = img_size
184 | self.patch_size = patch_size
185 | self.H, self.W = img_size[0] // stride, img_size[1] // stride
186 | self.num_patches = self.H * self.W
187 | self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride,
188 | padding=(patch_size[0] // 2, patch_size[1] // 2))
189 | self.norm = nn.LayerNorm(embed_dim)
190 |
191 | self.apply(self._init_weights)
192 |
193 | def _init_weights(self, m):
194 | if isinstance(m, nn.Linear):
195 | trunc_normal_(m.weight, std=.02)
196 | if isinstance(m, nn.Linear) and m.bias is not None:
197 | nn.init.constant_(m.bias, 0)
198 | elif isinstance(m, nn.LayerNorm):
199 | nn.init.constant_(m.bias, 0)
200 | nn.init.constant_(m.weight, 1.0)
201 | elif isinstance(m, nn.Conv2d):
202 | fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
203 | fan_out //= m.groups
204 | m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
205 | if m.bias is not None:
206 | m.bias.data.zero_()
207 |
208 | def forward(self, x):
209 | x = self.proj(x)
210 | _, _, H, W = x.shape
211 | x = x.flatten(2).transpose(1, 2)
212 | x = self.norm(x)
213 |
214 | return x, H, W
215 |
216 |
217 | class PyramidVisionTransformerV2(nn.Module):
218 | def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dims=[64, 128, 256, 512],
219 | num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,
220 | attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
221 | depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], num_stages=4, linear=False):
222 | super().__init__()
223 | self.num_classes = num_classes
224 | self.depths = depths
225 | self.num_stages = num_stages
226 |
227 | dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
228 | cur = 0
229 |
230 | for i in range(num_stages):
231 | patch_embed = OverlapPatchEmbed(img_size=img_size if i == 0 else img_size // (2 ** (i + 1)),
232 | patch_size=7 if i == 0 else 3,
233 | stride=4 if i == 0 else 2,
234 | in_chans=in_chans if i == 0 else embed_dims[i - 1],
235 | embed_dim=embed_dims[i])
236 |
237 | block = nn.ModuleList([Block(
238 | dim=embed_dims[i], num_heads=num_heads[i], mlp_ratio=mlp_ratios[i], qkv_bias=qkv_bias, qk_scale=qk_scale,
239 | drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + j], norm_layer=norm_layer,
240 | sr_ratio=sr_ratios[i], linear=linear)
241 | for j in range(depths[i])])
242 | norm = norm_layer(embed_dims[i])
243 | cur += depths[i]
244 |
245 | setattr(self, f"patch_embed{i + 1}", patch_embed)
246 | setattr(self, f"block{i + 1}", block)
247 | setattr(self, f"norm{i + 1}", norm)
248 |
249 | # classification head
250 | self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
251 |
252 | self.apply(self._init_weights)
253 |
254 | def _init_weights(self, m):
255 | if isinstance(m, nn.Linear):
256 | trunc_normal_(m.weight, std=.02)
257 | if isinstance(m, nn.Linear) and m.bias is not None:
258 | nn.init.constant_(m.bias, 0)
259 | elif isinstance(m, nn.LayerNorm):
260 | nn.init.constant_(m.bias, 0)
261 | nn.init.constant_(m.weight, 1.0)
262 | elif isinstance(m, nn.Conv2d):
263 | fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
264 | fan_out //= m.groups
265 | m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
266 | if m.bias is not None:
267 | m.bias.data.zero_()
268 |
269 | def freeze_patch_emb(self):
270 | self.patch_embed1.requires_grad = False
271 |
272 | @torch.jit.ignore
273 | def no_weight_decay(self):
274 | return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
275 |
276 | def get_classifier(self):
277 | return self.head
278 |
279 | def reset_classifier(self, num_classes, global_pool=''):
280 | self.num_classes = num_classes
281 | self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
282 |
283 | def forward_features(self, x):
284 | B = x.shape[0]
285 |
286 | for i in range(self.num_stages):
287 | patch_embed = getattr(self, f"patch_embed{i + 1}")
288 | block = getattr(self, f"block{i + 1}")
289 | norm = getattr(self, f"norm{i + 1}")
290 | x, H, W = patch_embed(x)
291 | for blk in block:
292 | x = blk(x, H, W)
293 | x = norm(x)
294 | if i != self.num_stages - 1:
295 | x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
296 |
297 | return x.mean(dim=1)
298 |
299 | def forward(self, x):
300 | x = self.forward_features(x)
301 | x = self.head(x)
302 |
303 | return x
304 |
305 |
306 | class DWConv(nn.Module):
307 | def __init__(self, dim=768):
308 | super(DWConv, self).__init__()
309 | self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
310 |
311 | def forward(self, x, H, W):
312 | B, N, C = x.shape
313 | x = x.transpose(1, 2).view(B, C, H, W)
314 | x = self.dwconv(x)
315 | x = x.flatten(2).transpose(1, 2)
316 |
317 | return x
318 |
319 |
320 | def _conv_filter(state_dict, patch_size=16):
321 | """ convert patch embedding weight from manual patchify + linear proj to conv"""
322 | out_dict = {}
323 | for k, v in state_dict.items():
324 | if 'patch_embed.proj.weight' in k:
325 | v = v.reshape((v.shape[0], 3, patch_size, patch_size))
326 | out_dict[k] = v
327 |
328 | return out_dict
329 |
330 |
331 | @register_model
332 | def pvt_v2_b0(pretrained=False, **kwargs):
333 | model = PyramidVisionTransformerV2(
334 | patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True,
335 | norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
336 | **kwargs)
337 | model.default_cfg = _cfg()
338 |
339 | return model
340 |
341 |
342 | @register_model
343 | def pvt_v2_b1(pretrained=False, **kwargs):
344 | model = PyramidVisionTransformerV2(
345 | patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True,
346 | norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
347 | **kwargs)
348 | model.default_cfg = _cfg()
349 |
350 | return model
351 |
352 |
353 | @register_model
354 | def pvt_v2_b2(pretrained=False, **kwargs):
355 | model = PyramidVisionTransformerV2(
356 | patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True,
357 | norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], **kwargs)
358 | model.default_cfg = _cfg()
359 |
360 | return model
361 |
362 |
363 | @register_model
364 | def pvt_v2_b3(pretrained=False, **kwargs):
365 | model = PyramidVisionTransformerV2(
366 | patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True,
367 | norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],
368 | **kwargs)
369 | model.default_cfg = _cfg()
370 |
371 | return model
372 |
373 |
374 | @register_model
375 | def pvt_v2_b4(pretrained=False, **kwargs):
376 | model = PyramidVisionTransformerV2(
377 | patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True,
378 | norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],
379 | **kwargs)
380 | model.default_cfg = _cfg()
381 |
382 | return model
383 |
384 |
385 | @register_model
386 | def pvt_v2_b5(pretrained=False, **kwargs):
387 | model = PyramidVisionTransformerV2(
388 | patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True,
389 | norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],
390 | **kwargs)
391 | model.default_cfg = _cfg()
392 |
393 | return model
394 |
395 |
396 | @register_model
397 | def pvt_v2_b2_li(pretrained=False, **kwargs):
398 | model = PyramidVisionTransformerV2(
399 | patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True,
400 | norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], linear=True, **kwargs)
401 | model.default_cfg = _cfg()
402 |
403 | return model
404 |
--------------------------------------------------------------------------------