code stringlengths 17 6.64M |
|---|
class BottleneckBase(nn.Module):
expansion = 4
NORM_TYPE = NormType.BATCH_NORM
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, conv_type=ConvType.HYPERCUBE, bn_momentum=0.1, D=3):
super(BottleneckBase, self).__init__()
self.conv1 = conv(inplanes, planes, kernel... |
class Bottleneck(BottleneckBase):
NORM_TYPE = NormType.BATCH_NORM
|
class ResNetEncoder(ResNet):
def __init__(self, **kwargs):
super().__init__(**kwargs)
del self.fc
del self.avgpool
def get_stages(self):
return [nn.Identity(), nn.Sequential(self.conv1, self.bn1, self.relu), nn.Sequential(self.maxpool, self.layer1), self.layer2, self.layer3, ... |
class Model(MinkowskiNetwork):
OUT_PIXEL_DIST = (- 1)
def __init__(self, in_channels, out_channels, config, D, **kwargs):
super(Model, self).__init__(D)
self.in_channels = in_channels
self.out_channels = out_channels
self.config = config
|
class ResNetBase(Model):
BLOCK = None
LAYERS = ()
INIT_DIM = 64
PLANES = (64, 128, 256, 512)
OUT_PIXEL_DIST = 32
HAS_LAST_BLOCK = False
CONV_TYPE = ConvType.HYPERCUBE
def __init__(self, in_channels, out_channels, config, D=3, **kwargs):
assert (self.BLOCK is not None)
... |
def post_act_block(in_channels, out_channels, kernel_size, indice_key=None, stride=1, padding=0, conv_type='subm', norm_fn=None):
if (conv_type == 'subm'):
conv = spconv.SubMConv3d(in_channels, out_channels, kernel_size, bias=False, indice_key=indice_key)
elif (conv_type == 'spconv'):
conv = s... |
class SparseBasicBlock(spconv.SparseModule):
expansion = 1
def __init__(self, inplanes, planes, stride=1, norm_fn=None, downsample=None, indice_key=None):
super(SparseBasicBlock, self).__init__()
assert (norm_fn is not None)
bias = (norm_fn is not None)
self.conv1 = spconv.Sub... |
class VoxelBackBone8x(nn.Module):
def __init__(self, input_channels, grid_size, **kwargs):
super().__init__()
norm_fn = partial(nn.BatchNorm1d, eps=0.001, momentum=0.01)
self.sparse_shape = (grid_size[::(- 1)] + [1, 0, 0])
self.conv_input = spconv.SparseSequential(spconv.SubMConv3... |
class VoxelResBackBone8x(nn.Module):
def __init__(self, input_channels, grid_size, **kwargs):
super().__init__()
norm_fn = partial(nn.BatchNorm1d, eps=0.001, momentum=0.01)
self.sparse_shape = (grid_size[::(- 1)] + [1, 0, 0])
self.conv_input = spconv.SparseSequential(spconv.SubMCo... |
class HeightCompression(nn.Module):
def __init__(self, **kwargs):
super().__init__()
def forward(self, encoded_spconv_tensor):
'\n Args:\n batch_dict:\n encoded_spconv_tensor: sparse tensor\n Returns:\n batch_dict:\n spatial_f... |
class VoxelNet(VoxelBackBone8x):
def __init__(self, in_channels, out_channels, config, D=3):
self.bev_stride = 8
voxel_size = [0.1, 0.1, 0.2]
point_cloud_range = np.array([(- 51.2), (- 51.2), (- 5.0), 51.2, 51.2, 3.0], dtype=np.float32)
self.grid_size = ((point_cloud_range[3:] - p... |
def main():
'\n Code for launching the pretraining\n '
parser = argparse.ArgumentParser(description='arg parser')
parser.add_argument('--cfg_file', type=str, default='config/slidr_minkunet.yaml', help='specify the config for training')
parser.add_argument('--resume_path', type=str, default=None,... |
class NCELoss(nn.Module):
'\n Compute the PointInfoNCE loss\n '
def __init__(self, temperature):
super(NCELoss, self).__init__()
self.temperature = temperature
self.criterion = nn.CrossEntropyLoss()
def forward(self, k, q):
logits = torch.mm(k, q.transpose(1, 0))
... |
class semantic_NCELoss(nn.Module):
'\n Compute the PointInfoNCE loss\n '
def __init__(self, temperature):
super(semantic_NCELoss, self).__init__()
self.temperature = temperature
self.criterion = nn.CrossEntropyLoss()
def forward(self, k, q, pseudo_label):
logits = t... |
class DistillKL(nn.Module):
'Distilling the Knowledge in a Neural Network'
def __init__(self, T):
super(DistillKL, self).__init__()
self.T = T
def forward(self, y_s, y_t):
p_s = F.log_softmax((y_s / self.T), dim=1)
p_t = F.softmax((y_t / self.T), dim=1)
loss = ((F... |
class CRDLoss(nn.Module):
"CRD Loss function\n includes two symmetric parts:\n (a) using teacher as anchor, choose positive and negatives over the student side\n (b) using student as anchor, choose positive and negatives over the teacher side\n Args:\n opt.s_dim: the dimension of student's feat... |
class ContrastLoss(nn.Module):
'\n contrastive loss, corresponding to Eq (18)\n '
def __init__(self, n_data):
super(ContrastLoss, self).__init__()
self.n_data = n_data
def forward(self, x):
bsz = x.shape[0]
m = (x.size(1) - 1)
Pn = (1 / float(self.n_data))
... |
class Embed(nn.Module):
'Embedding module'
def __init__(self, dim_in=1024, dim_out=128):
super(Embed, self).__init__()
self.linear = nn.Linear(dim_in, dim_out)
self.l2norm = Normalize(2)
def forward(self, x):
x = x.view(x.shape[0], (- 1))
x = self.linear(x)
... |
class Normalize(nn.Module):
'normalization layer'
def __init__(self, power=2):
super(Normalize, self).__init__()
self.power = power
def forward(self, x):
norm = x.pow(self.power).sum(1, keepdim=True).pow((1.0 / self.power))
out = x.div(norm)
return out
|
class ContrastMemory(nn.Module):
'\n memory buffer that supplies large amount of negative samples.\n '
def __init__(self, inputSize, outputSize, K, T=0.07, momentum=0.5):
super(ContrastMemory, self).__init__()
self.nLem = outputSize
self.unigrams = torch.ones(self.nLem)
... |
class AliasMethod(object):
'\n From: https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/\n '
def __init__(self, probs):
if (probs.sum() > 1):
probs.div_(probs.sum())
K = len(probs)
self.prob = torch.zeros(K)
... |
class PretrainDataModule(pl.LightningDataModule):
def __init__(self, config):
super().__init__()
self.config = config
if config['num_gpus']:
self.batch_size = (config['batch_size'] // config['num_gpus'])
else:
self.batch_size = config['batch_size']
def... |
def forgiving_state_restore(net, loaded_dict):
"\n Handle partial loading when some tensors don't match up in size.\n Because we want to use models that were trained off a different\n number of classes.\n "
loaded_dict = {k.replace('module.', ''): v for (k, v) in loaded_dict.items()}
net_state... |
def make_model(config):
'\n Build points and image models according to what is in the config\n '
model_fusion = fusionNet(config)
if (config['dataset'] == 'scannet'):
model_points = MinkUNet(3, config['model_n_out'], config)
else:
model_points = SPVCNN(1, config['model_n_out'], c... |
def _lookup_type(type_str):
if (type_str not in _data_type_reverse):
try:
type_str = _data_types[type_str]
except KeyError:
raise ValueError(('field type %r not in %r' % (type_str, _types_list)))
return _data_type_reverse[type_str]
|
def _split_line(line, n):
fields = line.split(None, n)
if (len(fields) == n):
fields.append('')
assert (len(fields) == (n + 1))
return fields
|
def make2d(array, cols=None, dtype=None):
"\n Make a 2D array from an array of arrays. The `cols' and `dtype'\n arguments can be omitted if the array is not empty.\n\n "
if (((cols is None) or (dtype is None)) and (not len(array))):
raise RuntimeError('cols and dtype must be specified for em... |
class PlyParseError(Exception):
"\n Raised when a PLY file cannot be parsed.\n\n The attributes `element', `row', `property', and `message' give\n additional information.\n\n "
def __init__(self, message, element=None, row=None, prop=None):
self.message = message
self.element = el... |
class PlyData(object):
'\n PLY file header and data.\n\n A PlyData instance is created in one of two ways: by the static\n method PlyData.read (to read a PLY file), or directly from __init__\n given a sequence of elements (which can then be written to a PLY\n file).\n\n '
def __init__(self,... |
def _open_stream(stream, read_or_write):
if hasattr(stream, read_or_write):
return (False, stream)
try:
return (True, open(stream, (read_or_write[0] + 'b')))
except TypeError:
raise RuntimeError('expected open file or filename')
|
class PlyElement(object):
"\n PLY file element.\n\n A client of this library doesn't normally need to instantiate this\n directly, so the following is only for the sake of documenting the\n internals.\n\n Creating a PlyElement instance is generally done in one of two ways:\n as a byproduct of Pl... |
class PlyProperty(object):
'\n PLY property description. This class is pure metadata; the data\n itself is contained in PlyElement instances.\n\n '
def __init__(self, name, val_dtype):
self._name = str(name)
self._check_name()
self.val_dtype = val_dtype
def _get_val_dty... |
class PlyListProperty(PlyProperty):
'\n PLY list property description.\n\n '
def __init__(self, name, len_dtype, val_dtype):
PlyProperty.__init__(self, name, val_dtype)
self.len_dtype = len_dtype
def _get_len_dtype(self):
return self._len_dtype
def _set_len_dtype(self,... |
def compute_slic(cam_token):
cam = nusc.get('sample_data', cam_token)
im = Image.open(os.path.join(nusc.dataroot, cam['filename']))
segments_slic = slic(im, n_segments=150, compactness=6, sigma=3.0, start_label=0).astype(np.uint8)
im = Image.fromarray(segments_slic)
im.save((('./superpixels/nuscen... |
def compute_slic_30(cam_token):
cam = nusc.get('sample_data', cam_token)
im = Image.open(os.path.join(nusc.dataroot, cam['filename']))
segments_slic = slic(im, n_segments=30, compactness=6, sigma=3.0, start_label=0).astype(np.uint8)
im = Image.fromarray(segments_slic)
im.save((('./superpixels/nusc... |
def confusion_matrix(preds, labels, num_classes):
hist = torch.bincount(((num_classes * labels) + preds), minlength=(num_classes ** 2)).reshape(num_classes, num_classes).float()
return hist
|
def compute_IoU_from_cmatrix(hist, ignore_index=None):
'Computes the Intersection over Union (IoU).\n Args:\n hist: confusion matrix.\n Returns:\n m_IoU, fw_IoU, and matrix IoU\n '
if (ignore_index is not None):
hist[ignore_index] = 0.0
intersection = torch.diag(hist)
un... |
def compute_IoU(preds, labels, num_classes, ignore_index=None):
'Computes the Intersection over Union (IoU).'
hist = confusion_matrix(preds, labels, num_classes)
return compute_IoU_from_cmatrix(hist, ignore_index)
|
def _lookup_type(type_str):
if (type_str not in _data_type_reverse):
try:
type_str = _data_types[type_str]
except KeyError:
raise ValueError(('field type %r not in %r' % (type_str, _types_list)))
return _data_type_reverse[type_str]
|
def _split_line(line, n):
fields = line.split(None, n)
if (len(fields) == n):
fields.append('')
assert (len(fields) == (n + 1))
return fields
|
def make2d(array, cols=None, dtype=None):
"\n Make a 2D array from an array of arrays. The `cols' and `dtype'\n arguments can be omitted if the array is not empty.\n\n "
if (((cols is None) or (dtype is None)) and (not len(array))):
raise RuntimeError('cols and dtype must be specified for em... |
class PlyParseError(Exception):
"\n Raised when a PLY file cannot be parsed.\n\n The attributes `element', `row', `property', and `message' give\n additional information.\n\n "
def __init__(self, message, element=None, row=None, prop=None):
self.message = message
self.element = el... |
class PlyData(object):
'\n PLY file header and data.\n\n A PlyData instance is created in one of two ways: by the static\n method PlyData.read (to read a PLY file), or directly from __init__\n given a sequence of elements (which can then be written to a PLY\n file).\n\n '
def __init__(self,... |
def _open_stream(stream, read_or_write):
if hasattr(stream, read_or_write):
return (False, stream)
try:
return (True, open(stream, (read_or_write[0] + 'b')))
except TypeError:
raise RuntimeError('expected open file or filename')
|
class PlyElement(object):
"\n PLY file element.\n\n A client of this library doesn't normally need to instantiate this\n directly, so the following is only for the sake of documenting the\n internals.\n\n Creating a PlyElement instance is generally done in one of two ways:\n as a byproduct of Pl... |
class PlyProperty(object):
'\n PLY property description. This class is pure metadata; the data\n itself is contained in PlyElement instances.\n\n '
def __init__(self, name, val_dtype):
self._name = str(name)
self._check_name()
self.val_dtype = val_dtype
def _get_val_dty... |
class PlyListProperty(PlyProperty):
'\n PLY list property description.\n\n '
def __init__(self, name, len_dtype, val_dtype):
PlyProperty.__init__(self, name, val_dtype)
self.len_dtype = len_dtype
def _get_len_dtype(self):
return self._len_dtype
def _set_len_dtype(self,... |
def collect_point_data(scene_name):
label_map = scannet_utils.read_label_mapping(opt.label_map_file, label_from='raw_category', label_to='nyu40id')
data_folder = os.path.join(opt.scannet_path, scene_name)
out_filename = os.path.join(data_folder, (scene_name + '_new_semantic.npy'))
seg_filename = os.pa... |
def preprocess_scenes(scene_name):
try:
collect_point_data(scene_name)
print('name: ', scene_name)
except Exception as e:
sys.stderr.write((scene_name + 'ERROR!!'))
sys.stderr.write(str(e))
sys.exit((- 1))
|
def main():
scenes = [d for d in os.listdir(opt.scannet_path) if os.path.isdir(os.path.join(opt.scannet_path, d))]
scenes.sort()
print(opt.scannet_path)
print(('Find %d scenes' % len(scenes)))
print('Extract points (Vertex XYZ, RGB, NxNyNz, Label, Instance-label)')
pool = mp.Pool(opt.num_proc)... |
def parse_args():
parser = argparse.ArgumentParser(description='Prompt engeering script')
parser.add_argument('--model', default='RN50', choices=['RN50', 'RN101', 'RN50x4', 'RN50x16', 'ViT32', 'ViT16'], help='clip model name')
parser.add_argument('--class-set', default=['voc'], nargs='+', choices=['kitti'... |
def zeroshot_classifier(model_name, classnames, templates):
(model, preprocess) = clip.load(model_name)
with torch.no_grad():
zeroshot_weights = []
for classname in classnames:
texts = [template.format(classname) for template in templates]
texts = clip.tokenize(texts).c... |
def generate_config(file):
with open(file, 'r') as f:
config = yaml.load(f, Loader=yaml.FullLoader)
config['datetime'] = dt.today().strftime('%d%m%y-%H%M')
return config
|
def save_checkpoint(self):
trained_epoch = (self.cur_epoch + 1)
ckpt_name = (self.ckpt_dir / ('checkpoint_epoch_%d' % trained_epoch))
checkpoint_state = {}
checkpoint_state['epoch'] = trained_epoch
checkpoint_state['it'] = self.it
if isinstance(self.model, torch.nn.parallel.DistributedDataPara... |
def resume(self, filename):
if (not os.path.isfile(filename)):
raise FileNotFoundError
self.logger.info(f'==> Loading parameters from checkpoint {filename}')
checkpoint = torch.load(filename, map_location='cpu')
self.model.load_params(checkpoint['model_state'], strict=True)
self.logger.inf... |
def represents_int(s):
try:
int(s)
return True
except ValueError:
return False
|
def read_aggregation(filename):
assert os.path.isfile(filename)
object_id_to_segs = {}
label_to_segs = {}
with open(filename) as f:
data = json.load(f)
num_objects = len(data['segGroups'])
for i in range(num_objects):
object_id = (data['segGroups'][i]['objectId'] + ... |
def read_segmentation(filename):
assert os.path.isfile(filename)
seg_to_verts = {}
with open(filename) as f:
data = json.load(f)
num_verts = len(data['segIndices'])
for i in range(num_verts):
seg_id = data['segIndices'][i]
if (seg_id in seg_to_verts):
... |
def read_label_mapping(filename, label_from='raw_category', label_to='nyu40id'):
assert os.path.isfile(filename)
mapping = dict()
with open(filename) as csvfile:
reader = csv.DictReader(csvfile, delimiter='\t')
for row in reader:
mapping[row[label_from]] = int(row[label_to])
... |
def read_scene_types_mapping(filename, remove_spaces=True):
assert os.path.isfile(filename)
mapping = dict()
lines = open(filename).read().splitlines()
lines = [line.split('\t') for line in lines]
if remove_spaces:
mapping = {x[1].strip(): int(x[0]) for x in lines}
else:
mappin... |
def visualize_label_image(filename, image):
height = image.shape[0]
width = image.shape[1]
vis_image = np.zeros([height, width, 3], dtype=np.uint8)
color_palette = create_color_palette()
for (idx, color) in enumerate(color_palette):
vis_image[(image == idx)] = color
imageio.imwrite(fil... |
def visualize_instance_image(filename, image):
height = image.shape[0]
width = image.shape[1]
vis_image = np.zeros([height, width, 3], dtype=np.uint8)
color_palette = create_color_palette()
instances = np.unique(image)
for (idx, inst) in enumerate(instances):
vis_image[(image == inst)]... |
def create_color_palette():
return [(174, 199, 232), (152, 223, 138), (31, 119, 180), (255, 187, 120), (188, 189, 34), (140, 86, 75), (255, 152, 150), (214, 39, 40), (197, 176, 213), (148, 103, 189), (196, 156, 148), (23, 190, 207), (247, 182, 210), (219, 219, 141), (255, 127, 14), (158, 218, 229), (44, 160, 44),... |
class BatchgeneratorsTransform(tfm.Transform):
'Example wrapper for `batchgenerators <https://github.com/MIC-DKFZ/batchgenerators>`_ transformations.'
def __init__(self, transforms, entries=(defs.KEY_IMAGES, defs.KEY_LABELS)) -> None:
super().__init__()
self.transforms = transforms
se... |
class TorchIOTransform(tfm.Transform):
'Example wrapper for `TorchIO <https://github.com/fepegar/torchio>`_ transformations.'
def __init__(self, transforms: list, entries=(defs.KEY_IMAGES, defs.KEY_LABELS)) -> None:
super().__init__()
self.transforms = transforms
self.entries = entrie... |
class BatchgeneratorsTransform(tfm.Transform):
'Example wrapper for `batchgenerators <https://github.com/MIC-DKFZ/batchgenerators>`_ transformations.'
def __init__(self, transforms, entries=(defs.KEY_IMAGES, defs.KEY_LABELS)) -> None:
super().__init__()
self.transforms = transforms
se... |
class TorchIOTransform(tfm.Transform):
'Example wrapper for `TorchIO <https://github.com/fepegar/torchio>`_ transformations.'
def __init__(self, transforms: list, entries=(defs.KEY_IMAGES, defs.KEY_LABELS)) -> None:
super().__init__()
self.transforms = transforms
self.entries = entrie... |
def plot_sample(plot_dir: str, id_: str, sample: dict):
plt.imsave(os.path.join(plot_dir, f'{id_}_image_channel0.png'), sample[defs.KEY_IMAGES][0])
plt.imsave(os.path.join(plot_dir, f'{id_}_image_channel1.png'), sample[defs.KEY_IMAGES][1])
plt.imsave(os.path.join(plot_dir, f'{id_}_label.png'), sample[defs... |
def main(hdf_file, plot_dir):
os.makedirs(plot_dir, exist_ok=True)
extractor = extr.DataExtractor(categories=(defs.KEY_IMAGES, defs.KEY_LABELS))
indexing_strategy = extr.SliceIndexing()
dataset = extr.PymiaDatasource(hdf_file, indexing_strategy, extractor)
seed = 1
np.random.seed(seed)
sam... |
class FileTypes(enum.Enum):
T1 = 1
T2 = 2
GT = 3
MASK = 4
AGE = 5
GPA = 6
GENDER = 7
|
class Subject(data.SubjectFile):
def __init__(self, subject: str, files: dict):
super().__init__(subject, images={FileTypes.T1.name: files[FileTypes.T1], FileTypes.T2.name: files[FileTypes.T2]}, labels={FileTypes.GT.name: files[FileTypes.GT]}, mask={FileTypes.MASK.name: files[FileTypes.MASK]}, numerical=... |
class LoadData(file_load.Load):
def __call__(self, file_name: str, id_: str, category: str, subject_id: str) -> typing.Tuple[(np.ndarray, typing.Union[(conv.ImageProperties, None)])]:
if (id_ == FileTypes.AGE.name):
with open(file_name, 'r') as f:
value = np.asarray([int(f.rea... |
class FileTypes(enum.Enum):
T1 = 1
T2 = 2
GT = 3
MASK = 4
AGE = 5
GPA = 6
GENDER = 7
|
class LoadData(file_load.Load):
def __call__(self, file_name: str, id_: str, category: str, subject_id: str) -> typing.Tuple[(np.ndarray, typing.Union[(conv.ImageProperties, None)])]:
if (id_ == FileTypes.AGE.name):
with open(file_name, 'r') as f:
value = np.asarray([int(f.rea... |
class Subject(data.SubjectFile):
def __init__(self, subject: str, files: dict):
super().__init__(subject, images={FileTypes.T1.name: files[FileTypes.T1], FileTypes.T2.name: files[FileTypes.T2]}, labels={FileTypes.GT.name: files[FileTypes.GT]}, mask={FileTypes.MASK.name: files[FileTypes.MASK]}, numerical=... |
def main(hdf_file: str, data_dir: str, meta: bool):
subjects = get_subject_files(data_dir)
if os.path.exists(hdf_file):
os.remove(hdf_file)
with crt.get_writer(hdf_file) as writer:
callbacks = crt.get_default_callbacks(writer, meta_only=meta)
transform = tfm.IntensityNormalization(... |
def get_subject_files(data_dir: str) -> typing.List[Subject]:
'Collects the files for all the subjects in the data directory.\n\n Args:\n data_dir (str): The data directory.\n\n Returns:\n typing.List[data.SubjectFile]: The list of the collected subject files.\n\n '
subject_dirs = [subj... |
def get_full_file_path(id_: str, root_dir: str, file_key) -> str:
"Gets the full file path for an image.\n Args:\n id_ (str): The image identification.\n root_dir (str): The image' root directory.\n file_key (object): A human readable identifier used to identify the image.\n Returns:\n ... |
def main(hdf_file, is_meta):
if (not is_meta):
extractor = extr.DataExtractor(categories=(defs.KEY_IMAGES,))
else:
extractor = extr.FilesystemDataExtractor(categories=(defs.KEY_IMAGES,))
transform = tfm.Permute(permutation=(2, 0, 1), entries=(defs.KEY_IMAGES,))
indexing_strategy = extr... |
def main(hdf_file):
extractor = extr.PadDataExtractor((2, 2, 2), extr.DataExtractor(categories=(defs.KEY_IMAGES,)))
transform = tfm.Permute(permutation=(3, 0, 1, 2), entries=(defs.KEY_IMAGES,))
indexing_strategy = extr.PatchWiseIndexing(patch_shape=(32, 32, 32))
dataset = extr.PymiaDatasource(hdf_file... |
def main(hdf_file):
extractor = extr.DataExtractor(categories=(defs.KEY_IMAGES,))
transform = None
indexing_strategy = extr.SliceIndexing()
dataset = extr.PymiaDatasource(hdf_file, indexing_strategy, extractor, transform)
direct_extractor = extr.ComposeExtractor([extr.ImagePropertiesExtractor(), e... |
def main(data_dir: str, result_file: str, result_summary_file: str):
metrics = [metric.DiceCoefficient(), metric.HausdorffDistance(percentile=95, metric='HDRFDST95'), metric.VolumeSimilarity()]
labels = {1: 'WHITEMATTER', 2: 'GREYMATTER', 5: 'THALAMUS'}
evaluator = eval_.SegmentationEvaluator(metrics, lab... |
class DummyNetwork(nn.Module):
def forward(self, x):
return torch.randint(0, 5, (x.size(0), 1, *x.size()[2:]))
|
def main(hdf_file: str, log_dir: str):
metrics = [metric.DiceCoefficient()]
labels = {1: 'WHITEMATTER', 2: 'GREYMATTER', 5: 'THALAMUS'}
evaluator = eval_.SegmentationEvaluator(metrics, labels)
functions = {'MEAN': np.mean, 'STD': np.std}
statistics_aggregator = writer.StatisticsAggregator(function... |
def main(hdf_file: str, log_dir: str):
metrics = [metric.DiceCoefficient()]
labels = {1: 'WHITEMATTER', 2: 'GREYMATTER', 5: 'THALAMUS'}
evaluator = eval_.SegmentationEvaluator(metrics, labels)
functions = {'MEAN': np.mean, 'STD': np.std}
statistics_aggregator = writer.StatisticsAggregator(function... |
def main(url: str, data_dir: str):
print(f'Downloading... ({url})')
resp = request.urlopen(url)
zip_ = zipfile.ZipFile(io.BytesIO(resp.read()))
print(f'Extracting... (to {data_dir})')
members = zip_.infolist()
for member in members:
if (member.filename.startswith('Subject_') or member.... |
class ConvDONormReLu2D(nn.Sequential):
def __init__(self, in_ch, out_ch, dropout_p: float=0.0, norm: str='bn'):
super().__init__()
self.add_module('conv', nn.Conv2d(in_ch, out_ch, 3, padding=1))
if (dropout_p > 0):
self.add_module('dropout', nn.Dropout2d(p=dropout_p, inplace=T... |
class DownConv2D(nn.Module):
def __init__(self, in_ch, out_ch, dropout_p: float=0.0, norm: str='bn'):
super().__init__()
self.double_conv = nn.Sequential(ConvDONormReLu2D(in_ch, out_ch, dropout_p, norm), ConvDONormReLu2D(out_ch, out_ch, dropout_p, norm))
self.pool = nn.MaxPool2d(2)
d... |
class UpConv2D(nn.Module):
def __init__(self, in_ch, out_ch, dropout_p: float=0.0, norm: str='bn', transpose: bool=False):
super().__init__()
self.transpose = transpose
if self.transpose:
self.upconv = nn.ConvTranspose2d(in_ch, out_ch, 2, stride=2)
else:
se... |
class UNetModel(nn.Module):
def __init__(self, ch_in: int, ch_out: int, n_channels: int=32, n_pooling: int=3, dropout_p: float=0.2, norm: str='bn', **kwargs):
super().__init__()
n_classes = ch_out
ch_out = n_channels
self.down_convs = nn.ModuleList()
for i in range(n_pooli... |
class ConvBlock(tf.keras.layers.Layer):
def __init__(self, layer_idx, filters_root, kernel_size, dropout_rate, padding, activation, **kwargs):
super(ConvBlock, self).__init__(**kwargs)
self.layer_idx = layer_idx
self.filters_root = filters_root
self.kernel_size = kernel_size
... |
class UpconvBlock(tf.keras.layers.Layer):
def __init__(self, layer_idx, filters_root, kernel_size, pool_size, padding, activation, **kwargs):
super(UpconvBlock, self).__init__(**kwargs)
self.layer_idx = layer_idx
self.filters_root = filters_root
self.kernel_size = kernel_size
... |
class CropConcatBlock(tf.keras.layers.Layer):
def call(self, x, skip_x, **kwargs):
skip_shape = tf.shape(skip_x)
up_shape = tf.shape(x)
height_diff = (skip_shape[1] - up_shape[1])
width_diff = (skip_shape[2] - up_shape[2])
height_pad = [(height_diff // 2), ((height_diff //... |
def _get_filter_count(layer_idx, filters_root):
return ((2 ** layer_idx) * filters_root)
|
def build_model(nx=None, ny=None, channels: int=1, num_classes: int=2, layer_depth: int=5, filters_root: int=64, kernel_size: int=3, pool_size: int=2, dropout_rate: int=0.0, padding: str='same', activation='relu') -> tf.keras.Model:
inputs = tf.keras.Input(shape=(nx, ny, channels), name='inputs')
x = inputs
... |
def main(hdf_file, log_dir):
metrics = [metric.DiceCoefficient()]
labels = {1: 'WHITEMATTER', 2: 'GREYMATTER', 3: 'HIPPOCAMPUS', 4: 'AMYGDALA', 5: 'THALAMUS'}
evaluator = eval_.SegmentationEvaluator(metrics, labels)
functions = {'MEAN': np.mean, 'STD': np.std}
statistics_aggregator = writer.Statis... |
def main(hdf_file, log_dir):
metrics = [metric.DiceCoefficient()]
labels = {1: 'WHITEMATTER', 2: 'GREYMATTER', 3: 'HIPPOCAMPUS', 4: 'AMYGDALA', 5: 'THALAMUS'}
evaluator = eval_.SegmentationEvaluator(metrics, labels)
functions = {'MEAN': np.mean, 'STD': np.std}
statistics_aggregator = writer.Statis... |
class Assembler(abc.ABC):
'Interface for assembling images from batch, which contain parts (chunks) of the images only.'
@abc.abstractmethod
def add_batch(self, to_assemble, sample_indices, last_batch=False, **kwargs):
'Add the batch results to be assembled.\n\n Args:\n to_assem... |
def numpy_zeros(shape: tuple, assembling_key: str, subject_index: int):
return np.zeros(shape)
|
class SubjectAssembler(Assembler):
def __init__(self, datasource: extr.PymiaDatasource, zero_fn=numpy_zeros, assemble_interaction_fn=None):
"Assembles predictions of one or multiple subjects.\n\n Assumes that the network output, i.e. to_assemble, is of shape (B, ..., C)\n where B is the bat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.