repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
mtl-segmentation-mtl | mtl-segmentation-mtl/datasets/nullloader.py | """
Null Loader
"""
import numpy as np
import torch
from torch.utils import data
num_classes = 19
ignore_label = 255
class NullLoader(data.Dataset):
"""
Null Dataset for Performance
"""
def __init__(self,crop_size):
self.imgs = range(200)
self.crop_size = crop_size
def __getitem__... | 576 | 23.041667 | 158 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/datasets/camvid.py | """
Camvid Dataset Loader
"""
import os
import sys
import numpy as np
from PIL import Image
from torch.utils import data
import logging
import datasets.uniform as uniform
import json
from config import cfg
# trainid_to_name = cityscapes_labels.trainId2name
# id_to_trainid = cityscapes_labels.label2trainid
num_classe... | 10,286 | 35.349823 | 133 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/datasets/__init__.py | """
Dataset setup and loaders
"""
from datasets import cityscapes
from datasets import mapillary
from datasets import kitti
from datasets import tartanair_semantic
from datasets import tartanair_trav
from datasets import tartanair_multi
from datasets import camvid
import torchvision.transforms as standard_transforms
i... | 15,208 | 39.994609 | 133 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/datasets/mapillary.py | """
Mapillary Dataset Loader
"""
from PIL import Image
from torch.utils import data
import os
import numpy as np
import json
import datasets.uniform as uniform
from config import cfg
num_classes = 65
ignore_label = 65
root = cfg.DATASET.MAPILLARY_DIR
config_fn = os.path.join(root, 'config.json')
id_to_ignore_or_group ... | 6,713 | 33.430769 | 86 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/datasets/tartanair_trav.py | """
TartanAir Traversability Dataset Loader
"""
import os
import sys
import numpy as np
from PIL import Image
from torch.utils import data
import logging
import datasets.uniform as uniform
import datasets.tartanair_labels as tartanair_labels
import json
from config import cfg
import random
trainid_to_name = tartana... | 9,950 | 34.162544 | 142 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/datasets/tartanair_semantic.py | """
TartanAir Semantic Dataset Loader
"""
import os
import sys
import numpy as np
from PIL import Image
from torch.utils import data
import logging
import datasets.uniform as uniform
import datasets.tartanair_labels as tartanair_labels
import json
from config import cfg
import random
trainid_to_name = tartanair_lab... | 10,167 | 34.062069 | 146 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/network/Resnet.py | """
# Code Adapted from:
# https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
#
# BSD 3-Clause License
#
# Copyright (c) 2017,
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are me... | 8,386 | 31.890196 | 90 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/network/squeeze.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch import nn
from collections import OrderedDict
from torch.nn.modules.container import Sequential
class Sequent... | 5,044 | 31.133758 | 120 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/network/wider_resnet.py | """
# Code adapted from:
# https://github.com/mapillary/inplace_abn/
#
# BSD 3-Clause License
#
# Copyright (c) 2017, mapillary
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistribution... | 15,629 | 35.776471 | 132 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/network/deepv3.py | """
# Code Adapted from:
# https://github.com/sthalles/deeplab_v3
#
# MIT License
#
# Copyright (c) 2018 Thalles Santos Silva
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restric... | 14,144 | 35.74026 | 138 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/network/SEresnext.py | """
# Code adapted from:
# https://github.com/Cadene/pretrained-models.pytorch
#
# BSD 3-Clause License
#
# Copyright (c) 2017, Remi Cadene
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Re... | 15,124 | 36.071078 | 98 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/network/mynn.py | """
Custom Norm wrappers to enable sync BN, regular BN and for weight initialization
"""
import torch.nn as nn
from config import cfg
from apex import amp
def Norm2d(in_channels):
"""
Custom Norm Function to allow flexible switching
"""
layer = getattr(cfg.MODEL, 'BNFUNC')
normalization_layer = la... | 1,190 | 27.357143 | 80 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/network/__init__.py | """
Network Initializations
"""
import logging
import importlib
import torch
def get_net(args, criterion, criterion2=None, tasks=None):
"""
Get Network Architecture based on arguments provided
"""
net = get_model(network=args.arch, num_classes=args.dataset_cls.num_classes,
criter... | 1,260 | 26.413043 | 100 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/utils/misc.py | """
Miscellanous Functions
"""
import sys
import re
import os
import shutil
import torch
from datetime import datetime
import logging
from subprocess import call
import shlex
from tensorboardX import SummaryWriter
import numpy as np
import torchvision.transforms as standard_transforms
import torchvision.utils as vutil... | 19,522 | 41.441304 | 128 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/utils/my_data_parallel.py |
"""
# Code adapted from:
# https://github.com/pytorch/pytorch/blob/master/torch/nn/parallel/data_parallel.py
#
# BSD 3-Clause License
#
# Copyright (c) 2017,
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condition... | 8,606 | 40.985366 | 111 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/sdcnet/main.py | #!/usr/bin/env python
import argparse
import os
import numpy as np
import shutil
import torch
import torch.backends.cudnn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from tensorboardX import SummaryWriter
import cv2
from tqdm import tqdm
### masks warning : RuntimeError: Set changed size duri... | 26,977 | 40.062405 | 127 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/sdcnet/sdc_aug.py | import os
import sys
import argparse
import cv2
import numpy as np
from PIL import Image
import shutil
import torch
import torch.nn as nn
from torch.autograd import Variable
from models.sdc_net2d import *
parser = argparse.ArgumentParser()
parser.add_argument('--pretrained', default='', type=str, metavar='PATH', he... | 15,478 | 45.623494 | 131 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/sdcnet/utility/tools.py | import os
import subprocess
import time
from inspect import isclass
class TimerBlock:
def __init__(self, title):
print(("{}".format(title)))
def __enter__(self):
self.start = time.clock()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.end = time.clock... | 3,701 | 37.164948 | 155 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/sdcnet/models/model_utils.py | from __future__ import division
from __future__ import print_function
import torch.nn as nn
def conv2d(channels_in, channels_out, kernel_size=3, stride=1, bias = True):
return nn.Sequential(
nn.Conv2d(channels_in, channels_out, kernel_size=kernel_size, stride=stride, padding=(kernel_size-1)//2, bias=bias)... | 649 | 39.625 | 124 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/sdcnet/models/sdc_net2d.py | '''
Portions of this code are adapted from:
https://github.com/NVIDIA/flownet2-pytorch/blob/master/networks/FlowNetS.py
https://github.com/ClementPinard/FlowNetPytorch/blob/master/models/FlowNetS.py
'''
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
from torch.... | 9,288 | 40.842342 | 119 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/sdcnet/datasets/frame_loader.py | from __future__ import division
from __future__ import print_function
import os
import natsort
import numpy as np
import cv2
import torch
from torch.utils import data
from datasets.dataset_utils import StaticRandomCrop
class FrameLoader(data.Dataset):
def __init__(self, args, root, is_training = False, transfor... | 3,766 | 35.931373 | 107 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/sdcnet/datasets/dataset_utils.py | from __future__ import division
from __future__ import print_function
import torch
class StaticRandomCrop(object):
"""
Helper function for random spatial crop
"""
def __init__(self, size, image_shape):
h, w = image_shape
self.th, self.tw = size
self.h1 = torch.randint(0, h - se... | 519 | 27.888889 | 79 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/sdcnet/spatialdisplconv_package/test_spatialdisplconv.py | import torch
import time
from spatialdisplconv import SpatialDisplConv
assert torch.cuda.is_available()
cuda_device = torch.device("cuda") # device object representing GPU
n = 8
h = 224
w = 224
offset = 9 # 11
#input1 = N, 3, H + 11, W + 11
#input2 = N, 11, H, W
#input3 = N, 11, H, W
#input4 = N, 2, H, W
# Note t... | 1,305 | 23.185185 | 98 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/sdcnet/spatialdisplconv_package/spatialdisplconv.py | from torch.nn.modules.module import Module
from torch.autograd import Function, Variable
import spatialdisplconv_cuda
class SpatialDisplConvFunction(Function):
@staticmethod
def forward(ctx, input1, input2, input3, input4, kernel_size = 1):
assert input1.is_contiguous(), "spatialdisplconv forward - in... | 2,270 | 32.397059 | 95 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/sdcnet/spatialdisplconv_package/setup.py | #!/usr/bin/env python3
import os
import torch
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
cxx_args = ['-std=c++11']
nvcc_args = [
'-gencode', 'arch=compute_50,code=sm_50',
'-gencode', 'arch=compute_52,code=sm_52',
'-gencode', 'arch=compute_60,code=sm_6... | 791 | 25.4 | 67 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/transforms/joint_transforms.py | """
# Code borrowded from:
# https://github.com/zijundeng/pytorch-semantic-segmentation/blob/master/utils/joint_transforms.py
#
#
# MIT License
#
# Copyright (c) 2017 ZijunDeng
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "So... | 22,631 | 35.8 | 109 | py |
mtl-segmentation-mtl | mtl-segmentation-mtl/transforms/transforms.py | """
# Code borrowded from:
# https://github.com/zijundeng/pytorch-semantic-segmentation/blob/master/utils/transforms.py
#
#
# MIT License
#
# Copyright (c) 2017 ZijunDeng
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software... | 11,778 | 32.274011 | 94 | py |
DISM | DISM-main/keras_hypernetworks.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import numpy as np
import tensorflow as tf
import tf_common
def swish(x):
return (x*tf.keras.activations.sigmoid(x))
tf.keras.utils.get_custom_objects().update({'swish': swish})
def keras_hypernet_v1_dims(n_layers_hidden = 3,
n_nod... | 19,058 | 42.217687 | 99 | py |
DISM | DISM-main/tf_common.py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tensorflow as tf
#define swish activation function
def swish(x):
return (x*tf.keras.activations.sigmoid(x))
tf.keras.utils.get_custom_objects().update({'swish': swish})
def set_tensorflow_precision_policy(is_mixed_precision = False):
'''Set the precis... | 2,458 | 40.677966 | 97 | py |
DISM | DISM-main/dense_networks.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tensorflow as tf
def swish(x):
return (x*tf.keras.activations.sigmoid(x))
tf.keras.utils.get_custom_objects().update({'swish': swish})
class dense_base():
'''Base-level functionality for dense networks.
Attributes:
opt (dict) ... | 14,852 | 43.737952 | 133 | py |
DISM | DISM-main/nids_keras_networks.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tensorflow as tf
def swish(x):
return (x*tf.keras.activations.sigmoid(x))
tf.keras.utils.get_custom_objects().update({'swish': swish})
class keras_nids_v1(tf.keras.Model):
'''NIDS model. Subclasses tf.keras.Model. and takes arbitrary tf.keras.Mo... | 12,477 | 44.046931 | 99 | py |
SRDC-CVPR2020 | SRDC-CVPR2020-master/main.py | #####################################################################################
# #
# All the codes about the model constructing should be kept in the folder ./models/ #
# All the codes about the data process should be kept in the f... | 13,540 | 48.061594 | 274 | py |
SRDC-CVPR2020 | SRDC-CVPR2020-master/trainer.py | import time
import torch
import os
import math
import numpy as np
import torch.nn.functional as F
from torch.autograd import Variable
from utils.kernel_kmeans import KernelKMeans
import gc
import ipdb
def train(train_loader_source, train_loader_source_batch, train_loader_target, train_loader_target_batch, model, learn... | 31,720 | 46.415546 | 213 | py |
SRDC-CVPR2020 | SRDC-CVPR2020-master/models/resnet.py | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from collections import OrderedDict
import ipdb
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
... | 7,466 | 32.039823 | 107 | py |
SRDC-CVPR2020 | SRDC-CVPR2020-master/utils/consensus_loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class ConsensusLoss(nn.Module):
def __init__(self, nClass, div):
super(ConsensusLoss, self).__init__()
self.nClass = nClass
self.div = div
def forward(self, x, y):
if self.div == 'kl':
x = F... | 1,432 | 29.489362 | 99 | py |
SRDC-CVPR2020 | SRDC-CVPR2020-master/utils/folder.py | """
File modified from: https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py
"""
import torch.utils.data as data
from PIL import Image
import os
import os.path
import sys
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
... | 7,791 | 35.24186 | 113 | py |
SRDC-CVPR2020 | SRDC-CVPR2020-master/data/prepare_data.py | import os
import shutil
import torch
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn.functional as F
from utils.folder import ImageFolder
import numpy as np
import cv2
def generate_dataloader(args):
# Data loading code
traindir = os.path.join(args.data_path_s... | 6,856 | 45.331081 | 173 | py |
relative-uncertainty | relative-uncertainty-master/src/MixUp/save_logits.py | import os
import torch
import torch.utils.data
from tqdm import tqdm
from src.utils.datasets import get_dataset
from src.utils.models import get_model_essentials
CHECKPOINTS_DIR = os.environ.get("CHECKPOINTS_DIR", "checkpoints/")
CHECKPOINTS_DIR = os.path.join(CHECKPOINTS_DIR, "mixup/")
def main(model_name, seed):... | 2,402 | 34.865672 | 116 | py |
relative-uncertainty | relative-uncertainty-master/src/MixUp/train.py | import argparse
import csv
import os
import numpy as np
import torch
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torch.utils.data
from tqdm import tqdm
from src.utils.datasets import get_d... | 7,260 | 34.419512 | 112 | py |
relative-uncertainty | relative-uncertainty-master/src/RegMixup/save_logits.py | import os
import torch
import torch.utils.data
from tqdm import tqdm
from src.utils.datasets import get_dataset
from src.utils.models import get_model_essentials
CHECKPOINTS_DIR = os.environ.get("CHECKPOINTS_DIR", "checkpoints/")
CHECKPOINTS_DIR = os.path.join(CHECKPOINTS_DIR, "regmixup/")
def main(model_name, see... | 2,405 | 34.910448 | 116 | py |
relative-uncertainty | relative-uncertainty-master/src/RegMixup/train.py | import argparse
import csv
import os
import numpy as np
import torch
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torch.utils.data
from tqdm import tqdm
from src.utils.datasets import get_d... | 7,615 | 34.588785 | 115 | py |
relative-uncertainty | relative-uncertainty-master/src/LogitNorm/save_logits.py | import os
import torch
import torch.utils.data
from tqdm import tqdm
from src.utils.datasets import get_dataset
from src.utils.models import get_model_essentials
CHECKPOINTS_DIR = os.environ.get("CHECKPOINTS_DIR", "checkpoints/")
CHECKPOINTS_DIR = os.path.join(CHECKPOINTS_DIR, "lognorm/")
def main(model_name):
... | 2,251 | 33.646154 | 116 | py |
relative-uncertainty | relative-uncertainty-master/src/RelU/main.py | import os
import argparse
import itertools
import json
import random
import pandas as pd
import numpy as np
from torch.autograd import Variable
import torch
import torch.utils.data
from tqdm import tqdm
from src.RelU.methods import get_method
from src.utils.datasets import get_dataset
from src.utils.helpers import appe... | 8,222 | 34.752174 | 116 | py |
relative-uncertainty | relative-uncertainty-master/src/RelU/calibration.py | import argparse
import os
import random
import numpy as np
import torch
import torch.optim as optim
import torch.utils.data
from src.RelU.main import evaluate
from src.RelU.methods import doctor
from src.utils.helpers import append_results_to_file
CHECKPOINTS_DIR = os.environ.get("CHECKPOINTS_DIR", "checkpoints/")
C... | 9,645 | 32.034247 | 120 | py |
relative-uncertainty | relative-uncertainty-master/src/RelU/methods.py | from functools import partial
import torch
import torch.utils.data
from tqdm import tqdm
def g(logits, temperature=1.0):
return torch.sum(torch.softmax(logits / temperature, dim=1) ** 2, dim=1)
def doctor(logits: torch.Tensor, temperature: float = 1.0, **kwargs):
g_out = g(logits=logits, temperature=tempera... | 3,581 | 35.181818 | 116 | py |
relative-uncertainty | relative-uncertainty-master/src/utils/datasets.py | from typing import Any, Dict, Type
from torch.utils.data import Dataset
from torchvision.datasets import CIFAR10, CIFAR100, SVHN, ImageFolder, ImageNet
datasets_registry: Dict[str, Any] = {
"cifar10": CIFAR10,
"cifar100": CIFAR100,
"svhn": SVHN,
"imagenet": ImageNet,
}
def get_dataset(dataset_name: ... | 822 | 23.939394 | 79 | py |
relative-uncertainty | relative-uncertainty-master/src/utils/models/resnet.py | """ResNet in PyTorch.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
"""
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=... | 4,358 | 33.322835 | 102 | py |
relative-uncertainty | relative-uncertainty-master/src/utils/models/densenet.py | """DenseNet in PyTorch."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck(nn.Module):
def __init__(self, in_planes, growth_rate):
super(Bottleneck, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.conv1 = nn.Conv2d(in_planes, 4 * ... | 3,880 | 32.747826 | 98 | py |
relative-uncertainty | relative-uncertainty-master/src/utils/models/__init__.py | import logging
from typing import Any, Dict
from torchvision import transforms
from . import densenet, resnet, vgg
logger = logging.getLogger(__name__)
def _get_default_cifar10_transforms():
statistics = ((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
test_transforms = transforms.Compose(
[
... | 8,166 | 30.053232 | 79 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/tools/doctor_tools.py | import os
import time
import torch
import logging
import numpy as np
from torch.autograd import Variable
def g(logits: torch.Tensor, temperature: float = 1.0):
return torch.sum(torch.softmax(logits/temperature, dim=1) ** 2, dim=1)
def doctor(logits: torch.Tensor, temperature: float = 1.0):
return 1 - g(logi... | 5,602 | 41.44697 | 126 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/tools/data_tools.py | import yaml
import torch
import pickle
import logging
import torchvision
from torchvision import transforms
from torch.utils.data import Dataset
from tools.cifar_c_class import CORRUPTIONS, CIFAR10_C, CIFAR100_C
# define an abstract class to load datasets from torchvision
class TorchvisionDataset(Dataset):
def _... | 6,617 | 31.600985 | 90 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/tools/preprocess_cifar100.py | import os
import torch
import numpy as np
from tools import ml_tools
from tools.data_tools import get_data, get_CIFAR100_class_names
def get_id_classes_to_eliminate(names: list, dict_classes: dict) -> list:
""" Get id of classes to eliminate
Args:
names (list): list of class names to eliminate
... | 5,851 | 35.805031 | 114 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/tools/ml_tools.py | import os
import torch
import random
import numpy as np
from tqdm import tqdm
from torch import nn as nn
from tools.models.resnet import ResNet34
import torch.nn.functional as torch_func
from torchvision import models as models
from tools.models.densenet import DenseNet121Small
def get_accuracy(predictions, targets):... | 6,177 | 35.128655 | 181 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/tools/rename_weight_dict.py | import torch
from collections import OrderedDict
if __name__ == '__main__':
path_list = [
'resnet34_custom_mixup/cifar10/1/old_best.pth',
'resnet34_custom_mixup/cifar100/1/old_best.pth',
'resnet34_custom_regmixup/cifar10/1/old_best.pth',
'resnet34_custom_regmixup/cifar100/1/old_bes... | 1,719 | 39.952381 | 66 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/tools/d_matrix_tools.py | import torch
from tools import data_tools
from torch.autograd import Variable
from sklearn.metrics import roc_curve, auc
def eval(lbd, device, model_op, params, test_labels, test_data, logger):
# validate
with torch.no_grad():
scores = model_op(test_data.to(device), params).cpu().numpy()
fprs, tpr... | 4,306 | 36.452174 | 121 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/tools/cifar_c_class.py | import os
from typing import Callable, Optional
import numpy as np
import torch.utils.data.dataset as dataset
from PIL import Image
from torchvision.datasets.utils import check_integrity, download_and_extract_archive, verify_str_arg
CORRUPTIONS = [
"brightness",
"contrast",
"defocus_blur",
"elastic_tr... | 3,457 | 28.305085 | 113 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/tools/models/resnet.py | """ResNet in PyTorch.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
"""
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=... | 4,358 | 33.322835 | 102 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/tools/models/vgg.py | """VGG11/13/16/19 in Pytorch."""
import torch.nn as nn
cfg = {
"VGG11": [64, "M", 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"],
"VGG13": [64, 64, "M", 128, 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"],
"VGG16": [
64,
64,
"M",
128,
128,
"M"... | 1,828 | 19.550562 | 87 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/tools/models/densenet.py | """DenseNet in PyTorch."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck(nn.Module):
def __init__(self, in_planes, growth_rate):
super(Bottleneck, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.conv1 = nn.Conv2d(in_planes, 4 * ... | 3,880 | 32.747826 | 98 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/tools/models/__init__.py | import logging
from typing import Any, Dict
from torchvision import transforms
from . import densenet, resnet, vgg
logger = logging.getLogger(__name__)
def _get_default_cifar10_transforms():
statistics = ((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
test_transforms = transforms.Compose(
[
... | 6,987 | 30.336323 | 79 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/corruption_analysis/global_corruption_report_plots_cifar10_cifar10c.py | import os
import torch
import logging
import argparse
import numpy as np
import pandas as pn
from tqdm import tqdm
import plotly.express as px
from tools import data_tools
import plotly.graph_objects as go
from matplotlib import pyplot as plt
from plotly.subplots import make_subplots
import itertools
models = ["densen... | 22,054 | 46.430108 | 204 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/corruption_analysis/corruption_report_plots_cifar10_cifar10c.py | import os
import torch
import argparse
import logging
import pandas as pn
from tools import data_tools
import matplotlib.pyplot as plt
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--config_file_path", type=str, required=True)
args = parser.parse_args()
config = dat... | 16,309 | 49.339506 | 207 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/corruption_analysis/d_matrix/compute_eval_scores.py | import os
import torch
from tools.data_tools import *
from sklearn.metrics import roc_curve, auc
from tools.d_matrix_tools import D_scores_func
def compute_eval_scores(device,
logger,
magnitude,
magnitude_folder,
new_match... | 4,447 | 36.694915 | 88 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/corruption_analysis/d_matrix/compute_d_matrix.py | import os
import torch
import numpy as np
from tools import ml_tools
from tools.d_matrix_tools import matrix_D
def compute_d_matrix(seed,
dest_folder,
match_ts_labels,
match_ts_predictions,
match_ts_logits,
r,
... | 1,710 | 33.918367 | 110 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/corruption_analysis/d_matrix/d_matrix_train_script.py | # import sys
# sys.path.append("..")
# sys.path.append("../..")
import os
import torch
import argparse
import numpy as np
from tools import ml_tools
from tools import data_tools
from corruption_analysis.d_matrix import compute_d_matrix
from tools.d_matrix_tools import compute_perturbed_loaders
from corruption_analysis... | 11,203 | 49.017857 | 163 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/corruption_analysis/d_matrix/d_matrix_eval_script.py | # import sys
# sys.path.append("..")
# sys.path.append("../..")
import os
import torch
import argparse
import numpy as np
from tools import ml_tools
from tools import data_tools
from corruption_analysis.d_matrix import compute_d_matrix
from tools.d_matrix_tools import compute_perturbed_loaders
from corruption_analysis... | 11,460 | 49.488987 | 161 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/corruption_analysis/doctor/doctor_script_compute.py | import os
import torch
import argparse
import numpy as np
from tools import ml_tools
from tools import data_tools
from tools import doctor_tools
from corruption_analysis.doctor import eval_doctor_scores
from tools.doctor_tools import compute_doctor_scores_for_magnitude_and_temperature
if __name__ == "__main__":
#... | 8,909 | 44.692308 | 155 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/corruption_analysis/doctor/doctor_script_eval.py | import os
import torch
import argparse
from tools import ml_tools
from tools import data_tools
from tools import doctor_tools
from corruption_analysis.doctor import eval_doctor_scores
from tools.doctor_tools import compute_doctor_scores_for_magnitude_and_temperature
if __name__ == "__main__":
# get the config fil... | 8,357 | 42.53125 | 134 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/corruption_analysis/doctor/eval_doctor_scores.py | import io
import os
import torch
import numpy as np
from tools import data_tools, ml_tools
from sklearn.metrics import auc, roc_curve
from tools.data_tools import fpr_at_fixed_tpr
# data pos = 0 in-distr and/or correct
# data neg = 1 out-distr and/or incorrect
def eval_doctor_scores(magnitude,
... | 9,123 | 51.739884 | 162 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/mismatch_analysis/d_matrix/compute_eval_scores.py | import os
import torch
from tools.data_tools import *
from sklearn.metrics import roc_curve, auc
from tools.d_matrix_tools import D_scores_func
def compute_eval_scores(device,
logger,
magnitude,
magnitude_folder,
new_match... | 6,604 | 41.070064 | 93 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/mismatch_analysis/d_matrix/compute_d_matrix.py | import os
import torch
import numpy as np
from tools import ml_tools
from tools.d_matrix_tools import matrix_D
def compute_d_matrix(seed,
dest_folder,
match_ts_labels,
match_ts_predictions,
match_ts_logits,
use_mi... | 2,596 | 40.887097 | 153 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/mismatch_analysis/d_matrix/d_matrix_train_script.py | import os
import torch
import argparse
from tools import ml_tools
from tools import data_tools
from mismatch_analysis.d_matrix import compute_d_matrix
from mismatch_analysis.d_matrix import compute_eval_scores
from tools.d_matrix_tools import compute_perturbed_loaders
if __name__ == "__main__":
# get the config f... | 11,668 | 48.236287 | 145 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/mismatch_analysis/d_matrix/d_matrix_eval_script.py | import os
import torch
import argparse
import numpy as np
from tools import ml_tools
from tools import data_tools
from mismatch_analysis.d_matrix import compute_d_matrix
from mismatch_analysis.d_matrix import compute_eval_scores
from tools.d_matrix_tools import compute_perturbed_loaders
if __name__ == "__main__":
... | 11,718 | 48.033473 | 145 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/mismatch_analysis/doctor/doctor_script.py | import os
import torch
import argparse
from tools import ml_tools
from tools import data_tools
from tools import doctor_tools
from mismatch_analysis.doctor import eval_doctor_scores
from mismatch_analysis.doctor import compute_doctor_scores
if __name__ == "__main__":
# get the config file from the command line us... | 7,189 | 37.655914 | 145 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/mismatch_analysis/doctor/compute_doctor_scores.py | import os
import time
import torch
from tools import doctor_tools
from tools import data_tools, ml_tools
def compute_doctor_scores_for_magnitude_and_temperature(temperature,
magnitude,
logger,
... | 1,446 | 44.21875 | 77 | py |
relative-uncertainty | relative-uncertainty-master/mismatch_and_corruption/mismatch_analysis/doctor/eval_doctor_scores.py | import os
import torch
from tools import data_tools, ml_tools
from sklearn.metrics import auc, roc_curve
from tools.data_tools import fpr_at_fixed_tpr
# data pos = 0 in-distr and/or correct
# data neg = 1 out-distr and/or incorrect
def eval_doctor_scores(magnitude,
temperature,
... | 6,800 | 43.743421 | 134 | py |
three_player_for_emnlp | three_player_for_emnlp-master/models/rnn_model.py |
# coding: utf-8
# In[ ]:
import torch
import torch.nn as nn
from torchvision.models.resnet import BasicBlock
import math
from torch.autograd import Variable
# In[ ]:
class CnnModel(nn.Module):
def __init__(self, args):
"""
args.hidden_dim -- dimension of filters
args.embedding... | 3,935 | 34.142857 | 109 | py |
three_player_for_emnlp | three_player_for_emnlp-master/models/generator.py |
# coding: utf-8
# In[ ]:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from models.rnn_model import CnnModel, RnnModel
# In[ ]:
def _get_entropy(p):
"""
Compute entropy of the input prob vector p
Inputs:
p -- torch variable, a list of ... | 8,621 | 32.548638 | 123 | py |
three_player_for_emnlp | three_player_for_emnlp-master/models/base_classification_models.py |
# coding: utf-8
# In[ ]:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import copy
# from models.models import CnnModel, RnnModel
# from basic_nlp_models import BasicNLPModel
# from models.encoder import Encoder, ClassificationEncoder
from... | 17,229 | 39.257009 | 115 | py |
three_player_for_emnlp | three_player_for_emnlp-master/three_player_games/util_functions.py |
# coding: utf-8
# In[ ]:
import torch
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import copy, random, sys, os
import tqdm
# In[ ]:
def _get_sparsity(z, mask):
mask_z = z * mask
seq_lengths = torch.sum(mask, dim=1)
... | 43,335 | 46.002169 | 275 | py |
three_player_for_emnlp | three_player_for_emnlp-master/three_player_games/rationale_3players_sentence_classification_models.py |
# coding: utf-8
# In[ ]:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import copy
# from models.models import CnnModel, RnnModel
# from basic_nlp_models import BasicNLPModel
# from models.encoder import Encoder, ClassificationEncoder
from... | 26,703 | 39.707317 | 169 | py |
three_player_for_emnlp | three_player_for_emnlp-master/three_player_games/rationale_3players_text_matching_models.py |
# coding: utf-8
# In[ ]:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import copy
# from models.models import CnnModel, RnnModel
# from basic_nlp_models import BasicNLPModel
# from models.encoder import Encoder, ClassificationEncoder
from... | 38,715 | 43.045506 | 173 | py |
three_player_for_emnlp | three_player_for_emnlp-master/three_player_games/rationale_3players_for_emnlp.py |
# coding: utf-8
# In[ ]:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import copy
# from models.models import CnnModel, RnnModel
# from basic_nlp_models import BasicNLPModel
# from models.encoder import Encoder, ClassificationEncoder
from... | 9,972 | 36.492481 | 169 | py |
three_player_for_emnlp | three_player_for_emnlp-master/three_player_games/run_beer_single_aspect_rationale_3players.py |
# coding: utf-8
# In[ ]:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import copy, random, sys, os
from collections import deque
# from models.models import CnnModel, RnnModel
# from basic_nlp_models import BasicNLPModel
# from models.enc... | 19,203 | 36.145068 | 209 | py |
three_player_for_emnlp | three_player_for_emnlp-master/three_player_games/run_beer_single_aspect_introspection_3players.py |
# coding: utf-8
# In[ ]:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import copy, random, sys, os
from collections import deque
# from models.models import CnnModel, RnnModel
# from basic_nlp_models import BasicNLPModel
# from models.enc... | 16,225 | 35.793651 | 209 | py |
three_player_for_emnlp | three_player_for_emnlp-master/three_player_games/rationale_3players_relation_classification_models.py |
# coding: utf-8
# In[ ]:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import copy
# from models.models import CnnModel, RnnModel
# from basic_nlp_models import BasicNLPModel
# from models.encoder import Encoder, ClassificationEncoder
from... | 16,317 | 42.398936 | 169 | py |
three_player_for_emnlp | three_player_for_emnlp-master/utils/utils.py |
# coding: utf-8
# In[ ]:
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
# In[ ]:
class Transpose(nn.Module):
def __init__(self, dim1, dim2):
... | 7,452 | 27.231061 | 151 | py |
Global-Flow-Transport | Global-Flow-Transport-main/reconstruct_sequence.py | import os, sys, shutil, socket, faulthandler, signal, math, copy, random
import datetime, time
import logging, argparse
import json
import munch
import imageio
parser = argparse.ArgumentParser(description='Reconstruct volumetric smoke densities from 2D views.')
parser.add_argument('-s', '--setup', dest='setup_file', ... | 185,003 | 56.831822 | 434 | py |
Global-Flow-Transport | Global-Flow-Transport-main/lib/tf_ops.py | import os
import tensorflow as tf
import numpy as np
#import numbers
import logging
log = logging.getLogger('TFops')
log.setLevel(logging.DEBUG)
from tensorflow.python.keras.utils import conv_utils
from tensorflow.python.framework import tensor_shape
import scipy.signal
#https://stackoverflow.com/questions/14267555/... | 22,797 | 34.677621 | 204 | py |
nninfo | nninfo-main/nninfo/tester.py | import torch
from torch.utils.data import DataLoader
from nninfo.exp_comp import ExperimentComponent
from nninfo.model.quantization import quantizer_list_factory
class Tester(ExperimentComponent):
"""
Is called after each training chapter to perform predefined tests and save their results.
Args:
... | 2,610 | 31.234568 | 98 | py |
nninfo | nninfo-main/nninfo/experiment.py | import os
import re
from pathlib import Path
import numpy as np
import torch
import torch.utils.data
import nninfo
from nninfo.data_set import DataSet
from nninfo.trainer import Trainer
from nninfo.schedule import Schedule
from nninfo.model.neural_network import NeuralNetwork, NeuronID, NoisyNeuralNetwork
from nninfo... | 16,997 | 34.119835 | 151 | py |
nninfo | nninfo-main/nninfo/data_set.py | import torch
import numpy as np
from numpy.random import Philox, Generator
SUBSET_SYMBOL = "/" # <dataset>/<subset>/<subsubset> etc.
class DataSet(torch.utils.data.Dataset):
def __init__(self, task, name):
self._task = task
self._name = name
self._subsets = []
@staticmethod
def f... | 10,492 | 31.893417 | 127 | py |
nninfo | nninfo-main/nninfo/file_io.py | # you may not need all of these, if you know your data file types
# and the way FileManager handles them.
import os, re, glob
from pathlib import Path
import shutil
import pickle
import json
import ast
import copy
import numpy as np
import scipy.io as io
import torch
import yaml
import pandas as pd
from filelock impor... | 22,131 | 34.986992 | 120 | py |
nninfo | nninfo-main/nninfo/trainer.py | from typing import Optional
import numpy as np
from torch.utils.data import DataLoader
import torch.optim as optim
import torch.nn as nn
import nninfo
from nninfo.config import CLUSTER_MODE
from nninfo.exp_comp import ExperimentComponent
from nninfo.model.quantization import quantizer_list_factory
log = nninfo.logger... | 8,704 | 34.530612 | 135 | py |
nninfo | nninfo-main/nninfo/model/quantization.py | from abc import abstractmethod, ABC
from dataclasses import dataclass
from typing import Union, Tuple, List
import numpy as np
import torch
Limits = Union[Tuple[float, float], str]
@dataclass
class Quantizer(ABC):
"""
n_levels: Number of equidistant quantization levels
"""
n_levels: int
limi... | 3,670 | 29.591667 | 154 | py |
nninfo | nninfo-main/nninfo/model/neural_network.py | import copy
from dataclasses import dataclass, field
from functools import cache
from typing import Optional, Union, Tuple, List
from ast import literal_eval
import torch.nn as nn
import torch
import numpy as np
import scipy as scp
import yaml
import nninfo
from ..file_io import NoAliasDumper
from .quantization impor... | 18,419 | 33.820416 | 122 | py |
nninfo | nninfo-main/nninfo/tasks/combined_mnist_binary_task.py | import torch
import torchvision.datasets
from .task import Task, binary_encode_label
class CombinedMnistBinaryTask(Task):
task_id = "combined_mnist_binary_dat"
@property
def finite(self):
return True
@property
def x_limits(self):
return (0, 1)
@property
def y_limits(self... | 1,267 | 25.978723 | 78 | py |
nninfo | nninfo-main/nninfo/tasks/cifar10_task.py | import torch
import torchvision.datasets
from .task import Task
class CIFAR10Task(Task):
task_id = "cifar10_1d_dat"
@property
def finite(self):
return True
@property
def x_limits(self):
return (0, 1)
@property
def y_limits(self):
return "binary"
@property
... | 1,137 | 23.73913 | 59 | py |
nninfo | nninfo-main/nninfo/tasks/combined_mnist_quaternary_task.py | import torch
import torchvision.datasets
from .task import Task, quaternary_encode_label
class CombinedMnistQuaternaryTask(Task):
task_id = "combined_mnist_quaternary_dat"
@property
def finite(self):
return True
@property
def x_limits(self):
return (0, 1)
@property
def ... | 1,284 | 25.770833 | 78 | py |
nninfo | nninfo-main/nninfo/tasks/fake_task.py | import torch
import numpy as np
from .task import Task
class FakeTask(Task):
task_id = "fake_dat"
@property
def finite(self):
return True
@property
def x_limits(self):
return "binary"
@property
def y_limits(self):
return "binary"
@property
def x_dim(self... | 1,320 | 24.403846 | 85 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.