Spaces:
Runtime error
Runtime error
File size: 7,423 Bytes
5c718d1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
from utils import *
from modules import *
from data import *
from torch.utils.data import DataLoader
import torch.nn.functional as F
from datetime import datetime
import hydra
from omegaconf import DictConfig, OmegaConf
import pytorch_lightning as pl
from pytorch_lightning import Trainer
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.utilities.seed import seed_everything
import torch.multiprocessing
import seaborn as sns
from pytorch_lightning.callbacks import ModelCheckpoint
import sys
import pdb
import matplotlib as mpl
from skimage import measure
from scipy.stats import mode as statsmode
from collections import OrderedDict
import unet
import pdb
torch.multiprocessing.set_sharing_strategy("file_system")
colors = ("red", "palegreen", "green", "steelblue", "blue", "yellow", "lightgrey")
class_names = (
"Buildings",
"Cultivation",
"Natural green",
"Wetland",
"Water",
"Infrastructure",
"Background",
)
bounds = list(np.arange(len(class_names) + 1) + 1)
cmap = mpl.colors.ListedColormap(colors)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
def retouch_label(pred_label, true_label):
retouched_label = pred_label + 0
blobs = measure.label(retouched_label)
for idx in np.unique(blobs):
# most frequent label class in this blob
retouched_label[blobs == idx] = statsmode(true_label[blobs == idx])[0][0]
return retouched_label
def get_class_labels(dataset_name):
if dataset_name.startswith("cityscapes"):
return [
"road",
"sidewalk",
"parking",
"rail track",
"building",
"wall",
"fence",
"guard rail",
"bridge",
"tunnel",
"pole",
"polegroup",
"traffic light",
"traffic sign",
"vegetation",
"terrain",
"sky",
"person",
"rider",
"car",
"truck",
"bus",
"caravan",
"trailer",
"train",
"motorcycle",
"bicycle",
]
elif dataset_name == "cocostuff27":
return [
"electronic",
"appliance",
"food",
"furniture",
"indoor",
"kitchen",
"accessory",
"animal",
"outdoor",
"person",
"sports",
"vehicle",
"ceiling",
"floor",
"food",
"furniture",
"rawmaterial",
"textile",
"wall",
"window",
"building",
"ground",
"plant",
"sky",
"solid",
"structural",
"water",
]
elif dataset_name == "voc":
return [
"background",
"aeroplane",
"bicycle",
"bird",
"boat",
"bottle",
"bus",
"car",
"cat",
"chair",
"cow",
"diningtable",
"dog",
"horse",
"motorbike",
"person",
"pottedplant",
"sheep",
"sofa",
"train",
"tvmonitor",
]
elif dataset_name == "potsdam":
return ["roads and cars", "buildings and clutter", "trees and vegetation"]
else:
raise ValueError("Unknown Dataset {}".format(dataset_name))
@hydra.main(config_path="configs", config_name="train_config.yml")
def my_app(cfg: DictConfig) -> None:
OmegaConf.set_struct(cfg, False)
print(OmegaConf.to_yaml(cfg))
pytorch_data_dir = cfg.pytorch_data_dir
data_dir = join(cfg.output_root, "data")
log_dir = join(cfg.output_root, "logs")
checkpoint_dir = join(cfg.output_root, "checkpoints")
prefix = "{}/{}_{}".format(cfg.log_dir, cfg.dataset_name, cfg.experiment_name)
name = "{}_date_{}".format(prefix, datetime.now().strftime("%b%d_%H-%M-%S"))
cfg.full_name = prefix
os.makedirs(data_dir, exist_ok=True)
os.makedirs(log_dir, exist_ok=True)
os.makedirs(checkpoint_dir, exist_ok=True)
seed_everything(seed=0)
print(data_dir)
print(cfg.output_root)
geometric_transforms = T.Compose(
[T.RandomHorizontalFlip(), T.RandomResizedCrop(size=cfg.res, scale=(0.8, 1.0))]
)
photometric_transforms = T.Compose(
[
T.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.1),
T.RandomGrayscale(0.2),
T.RandomApply([T.GaussianBlur((5, 5))]),
]
)
sys.stdout.flush()
train_dataset = ContrastiveSegDataset(
pytorch_data_dir=pytorch_data_dir,
dataset_name=cfg.dataset_name,
crop_type=cfg.crop_type,
image_set="train",
transform=get_transform(cfg.res, False, cfg.loader_crop_type),
target_transform=get_transform(cfg.res, True, cfg.loader_crop_type),
cfg=cfg,
aug_geometric_transform=geometric_transforms,
aug_photometric_transform=photometric_transforms,
num_neighbors=cfg.num_neighbors,
mask=True,
pos_images=True,
pos_labels=True,
)
if cfg.dataset_name == "voc":
val_loader_crop = None
else:
val_loader_crop = "center"
val_dataset = ContrastiveSegDataset(
pytorch_data_dir=pytorch_data_dir,
dataset_name=cfg.dataset_name,
crop_type=None,
image_set="val",
transform=get_transform(320, False, val_loader_crop),
target_transform=get_transform(320, True, val_loader_crop),
mask=True,
cfg=cfg,
)
# val_dataset = MaterializedDataset(val_dataset)
train_loader = DataLoader(
train_dataset,
cfg.batch_size,
shuffle=True,
num_workers=cfg.num_workers,
pin_memory=True,
)
if cfg.submitting_to_aml:
val_batch_size = 16
else:
val_batch_size = cfg.batch_size
val_loader = DataLoader(
val_dataset,
val_batch_size,
shuffle=False,
num_workers=cfg.num_workers,
pin_memory=True,
)
model = LitUnsupervisedSegmenter(train_dataset.n_classes, cfg)
tb_logger = TensorBoardLogger(join(log_dir, name), default_hp_metric=False)
if cfg.submitting_to_aml:
gpu_args = dict(gpus=1, val_check_interval=250)
if gpu_args["val_check_interval"] > len(train_loader):
gpu_args.pop("val_check_interval")
else:
gpu_args = dict(gpus=-1, accelerator="ddp", val_check_interval=cfg.val_freq)
# gpu_args = dict(gpus=1, accelerator='ddp', val_check_interval=cfg.val_freq)
if gpu_args["val_check_interval"] > len(train_loader) // 4:
gpu_args.pop("val_check_interval")
trainer = Trainer(
log_every_n_steps=cfg.scalar_log_freq,
logger=tb_logger,
max_steps=cfg.max_steps,
callbacks=[
ModelCheckpoint(
dirpath=join(checkpoint_dir, name),
every_n_train_steps=400,
save_top_k=2,
monitor="test/cluster/mIoU",
mode="max",
)
],
**gpu_args
)
trainer.fit(model, train_loader, val_loader)
if __name__ == "__main__":
prep_args()
my_app()
|