code
stringlengths
17
6.64M
class VariationOfInformation(ConfusionMatrixMetric): def __init__(self, metric: str='VARINFO'): 'Represents a variation of information metric.\n\n Args:\n metric (str): The identification string of the metric.\n ' super().__init__(metric) def calculate(self): ...
class VolumeSimilarity(ConfusionMatrixMetric): def __init__(self, metric: str='VOLSMTY'): 'Represents a volume similarity metric.\n\n Args:\n metric (str): The identification string of the metric.\n ' super().__init__(metric) def calculate(self): 'Calculates ...
class MeanAbsoluteError(NumpyArrayMetric): def __init__(self, metric: str='MAE'): 'Represents a mean absolute error metric.\n\n Args:\n metric (str): The identification string of the metric.\n ' super().__init__(metric) def calculate(self): 'Calculates the me...
class MeanSquaredError(NumpyArrayMetric): def __init__(self, metric: str='MSE'): 'Represents a mean squared error metric.\n\n Args:\n metric (str): The identification string of the metric.\n ' super().__init__(metric) def calculate(self): 'Calculates the mean...
class RootMeanSquaredError(NumpyArrayMetric): def __init__(self, metric: str='RMSE'): 'Represents a root mean squared error metric.\n\n Args:\n metric (str): The identification string of the metric.\n ' super().__init__(metric) def calculate(self): 'Calculate...
class NormalizedRootMeanSquaredError(NumpyArrayMetric): def __init__(self, metric: str='NRMSE'): 'Represents a normalized root mean squared error metric.\n\n Args:\n metric (str): The identification string of the metric.\n ' super().__init__(metric) def calculate(sel...
class CoefficientOfDetermination(NumpyArrayMetric): def __init__(self, metric: str='R2'): 'Represents a coefficient of determination (R^2) error metric.\n\n Args:\n metric (str): The identification string of the metric.\n ' super().__init__(metric) def calculate(self...
class PeakSignalToNoiseRatio(NumpyArrayMetric): def __init__(self, metric: str='PSNR'): 'Represents a peak signal to noise ratio metric.\n\n Args:\n metric (str): The identification string of the metric.\n ' super().__init__(metric) def calculate(self): 'Calc...
class StructuralSimilarityIndexMeasure(NumpyArrayMetric): def __init__(self, metric: str='SSIM'): 'Represents a structural similarity index measure metric.\n\n Args:\n metric (str): The identification string of the metric.\n ' super().__init__(metric) def calculate(s...
def get_reconstruction_metrics(): 'Gets a list with reconstruction metrics.\n\n Returns:\n list[Metric]: A list of metrics.\n ' return [PeakSignalToNoiseRatio(), StructuralSimilarityIndexMeasure()]
def get_segmentation_metrics(): 'Gets a list with segmentation metrics.\n\n Returns:\n list[Metric]: A list of metrics.\n ' return ((get_overlap_metrics() + get_distance_metrics()) + get_classical_metrics())
def get_regression_metrics(): 'Gets a list with regression metrics.\n\n Returns:\n list[Metric]: A list of metrics.\n ' return [CoefficientOfDetermination(), MeanAbsoluteError(), MeanSquaredError(), RootMeanSquaredError(), NormalizedRootMeanSquaredError()]
def get_overlap_metrics(): 'Gets a list of overlap-based metrics.\n\n Returns:\n list[Metric]: A list of metrics.\n ' return [AdjustedRandIndex(), AreaUnderCurve(), CohenKappaCoefficient(), DiceCoefficient(), InterclassCorrelation(), JaccardCoefficient(), MutualInformation(), RandIndex(), Surface...
def get_distance_metrics(): 'Gets a list of distance-based metrics.\n\n Returns:\n list[Metric]: A list of metrics.\n ' return [HausdorffDistance(), AverageDistance(), MahalanobisDistance(), VariationOfInformation(), GlobalConsistencyError(), ProbabilisticDistance()]
def get_classical_metrics(): 'Gets a list of classical metrics.\n\n Returns:\n list[Metric]: A list of metrics.\n ' return [Sensitivity(), Specificity(), Precision(), FMeasure(), Accuracy(), Fallout(), FalseNegativeRate(), TruePositive(), FalsePositive(), TrueNegative(), FalseNegative(), Referenc...
class Writer(abc.ABC): 'Represents an evaluation results writer base class.' @abc.abstractmethod def write(self, results: typing.List[evaluator.Result], **kwargs): 'Writes the evaluation results.\n\n Args:\n results (list of evaluator.Result): The evaluation results.\n ' ...
class ConsoleWriterHelper(): def __init__(self, use_logging: bool=False): 'Represents a console writer helper.\n\n Args:\n use_logging (bool): Indicates whether to use the Python logging module or not.\n ' self.use_logging = use_logging def format_and_write(self, lin...
class StatisticsAggregator(): def __init__(self, functions: dict=None): 'Represents a statistics evaluation results aggregator.\n\n Args:\n functions (dict): The numpy function handles to calculate the statistics.\n ' super().__init__() if (functions is None): ...
class CSVWriter(Writer): def __init__(self, path: str, delimiter: str=';'): 'Represents a CSV file evaluation results writer.\n\n Args:\n path (str): The CSV file path.\n delimiter (str): The CSV column delimiter.\n ' super().__init__() self.path = path...
class ConsoleWriter(Writer): def __init__(self, precision: int=3, use_logging: bool=False): 'Represents a console evaluation results writer.\n\n Args:\n precision (int): The decimal precision.\n use_logging (bool): Indicates whether to use the Python logging module or not.\n ...
class CSVStatisticsWriter(Writer): def __init__(self, path: str, delimiter: str=';', functions: dict=None): 'Represents a CSV file evaluation results statistics writer.\n\n Args:\n path (str): The CSV file path.\n delimiter (str): The CSV column delimiter.\n functi...
class ConsoleStatisticsWriter(Writer): def __init__(self, precision: int=3, use_logging: bool=False, functions: dict=None): 'Represents a console evaluation results statistics writer.\n\n Args:\n precision (int): The float precision.\n use_logging (bool): Indicates whether to...
class FilterParams(abc.ABC): 'Represents a filter parameters interface.'
class Filter(abc.ABC): def __init__(self): 'Filter base class.' self.verbose = False @abc.abstractmethod def execute(self, image: sitk.Image, params: FilterParams=None) -> sitk.Image: 'Executes a filter on an image.\n\n Args:\n image (sitk.Image): The image to f...
class FilterPipeline(): def __init__(self, filters: typing.List[Filter]=None): 'Represents a filter pipeline, which sequentially executes filters (:class:`.Filter`) on an image.\n\n Args:\n filters (list of Filter): The filters of the pipeline.\n ' self.filters = [] ...
class Relabel(pymia_fltr.Filter): def __init__(self, label_changes: typing.Dict[(int, typing.Union[(int, tuple)])]) -> None: 'Represents a relabel filter.\n\n Args:\n label_changes(typing.Dict[int, typing.Union[int, tuple]]): Label change rule where the key is the new label\n ...
class SizeCorrectionParams(pymia_fltr.FilterParams): def __init__(self, reference_shape: tuple) -> None: 'Represents size (shape) correction filter parameters used by the :class:`.SizeCorrection` filter.\n\n Args:\n reference_shape (tuple): The reference or target shape.\n ' ...
class SizeCorrection(pymia_fltr.Filter): def __init__(self, two_sided: bool=True, pad_constant: float=0.0) -> None: 'Represents a filter to correct the shape/size by padding or cropping.\n\n Args:\n two_sided (bool): Indicates whether the cropping and padding should be applied on one or...
class CmdlineExecutorParams(pymia_fltr.FilterParams): def __init__(self, arguments: typing.List[str]) -> None: 'Command line executor filter parameters used by the :class:`.CmdlineExecutor` filter.\n\n Args:\n arguments (typing.List[str]): Additional arguments for the command line execu...
class CmdlineExecutor(pymia_fltr.Filter): def __init__(self, executable_path: str): 'Represents a command line executable.\n\n Use this filter to execute for instance a C++ command line program, which loads and image, processes, and saves it.\n\n Args:\n executable_path (str): Th...
class BinaryThreshold(pymia_fltr.Filter): def __init__(self, threshold: float): 'Represents a binary threshold image filter.\n\n Args:\n threshold (float): The threshold value.\n ' super().__init__() self.threshold = threshold self.filter = sitk.BinaryThre...
class LargestNConnectedComponents(pymia_fltr.Filter): def __init__(self, number_of_components: int=1, consecutive_component_labels: bool=False): 'Represents a largest N connected components filter.\n\n Extracts the largest N connected components from a label image.\n By default the N compon...
class BiasFieldCorrectorParams(pymia_fltr.FilterParams): def __init__(self, mask: sitk.Image): "Bias field correction filter parameters used by the :class:`.BiasFieldCorrector` filter.\n\n Args:\n mask (sitk.Image): A mask image (0=background; 1=mask).\n\n Examples:\n\n ...
class BiasFieldCorrector(pymia_fltr.Filter): def __init__(self, convergence_threshold: float=0.001, max_iterations: typing.List[int]=(50, 50, 50, 50), fullwidth_at_halfmax: float=0.15, filter_noise: float=0.01, histogram_bins: int=200, control_points: typing.List[int]=(4, 4, 4), spline_order: int=3): 'Re...
class GradientAnisotropicDiffusion(pymia_fltr.Filter): def __init__(self, time_step: float=0.125, conductance: int=3, conductance_scaling_update_interval: int=1, no_iterations: int=5): 'Represents a gradient anisotropic diffusion filter.\n\n Args:\n time_step (float): The time step.\n ...
class NormalizeZScore(pymia_fltr.Filter): 'Represents a z-score normalization filter.' def execute(self, image: sitk.Image, params: pymia_fltr.FilterParams=None) -> sitk.Image: 'Executes a z-score normalization on an image.\n\n Args:\n image (sitk.Image): The image to filter.\n ...
class RescaleIntensity(pymia_fltr.Filter): def __init__(self, min_intensity: float, max_intensity: float): 'Represents a rescale intensity filter.\n\n Args:\n min_intensity (float): The min intensity value.\n max_intensity (float): The max intensity value.\n ' ...
class HistogramMatcherParams(pymia_fltr.FilterParams): def __init__(self, reference_image: sitk.Image): 'Histogram matching filter parameters used by the :class:`.HistogramMatcher` filter.\n\n Args:\n reference_image (sitk.Image): Reference image for the matching.\n ' sel...
class HistogramMatcher(pymia_fltr.Filter): def __init__(self, histogram_levels: int=256, match_points: int=1, threshold_mean_intensity: bool=True): 'Represents a histogram matching filter.\n\n Args:\n histogram_levels (int): Number of histogram levels.\n match_points (int): N...
class RegistrationType(enum.Enum): 'Represents the registration transformation type.' AFFINE = 1 SIMILARITY = 2 RIGID = 3 BSPLINE = 4
class RegistrationCallback(abc.ABC): def __init__(self) -> None: 'Represents the abstract handler for the registration callbacks.' self.registration_method = None self.fixed_image = None self.moving_image = None self.transform = None def set_params(self, registration_...
class MultiModalRegistrationParams(pymia_fltr.FilterParams): def __init__(self, fixed_image: sitk.Image, fixed_image_mask: sitk.Image=None, callbacks: typing.List[RegistrationCallback]=None): 'Represents parameters for the multi-modal rigid registration used by the :class:`.MultiModalRegistration` filter...
class MultiModalRegistration(pymia_fltr.Filter): def __init__(self, registration_type: RegistrationType=RegistrationType.RIGID, number_of_histogram_bins: int=200, learning_rate: float=1.0, step_size: float=0.001, number_of_iterations: int=200, relaxation_factor: float=0.5, shrink_factors: typing.List[int]=(2, 1,...
class PlotOnResolutionChangeCallback(RegistrationCallback): def __init__(self, plot_dir: str, file_name_prefix: str='') -> None: 'Represents a plotter for registrations.\n\n Saves the moving image on each resolution change and the registration end.\n\n Args:\n plot_dir (str): Pat...
class TestLargestNConnectedComponents(unittest.TestCase): def setUp(self): image = sitk.Image((5, 5), sitk.sitkUInt8) image.SetPixel((0, 0), 1) image.SetPixel((2, 0), 1) image.SetPixel((2, 1), 1) image.SetPixel((4, 0), 1) image.SetPixel((4, 1), 1) image.Set...
class TestNormalizeZScore(unittest.TestCase): def setUp(self): image = sitk.Image((4, 1), sitk.sitkUInt8) image.SetPixel((0, 0), 1) image.SetPixel((1, 0), 2) image.SetPixel((2, 0), 3) image.SetPixel((3, 0), 4) self.image = image self.desired = np.array([[(-...
class TestImageProperties(unittest.TestCase): def test_is_two_dimensional(self): x = 10 y = 10 image = sitk.Image([x, y], sitk.sitkUInt8) dut = img.ImageProperties(image) self.assertEqual(dut.is_two_dimensional(), True) self.assertEqual(dut.is_three_dimensional(), ...
class TestNumpySimpleITKImageBridge(unittest.TestCase): def setUp(self): dim_x = 5 dim_y = 10 dim_z = 3 self.no_vector_components = 4 self.origin_spacing_2d = (dim_x, dim_y) self.direction_2d = (0, 1, 1, 0) self.origin_spacing_3d = (dim_x, dim_y, dim_z) ...
class TestSimpleITKNumpyImageBridge(unittest.TestCase): def test_convert(self): x = 10 y = 10 z = 3 size = (x, y, z) image = sitk.Image(size, sitk.sitkUInt8) (array, properties) = img.SimpleITKNumpyImageBridge.convert(image) self.assertEqual(isinstance(arra...
def get_kernel(): weight = torch.zeros(8, 1, 3, 3) weight[(0, 0, 0, 0)] = 1 weight[(1, 0, 0, 1)] = 1 weight[(2, 0, 0, 2)] = 1 weight[(3, 0, 1, 0)] = 1 weight[(4, 0, 1, 2)] = 1 weight[(5, 0, 2, 0)] = 1 weight[(6, 0, 2, 1)] = 1 weight[(7, 0, 2, 2)] = 1 return weight
class PAR(nn.Module): def __init__(self, dilations, num_iter): super().__init__() self.dilations = dilations self.num_iter = num_iter kernel = get_kernel() self.register_buffer('kernel', kernel) self.pos = self.get_pos() self.dim = 2 self.w1 = 0.3 ...
def conv3x3(in_planes, out_planes, stride=1, dilation=1, padding=1): ' 3 x 3 conv' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=padding, dilation=dilation, bias=False)
def conv1x1(in_planes, out_planes, stride=1, dilation=1, padding=1): ' 1 x 1 conv' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, padding=padding, dilation=dilation, bias=False)
class LargeFOV(nn.Module): def __init__(self, in_planes, out_planes, dilation=5): super(LargeFOV, self).__init__() self.embed_dim = 512 self.dilation = dilation self.conv6 = conv3x3(in_planes=in_planes, out_planes=self.embed_dim, padding=self.dilation, dilation=self.dilation) ...
class ASPP(nn.Module): def __init__(self, in_planes, out_planes, atrous_rates=[6, 12, 18, 24]): super(ASPP, self).__init__() for (i, rate) in enumerate(atrous_rates): self.add_module(('c%d' % i), nn.Conv2d(in_planes, out_planes, 3, 1, padding=rate, dilation=rate, bias=True)) s...
class CTCHead(nn.Module): def __init__(self, in_dim, out_dim=4096, norm_last_layer=True, nlayers=3, hidden_dim=2048, bottleneck_dim=256): super().__init__() nlayers = max(nlayers, 1) if (nlayers == 1): self.mlp = nn.Linear(in_dim, bottleneck_dim) else: laye...
class network(nn.Module): def __init__(self, backbone, num_classes=None, pretrained=None, init_momentum=None, aux_layer=None): super().__init__() self.num_classes = num_classes self.init_momentum = init_momentum self.encoder = getattr(encoder, backbone)(pretrained=pretrained, aux_...
def setup_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True
def validate(model=None, data_loader=None, args=None): (preds, gts, cams, cams_aux) = ([], [], [], []) model.eval() avg_meter = AverageMeter() with torch.no_grad(): for (_, data) in tqdm(enumerate(data_loader), total=len(data_loader), ncols=100, ascii=' >='): (name, inputs, labels,...
def train(args=None): torch.cuda.set_device(args.local_rank) dist.init_process_group(backend=args.backend) logging.info(('Total gpus: %d, samples per gpu: %d...' % (dist.get_world_size(), args.spg))) time0 = datetime.datetime.now() time0 = time0.replace(microsecond=0) train_dataset = coco.Coco...
def setup_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True
def validate(model=None, data_loader=None, args=None): (preds, gts, cams, cams_aux) = ([], [], [], []) model.eval() avg_meter = AverageMeter() with torch.no_grad(): for (_, data) in tqdm(enumerate(data_loader), total=len(data_loader), ncols=100, ascii=' >='): (name, inputs, labels,...
def train(args=None): torch.cuda.set_device(args.local_rank) dist.init_process_group(backend=args.backend) logging.info(('Total gpus: %d, samples per gpu: %d...' % (dist.get_world_size(), args.spg))) time0 = datetime.datetime.now() time0 = time0.replace(microsecond=0) train_dataset = voc.VOC12...
def load_txt(txt_name): with open(txt_name) as f: name_list = [x for x in f.read().split('\n') if x] return name_list
def load_txt(txt_name): with open(txt_name) as f: name_list = [x for x in f.read().split('\n') if x] return name_list
def crf_inference(img, probs, t=10, scale_factor=1, labels=21): (h, w) = img.shape[:2] n_labels = labels d = dcrf.DenseCRF2D(w, h, n_labels) unary = unary_from_softmax(probs) unary = np.ascontiguousarray(unary) img_c = np.ascontiguousarray(img) d.setUnaryEnergy(unary) d.addPairwiseGaus...
def crf_inference_label(img, labels, t=10, n_labels=21, gt_prob=0.7): (h, w) = img.shape[:2] d = dcrf.DenseCRF2D(w, h, n_labels) unary = unary_from_labels(labels, n_labels, gt_prob=gt_prob, zero_unsure=False) d.setUnaryEnergy(unary) d.addPairwiseGaussian(sxy=3, compat=3) d.addPairwiseBilateral...
class DenseCRF(object): def __init__(self, iter_max, pos_w, pos_xy_std, bi_w, bi_xy_std, bi_rgb_std): self.iter_max = iter_max self.pos_w = pos_w self.pos_xy_std = pos_xy_std self.bi_w = bi_w self.bi_xy_std = bi_xy_std self.bi_rgb_std = bi_rgb_std def __call__...
def multilabel_score(y_true, y_pred): return metrics.f1_score(y_true, y_pred)
def _fast_hist(label_true, label_pred, num_classes): mask = ((label_true >= 0) & (label_true < num_classes)) hist = np.bincount(((num_classes * label_true[mask].astype(int)) + label_pred[mask]), minlength=(num_classes ** 2)) return hist.reshape(num_classes, num_classes)
def scores(label_trues, label_preds, num_classes=21): hist = np.zeros((num_classes, num_classes)) for (lt, lp) in zip(label_trues, label_preds): hist += _fast_hist(lt.flatten(), lp.flatten(), num_classes) acc = (np.diag(hist).sum() / hist.sum()) _acc_cls = (np.diag(hist) / hist.sum(axis=1)) ...
def pseudo_scores(label_trues, label_preds, num_classes=21): hist = np.zeros((num_classes, num_classes)) for (lt, lp) in zip(label_trues, label_preds): lt = lt.flatten() lp = lp.flatten() lt[(lp == 255)] = 255 lp[(lp == 255)] = 0 hist += _fast_hist(lt, lp, num_classes) ...
class CosWarmupAdamW(torch.optim.AdamW): def __init__(self, params, lr, weight_decay, betas, warmup_iter=None, max_iter=None, warmup_ratio=None, power=None, **kwargs): super().__init__(params, lr=lr, betas=betas, weight_decay=weight_decay, eps=1e-08) self.global_step = 0 self.warmup_iter ...
class PolyWarmupAdamW(torch.optim.AdamW): def __init__(self, params, lr, weight_decay, betas, warmup_iter=None, max_iter=None, warmup_ratio=None, power=None, **kwargs): super().__init__(params, lr=lr, betas=betas, weight_decay=weight_decay, eps=1e-08) self.global_step = 0 self.warmup_iter...
class PolyWarmupSGD(torch.optim.SGD): def __init__(self, params, lr, weight_decay, warmup_iter=None, max_iter=None, warmup_ratio=None, power=None, **kwargs): super().__init__(params, lr=lr, momentum=0.9, weight_decay=weight_decay) self.global_step = 0 self.warmup_iter = warmup_iter ...
class PConv2D(Conv2D): def __init__(self, *args, n_channels=3, mono=False, **kwargs): super().__init__(*args, **kwargs) self.input_spec = [InputSpec(ndim=4), InputSpec(ndim=4)] def build(self, input_shape): 'Adapted from original _Conv() layer of Keras \n param input_sh...
def plot_images(images, s=5): (_, axes) = plt.subplots(1, len(images), figsize=((s * len(images)), s)) if (len(images) == 1): axes = [axes] for (img, ax) in zip(images, axes): ax.imshow(img) plt.show()
def parse_args(): parser = ArgumentParser(description='Compute feature vectors for the objects and backgrounds for the MSRA10K dataset') parser.add_argument('-obj_path', '--obj_path', type=str, default='/home/bakrinski/datasets/MSRA10K/images/', help='OBJ_FOLDER_IMG input images path') parser.add_argument...
def getHistograms(img): imgHsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) (h, s, v) = cv2.split(imgHsv) (histH, _) = np.histogram(h, bins=NBINS, density=True) (histS, _) = np.histogram(s, bins=NBINS, density=True) (histV, _) = np.histogram(v, bins=NBINS, density=True) imgGray = cv2.cvtColor(img, c...
def getHistogramsWithMask(img, mask): imgHsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) (h, s, v) = cv2.split(imgHsv) (histH, _) = np.histogram(h, bins=NBINS, density=True, weights=mask) (histS, _) = np.histogram(s, bins=NBINS, density=True, weights=mask) (histV, _) = np.histogram(v, bins=NBINS, densi...
def main(): existsDataSetFile = os.path.isfile('dataset.txt') if (not existsDataSetFile): with open('dataset.txt', 'w') as fd: for i in range(0, 10000): print(i, file=fd) print('now obj') existsObj = os.path.isfile('histogramsOBJ.npy') if (not existsObj): ...
def bbox(img): rows = np.any(img, axis=1) cols = np.any(img, axis=0) (rmin, rmax) = np.where(rows)[0][[0, (- 1)]] (cmin, cmax) = np.where(cols)[0][[0, (- 1)]] return (rmin, rmax, cmin, cmax)
def main(): DATASETS = ['Augmented MSRA10K Experiment VIII'] DATASETS_NAME = ['Augmented MSRA10K Experiment VIII'] j = 0 for dataset in DATASETS: FOLDER_MASK = '/home/dvruiz/scriptPosProcessObjects/29_05_2019_FullMix/multipleBG/masks/' fileList = os.listdir(FOLDER_MASK) xs = np...
def autolabel(rects, counts): for (ii, rect) in enumerate(rects): height = rect.get_height() plt.text((rect.get_x() + (rect.get_width() / 2.0)), (1.02 * height), f'{counts[ii]:.2f}', ha='center', va='bottom')
def bbox(img): rows = np.any(img, axis=1) cols = np.any(img, axis=0) (rmin, rmax) = np.where(rows)[0][[0, (- 1)]] (cmin, cmax) = np.where(cols)[0][[0, (- 1)]] return (rmin, rmax, cmin, cmax)
def main(): n_bins = 10 DATASETS = ['Augmented MSRA10K Experiment VIII'] DATASETS_NAME = ['Augmented MSRA10K Experiment VIII'] j = 0 for dataset in DATASETS: FOLDER_MASK = '/home/dvruiz/scriptPosProcessObjects/29_05_2019_FullMix/multipleBG/masks/' fileList = os.listdir(FOLDER_MASK)...
def train(args, data_info, show_loss, data_nums): train_loader = data_info[0] val_loader = data_info[1] test_loader = data_info[2] num_feature = data_info[3] device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu')) model = L0_SIGN(args, num_feature, device) model = model.to(...
def evaluate(model, loader, device): model.eval() predictions = [] labels = [] edges_all = 0 with torch.no_grad(): for data in loader: data = data.to(device) (pred, _, _, num_edges) = model(data) pred = pred.detach().cpu().numpy() edges_all +...
class Dataset(InMemoryDataset): def __init__(self, root, dataset, pred_edges=1, transform=None, pre_transform=None): '\n if pred_edges=0, the dataset is used for SIGN/GNN only,\n we store the graph with edges in the .edge file\n ' self.path = root self.dataset = datas...
def create_twomoon_dataset(n, p): (relevant, y) = make_moons(n_samples=n, shuffle=True, noise=0.1, random_state=None) print(y.shape) noise_vector = norm.rvs(loc=0, scale=1, size=[n, (p - 2)]) data = np.concatenate([relevant, noise_vector], axis=1) print(data.shape) return (data, y)
def create_sin_dataset(n, p): 'This dataset was added to provide an example of L1 norm reg failure for presentation.\n ' assert (p == 2) x1 = np.random.uniform((- math.pi), math.pi, n).reshape(n, 1) x2 = np.random.uniform((- math.pi), math.pi, n).reshape(n, 1) y = np.sin(x1) data = np.conca...
def state_dict(model, include=None, exclude=None, cpu=True): if isinstance(model, nn.DataParallel): model = model.module state_dict = model.state_dict() matcher = IENameMatcher(include, exclude) with matcher: state_dict = {k: v for (k, v) in state_dict.items() if matcher.match(k)} ...
def load_state_dict(model, state_dict, include=None, exclude=None): if isinstance(model, nn.DataParallel): model = model.module matcher = IENameMatcher(include, exclude) with matcher: state_dict = {k: v for (k, v) in state_dict.items() if matcher.match(k)} stat = matcher.get_last_stat(...
def load_weights(model, filename, include=None, exclude=None, return_raw=True): if osp.isfile(filename): try: raw = weights = torch.load(filename) if (('model' in weights) and ('optimizer' in weights)): weights = weights['model'] try: loa...
class FeatureSelector(nn.Module): def __init__(self, input_dim, sigma, device): super(FeatureSelector, self).__init__() self.mu = torch.nn.Parameter((0.01 * torch.randn(input_dim)), requires_grad=True) self.noise = torch.randn(self.mu.size()) self.sigma = sigma self.device...
class GatingLayer(nn.Module): 'To implement L1-based gating layer (so that we can compare L1 with L0(STG) in a fair way)\n ' def __init__(self, input_dim, device): super(GatingLayer, self).__init__() self.mu = torch.nn.Parameter((0.01 * torch.randn(input_dim)), requires_grad=True) ...
class LinearLayer(nn.Sequential): def __init__(self, in_features, out_features, batch_norm=None, dropout=None, bias=None, activation=None): if (bias is None): bias = (batch_norm is None) modules = [nn.Linear(in_features, out_features, bias=bias)] if ((batch_norm is not None) a...
class MLPLayer(nn.Module): def __init__(self, input_dim, output_dim, hidden_dims, batch_norm=None, dropout=None, activation='relu', flatten=True): super().__init__() if (hidden_dims is None): hidden_dims = [] elif (type(hidden_dims) is int): hidden_dims = [hidden_d...
def PartialLogLikelihood(logits, fail_indicator, ties): "\n fail_indicator: 1 if the sample fails, 0 if the sample is censored.\n logits: raw output from model \n ties: 'noties' or 'efron' or 'breslow'\n " logL = 0 cumsum_y_pred = torch.cumsum(logits, 0) hazard_ratio = torch.exp(logits) ...
def calc_concordance_index(logits, fail_indicator, fail_time): "\n Compute the concordance-index value.\n Parameters:\n label_true: dict, like {'e': event, 't': time}, Observation and Time in survival analyze.\n y_pred: np.array, predictive proportional risk of network.\n Returns:\n ...