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 |
|---|---|---|---|---|---|---|
cotta | cotta-main/cifar/cifar10c_gradual.py | import logging
import torch
import torch.optim as optim
from robustbench.data import load_cifar10c
from robustbench.model_zoo.enums import ThreatModel
from robustbench.utils import load_model
from robustbench.utils import clean_accuracy as accuracy
import tent
import norm
import cotta
from conf import cfg, load_cfg... | 5,646 | 35.668831 | 108 | py |
cotta | cotta-main/cifar/tent.py | from copy import deepcopy
import torch
import torch.nn as nn
import torch.jit
class Tent(nn.Module):
"""Tent adapts a model by entropy minimization during testing.
Once tented, a model adapts itself by updating on every forward.
"""
def __init__(self, model, optimizer, steps=1, episodic=False):
... | 4,403 | 33.952381 | 79 | py |
cotta | cotta-main/cifar/cifar10c.py | import logging
import torch
import torch.optim as optim
from robustbench.data import load_cifar10c
from robustbench.model_zoo.enums import ThreatModel
from robustbench.utils import load_model
from robustbench.utils import clean_accuracy as accuracy
import tent
import norm
import cotta
from conf import cfg, load_cfg... | 5,501 | 35.437086 | 78 | py |
cotta | cotta-main/cifar/norm.py | from copy import deepcopy
import torch
import torch.nn as nn
class Norm(nn.Module):
"""Norm adapts a model by estimating feature statistics during testing.
Once equipped with Norm, the model normalizes its features during testing
with batch-wise statistics, just like batch norm does during training.
... | 2,159 | 31.727273 | 77 | py |
cotta | cotta-main/cifar/my_transforms.py | # KATANA: Simple Post-Training Robustness Using Test Time Augmentations
# https://arxiv.org/pdf/2109.08191v1.pdf
import torch
import torchvision.transforms.functional as F
from torchvision.transforms import ColorJitter, Compose, Lambda
from numpy import random
class GaussianNoise(torch.nn.Module):
def __init__(sel... | 4,960 | 38.373016 | 111 | py |
cotta | cotta-main/cifar/utils.py | import os
import sys
import torch
import numpy as np
from typing import Dict, List, Tuple
import torch.nn as nn
import torch.utils.data as data
import logging
from tqdm import tqdm
def pytorch_evaluate(net: nn.Module, data_loader: data.DataLoader, fetch_keys: List,
x_shape: Tuple = None, output_sh... | 5,803 | 31.606742 | 125 | py |
cotta | cotta-main/cifar/conf.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Configuration file (powered by YACS)."""
import argparse
import os
import sys
import logging
import random
import torch
import numpy as np... | 6,075 | 27.12963 | 79 | py |
cotta | cotta-main/cifar/robustbench/loaders.py | """
This file is based on the code from https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py.
"""
from torchvision.datasets.vision import VisionDataset
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image
import os
import os.path
impor... | 7,147 | 37.021277 | 113 | py |
cotta | cotta-main/cifar/robustbench/utils.py | import argparse
import dataclasses
import json
import math
import os
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Dict, Optional, Union
import requests
import torch
from torch import nn
from robustbench.model_zoo import model_dicts as all_models
from robustbench.mode... | 18,143 | 38.103448 | 172 | py |
cotta | cotta-main/cifar/robustbench/data.py | import os
from pathlib import Path
from typing import Callable, Dict, Optional, Sequence, Set, Tuple
import numpy as np
import torch
import torch.utils.data as data
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import Dataset
from robustbench.model_zoo.enums... | 8,743 | 36.050847 | 122 | py |
cotta | cotta-main/cifar/robustbench/eval.py | import warnings
from argparse import Namespace
from pathlib import Path
from typing import Dict, Optional, Sequence, Tuple, Union
import numpy as np
import pandas as pd
import torch
import random
from autoattack import AutoAttack
from torch import nn
from tqdm import tqdm
from robustbench.data import CORRUPTIONS, loa... | 8,723 | 38.475113 | 107 | py |
cotta | cotta-main/cifar/robustbench/model_zoo/cifar100.py | from collections import OrderedDict
import torch
from robustbench.model_zoo.architectures.dm_wide_resnet import CIFAR100_MEAN, CIFAR100_STD, \
DMWideResNet, Swish, DMPreActResNet
from robustbench.model_zoo.architectures.resnet import PreActBlock, PreActResNet
from robustbench.model_zoo.architectures.resnext impor... | 9,269 | 35.210938 | 134 | py |
cotta | cotta-main/cifar/robustbench/model_zoo/cifar10.py | from collections import OrderedDict
import torch
import torch.nn.functional as F
from torch import nn
from robustbench.model_zoo.architectures.dm_wide_resnet import CIFAR10_MEAN, CIFAR10_STD, \
DMWideResNet, Swish, DMPreActResNet
from robustbench.model_zoo.architectures.resnet import Bottleneck, BottleneckChen202... | 28,007 | 36.645161 | 102 | py |
cotta | cotta-main/cifar/robustbench/model_zoo/imagenet.py | from collections import OrderedDict
from torchvision import models as pt_models
from robustbench.model_zoo.enums import ThreatModel
from robustbench.model_zoo.architectures.utils_architectures import normalize_model
mu = (0.485, 0.456, 0.406)
sigma = (0.229, 0.224, 0.225)
linf = OrderedDict(
[
('Wong2... | 3,493 | 37.822222 | 93 | py |
cotta | cotta-main/cifar/robustbench/model_zoo/architectures/resnet.py | import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 ... | 9,823 | 36.639847 | 104 | py |
cotta | cotta-main/cifar/robustbench/model_zoo/architectures/dm_wide_resnet.py | # Copyright 2020 Deepmind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | 10,748 | 35.561224 | 101 | py |
cotta | cotta-main/cifar/robustbench/model_zoo/architectures/resnext.py | """ResNeXt implementation (https://arxiv.org/abs/1611.05431).
MIT License
Copyright (c) 2017 Xuanyi Dong
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 restriction, including without li... | 5,799 | 32.918129 | 113 | py |
cotta | cotta-main/cifar/robustbench/model_zoo/architectures/wide_resnet.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, dropRate=0.0):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.relu1 = nn.ReLU(inplace=True)
se... | 4,070 | 41.40625 | 116 | py |
cotta | cotta-main/cifar/robustbench/model_zoo/architectures/utils_architectures.py | import torch
import torch.nn as nn
from collections import OrderedDict
from typing import Tuple
from torch import Tensor
class ImageNormalizer(nn.Module):
def __init__(self, mean: Tuple[float, float, float],
std: Tuple[float, float, float]) -> None:
super(ImageNormalizer, self).__init__()
... | 829 | 28.642857 | 76 | py |
COVID19-L3-Net | COVID19-L3-Net-master/test.py | from haven import haven_chk as hc
from haven import haven_results as hr
from haven import haven_utils as hu
import torch
import torchvision
import tqdm
import pandas as pd
import pprint
import itertools
import os
import pylab as plt
import exp_configs
import time
import numpy as np
from src import models
from src impo... | 5,614 | 32.422619 | 89 | py |
COVID19-L3-Net | COVID19-L3-Net-master/trainval.py | from haven import haven_chk as hc
from haven import haven_results as hr
from haven import haven_utils as hu
import torch
import torchvision
import tqdm
import pandas as pd
import pprint
import itertools
import os
import pylab as plt
import exp_configs
import time
import numpy as np
from src import models
from src impo... | 6,283 | 33.338798 | 99 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/utils.py | import torch
def collate_fn(batch):
batch_dict = {}
for k in batch[0]:
batch_dict[k] = []
for i in range(len(batch)):
batch_dict[k] += [batch[i][k]]
# tuple(zip(*batch))
batch_dict['images'] = torch.stack(batch_dict['images'])
batch_dict['masks'] = torch.sta... | 372 | 23.866667 | 60 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/semseg.py | import torch
import torch.nn.functional as F
import torchvision
from torchvision import transforms
import os
import tqdm
import pylab as plt
import numpy as np
import scipy.sparse as sps
from collections.abc import Sequence
import time
from src import utils as ut
from sklearn.metrics import confusion_matrix
import skim... | 8,795 | 33.494118 | 101 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/metrics.py | from collections import defaultdict
from scipy import spatial
import numpy as np
import torch
class SegMonitor:
def __init__(self):
self.cf = None
self.n_samples = 0
def val_on_batch(self, model, batch):
masks = batch["masks"]
self.n_samples += masks.shape[0]
pred_mas... | 3,232 | 26.398305 | 75 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/__init__.py | # from . import semseg_cost
import torch
import os
import tqdm
from . import semseg
import torch
def get_model(model_dict, exp_dict=None, train_set=None):
if model_dict['name'] in ["semseg"]:
model = semseg.SemSeg(exp_dict, train_set)
# load pretrained
if 'pretrained' in model_dict:
... | 413 | 17 | 71 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/unet2d.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
class DoubleConv(nn.Module):
"""(convolution => [BN] => ReLU) * 2"""
def __init__(self, in_channels, out_channels):
super().__init__()
self.double_conv = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_... | 3,432 | 31.084112 | 122 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/__init__.py | from . import unet2d
from . import segmentation_models_pytorch as smp
def get_base(base_name, exp_dict, n_classes):
if base_name == "fcn8_vgg16":
base = fcn8_vgg16.FCN8VGG16(n_classes=n_classes)
if base_name == "unet2d":
base = unet2d.UNet(n_channels=1, n_classes=n_classes)
if base_name ... | 966 | 33.535714 | 80 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/pspnet/model.py | from typing import Optional, Union
from .decoder import PSPDecoder
from ..encoders import get_encoder
from ..base import SegmentationModel
from ..base import SegmentationHead, ClassificationHead
class PSPNet(SegmentationModel):
"""PSPNet_ is a fully convolution neural network for image semantic segmentation
... | 3,796 | 39.827957 | 117 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/pspnet/decoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..base import modules
class PSPBlock(nn.Module):
def __init__(self, in_channels, out_channels, pool_size, use_bathcnorm=True):
super().__init__()
if pool_size == 1:
use_bathcnorm = False # PyTorch does not suppo... | 1,961 | 25.876712 | 113 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/inceptionv4.py | """ Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
... | 3,451 | 35.723404 | 107 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/inceptionresnetv2.py | """ Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
... | 3,461 | 37.043956 | 107 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/efficientnet.py | """ Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
... | 6,292 | 34.156425 | 107 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/_utils.py | import torch
import torch.nn as nn
def patch_first_conv(model, in_channels):
"""Change first convolution layer input channels.
In case:
in_channels == 1 or in_channels == 2 -> reuse original weights
in_channels > 3 -> make random kaiming normal initialization
"""
# get first conv
... | 1,515 | 28.72549 | 80 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/resnet.py | """ Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
... | 7,936 | 33.064378 | 107 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/vgg.py | """ Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
... | 5,480 | 33.689873 | 113 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/densenet.py | """ Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
... | 5,171 | 34.183673 | 108 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/senet.py | """ Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
... | 5,675 | 31.434286 | 107 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/_base.py | import torch
import torch.nn as nn
from typing import List
from collections import OrderedDict
from . import _utils as utils
class EncoderMixin:
"""Add encoder functionality such as:
- output channels specification of feature tensors (produced by encoder)
- patching first convolution for arbitrar... | 1,331 | 30.714286 | 85 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/timm_efficientnet.py | import torch
import torch.nn as nn
# from timm.models.efficientnet import EfficientNet, Swish
from timm.models.efficientnet import decode_arch_def, round_channels, default_cfgs
from ._base import EncoderMixin
def get_efficientnet_kwargs(channel_multiplier=1.0, depth_multiplier=1.0):
"""Creates an EfficientNet m... | 8,763 | 34.056 | 110 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/__init__.py | import functools
import torch.utils.model_zoo as model_zoo
from .resnet import resnet_encoders
from .dpn import dpn_encoders
from .vgg import vgg_encoders
from .senet import senet_encoders
from .densenet import densenet_encoders
from .inceptionresnetv2 import inceptionresnetv2_encoders
from .inceptionv4 import incepti... | 2,282 | 32.573529 | 83 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/xception.py | import re
import torch.nn as nn
from pretrainedmodels.models.xception import pretrained_settings
from pretrainedmodels.models.xception import Xception
from ._base import EncoderMixin
class XceptionEncoder(Xception, EncoderMixin):
def __init__(self, out_channels, *args, depth=5, **kwargs):
super().__ini... | 1,913 | 27.567164 | 95 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/mobilenet.py | """ Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
... | 2,850 | 32.940476 | 107 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/encoders/dpn.py | """ Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
... | 5,839 | 33.152047 | 107 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/base/modules.py | import torch
import torch.nn as nn
try:
from inplace_abn import InPlaceABN
except ImportError:
InPlaceABN = None
class Conv2dReLU(nn.Sequential):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
padding=0,
stride=1,
... | 3,433 | 26.693548 | 114 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/base/model.py | import torch
from . import initialization as init
class SegmentationModel(torch.nn.Module):
def initialize(self):
init.initialize_decoder(self.decoder)
init.initialize_head(self.segmentation_head)
if self.classification_head is not None:
init.initialize_head(self.classificatio... | 1,209 | 27.139535 | 99 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/base/heads.py | import torch.nn as nn
from .modules import Flatten, Activation
class SegmentationHead(nn.Sequential):
def __init__(self, in_channels, out_channels, kernel_size=3, activation=None, upsampling=1):
conv2d = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=kernel_size // 2)
upsam... | 1,162 | 45.52 | 106 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/base_networks/segmentation_models_pytorch/base/initialization.py | import torch.nn as nn
def initialize_decoder(module):
for m in module.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_uniform_(m.weight, mode="fan_in", nonlinearity="relu")
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.B... | 821 | 28.357143 | 82 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/losses/dice_loss.py |
import torch
from torch.nn import Module
def dice_loss(probs, target):
"""Dice loss.
:param input: The input (predicted)
:param target: The target (ground truth)
:returns: the Dice score between 0 and 1.
"""
eps = 0.0001
iflat = probs.view(-1)
tflat = target.view(-1)
intersectio... | 458 | 19.863636 | 53 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/models/losses/__init__.py | import torch
import torch.nn.functional as F
from . import dice_loss
def compute_loss(loss_name, logits, labels):
if loss_name == 'cross_entropy':
probs = F.log_softmax(logits, dim=1)
loss = F.nll_loss(
probs, labels, reduction='mean', ignore_index=255)
if loss_name ==... | 649 | 29.952381 | 67 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/datasets/open_source.py | import torch
import os
import h5py
import numpy as np
from haven import haven_utils as hu
from torchvision import transforms
import pydicom, tqdm
from . import transformers
from PIL import Image
class OpenSource(torch.utils.data.Dataset):
def __init__(
self,
split,
datadir,
exp_dic... | 3,891 | 37.534653 | 122 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/datasets/__init__.py | import torchvision
import torch
import numpy as np
from torchvision.transforms import transforms
from sklearn.utils import shuffle
from PIL import Image
from . import open_source
from src import utils as ut
import os
import os
import numpy as np
import random
import torch
from torch.utils.data import Dataset
from torc... | 1,271 | 27.909091 | 89 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/datasets/transformers/trans_utils.py | import torch
import numpy as np
import random
from scipy.ndimage import zoom
from torchvision import transforms
def get_class_map(n_classes):
if n_classes==5:
class_map = {
-1:-1,
0:0,
1:1,
2:1,
3:-1,
4:-1,
... | 10,957 | 25.6618 | 116 | py |
COVID19-L3-Net | COVID19-L3-Net-master/src/datasets/transformers/__init__.py | import torch
import numpy as np
import random
from scipy.ndimage import zoom
from torchvision import transforms
from . import trans_utils as tu
from haven import haven_utils as hu
# from batchgenerators.augmentations import crop_and_pad_augmentations
from . import micnn_augmentor
def apply_transform(split, image, la... | 5,034 | 34.457746 | 110 | py |
lerm | lerm-main/src/optim/objective.py | import torch
import torch.nn.functional as F
import math
def squared_error_loss(w, X, y):
return 0.5 * (y - torch.matmul(X, w)) ** 2
def binary_cross_entropy_loss(w, X, y):
logits = torch.matmul(X, w)
return torch.nn.functional.binary_cross_entropy_with_logits(
logits, y.double(), reduction="non... | 3,412 | 29.747748 | 122 | py |
lerm | lerm-main/src/optim/algorithms.py | import torch
import numpy as np
from src.utils.smoothing import get_smooth_weights
class Optimizer:
def __init__(self):
pass
def start_epoch(self):
raise NotImplementedError
def step(self):
raise NotImplementedError
def end_epoch(self):
raise NotImplementedError
... | 10,559 | 30.903323 | 88 | py |
lerm | lerm-main/src/utils/plotting.py | import os
import pickle
import torch
import numpy as np
from src.utils.training import compute_average_train_loss
from src.utils.io import var_to_str, get_path, load_results
from src.utils.config import N_EPOCHS
def get_suboptimality(dataset, model_cfg, train_loss, eps=1e-9, out_path="../results/"):
init_loss = ... | 4,704 | 39.560345 | 88 | py |
lerm | lerm-main/src/utils/training.py | import torch
import pandas as pd
import datetime
import pickle
import os
import time
from src.optim.algorithms import (
StochasticSubgradientMethod,
StochasticRegularizedDualAveraging,
LSVRG,
SLSVRG,
)
from src.utils.data import load_dataset
from src.utils.io import save_results, load_results, var_to_s... | 9,211 | 31.666667 | 88 | py |
lerm | lerm-main/src/utils/data.py | import os
from os import path
import pandas as pd
import zipfile
import urllib.request
import numpy as np
import torch
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def load_dataset(dataset="yacht", test_size=0.2, data_path="data/"):
if not os.path.exists(d... | 6,892 | 37.943503 | 123 | py |
lerm | lerm-main/src/utils/smoothing.py | import torch
def get_smooth_weights(losses, spectrum, smooth_coef, smoothing='l2'):
"""
Losses are the values of the losses at the current iterate, spectrum are the weights of the spectral measure
considered given in non-decreasing order
:param losses: (torch.Tensor of shape (n,) values of the losses ... | 5,720 | 42.340909 | 119 | py |
lerm | lerm-main/scripts/lbfgs.py | """
Run L-BFGS optimizer to get optimal value of spectral risk for a given dataset and regularizer.
Used to compute suboptimality of the optimizers assessed.
"""
import os
import sys
import numpy as np
import torch
from scipy.optimize import minimize
import pickle
import argparse
sys.path.append(".")
from src.utils.c... | 2,690 | 23.463636 | 95 | py |
lerm | lerm-main/scripts/debug.py | import torch
import sys
sys.path.append(".")
from src.utils.data import load_dataset
from src.utils.training import get_optimizer, get_objective
from src.utils.config import LRS
X_train, y_train, X_test, y_test = load_dataset("iwildcam")
objective = "erm"
l2_reg = 1.0
loss = "multinomial_cross_entropy"
model_cfg = ... | 1,682 | 24.892308 | 93 | py |
cntk-hotel-pictures-classificator | cntk-hotel-pictures-classificator-master/Detection/utils/unit_tests.py | # Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
import os, sys
abs_path = os.path.dirname(os.path.abspath(__file__))
sys.path.appen... | 8,680 | 43.290816 | 140 | py |
cntk-hotel-pictures-classificator | cntk-hotel-pictures-classificator-master/Detection/utils/caffe_layers/proposal_layer.py | # --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
#import caffe
import numpy as np
import yaml
from utils... | 6,953 | 37 | 80 | py |
cntk-hotel-pictures-classificator | cntk-hotel-pictures-classificator-master/Detection/utils/caffe_layers/proposal_target_layer.py | # --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
#import caffe
import yaml
import numpy as np
import num... | 8,184 | 37.608491 | 106 | py |
cntk-hotel-pictures-classificator | cntk-hotel-pictures-classificator-master/Detection/utils/caffe_layers/anchor_target_layer.py | # --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
import os
#import caffe
import yaml
import numpy as np
... | 11,877 | 39.401361 | 95 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/utils.py | import readline
import rlcompleter
readline.parse_and_bind("tab: complete")
import code
import pdb
import time
import argparse
import os
import imageio
import torch
import torch.multiprocessing as mp
# debugging tools
def interact(local=None):
"""interactive console with autocomplete function. Useful for debuggin... | 5,402 | 26.015 | 108 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/option.py | """optionional argument parsing"""
# pylint: disable=C0103, C0301
import argparse
import datetime
import os
import re
import shutil
import time
import torch
import torch.distributed as dist
import torch.backends.cudnn as cudnn
from utils import interact
from utils import str2bool, int2str
import template
# Training... | 13,298 | 47.36 | 173 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/launch.py | """ distributed launcher adopted from torch.distributed.launch
usage example: https://github.com/facebookresearch/maskrcnn-benchmark
This enables using multiprocessing for each spawned process (as they are treated as main processes)
"""
import sys
import subprocess
from argparse import ArgumentParser, REMAINDER... | 1,894 | 32.839286 | 103 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/train.py | import os
from tqdm import tqdm
import torch
import data.common
from utils import interact, MultiSaver
import torch.cuda.amp as amp
class Trainer():
def __init__(self, args, model, criterion, optimizer, loaders):
print('===> Initializing trainer')
self.args = args
self.mode = 'train' # ... | 7,051 | 30.20354 | 125 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/optim/__init__.py | import torch
import torch.optim as optim
import torch.optim.lr_scheduler as lrs
import os
from collections import Counter
from model import Model
from utils import interact, Map
class Optimizer(object):
def __init__(self, args, model):
self.args = args
self.save_dir = os.path.join(self.args.save... | 7,483 | 35.154589 | 128 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/optim/warm_multi_step_lr.py | import math
from bisect import bisect_right
from torch.optim.lr_scheduler import _LRScheduler
# MultiStep learning rate scheduler with warm restart
class WarmMultiStepLR(_LRScheduler):
def __init__(self, optimizer, milestones, gamma=0.1, last_epoch=-1, scale=1):
if not list(milestones) == sorted(milestones... | 1,135 | 33.424242 | 86 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/loss/adversarial.py | import torch
import torch.nn as nn
from utils import interact
import torch.cuda.amp as amp
class Adversarial(nn.modules.loss._Loss):
# pure loss function without saving & loading option
# but trains deiscriminator
def __init__(self, args, model, optimizer):
super(Adversarial, self).__init__()
... | 1,662 | 30.980769 | 96 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/loss/__init__.py | import os
from importlib import import_module
import torch
from torch import nn
import torch.distributed as dist
import matplotlib.pyplot as plt
plt.switch_backend('agg') # https://github.com/matplotlib/matplotlib/issues/3466
from .metric import PSNR, SSIM
from utils import interact
class Loss(torch.nn.modules.los... | 14,823 | 30.87957 | 118 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/loss/metric.py | # from skimage.metrics import peak_signal_noise_ratio, structural_similarity
import torch
from torch import nn
def _expand(img):
if img.ndim < 4:
img = img.expand([1] * (4-img.ndim) + list(img.shape))
return img
class PSNR(nn.Module):
def __init__(self):
super(PSNR, self).__init__()
... | 3,411 | 29.19469 | 120 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/data/sampler.py | import math
import torch
from torch.utils.data import Sampler
import torch.distributed as dist
class DistributedEvalSampler(Sampler):
r"""
DistributedEvalSampler is different from DistributedSampler.
It does NOT add extra samples to make it evenly divisible.
DistributedEvalSampler should NOT be used f... | 4,817 | 40.534483 | 105 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/data/dataset.py | import os
import random
import imageio
import numpy as np
import torch.utils.data as data
from data import common
from utils import interact
class Dataset(data.Dataset):
"""Basic dataloader class
"""
def __init__(self, args, mode='train'):
super(Dataset, self).__init__()
self.args = args
... | 4,816 | 30.077419 | 135 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/data/common.py | import random
import numpy as np
from skimage.color import rgb2hsv, hsv2rgb
from skimage.transform import pyramid_gaussian
import torch
def _apply(func, x):
if isinstance(x, (list, tuple)):
return [_apply(func, x_i) for x_i in x]
elif isinstance(x, dict):
y = {}
for key, value in x.it... | 4,605 | 27.085366 | 94 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/data/__init__.py | """Generic dataset loader"""
from importlib import import_module
from torch.utils.data import DataLoader
from torch.utils.data import SequentialSampler, RandomSampler
from torch.utils.data.distributed import DistributedSampler
from .sampler import DistributedEvalSampler
class Data():
def __init__(self, args):
... | 2,958 | 35.9875 | 137 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/model/structure.py | import torch.nn as nn
from .common import ResBlock, default_conv
def encoder(in_channels, n_feats):
"""RGB / IR feature encoder
"""
# in_channels == 1 or 3 or 4 or ....
# After 1st conv, B x n_feats x H x W
# After 2nd conv, B x 2n_feats x H/2 x W/2
# After 3rd conv, B x 3n_feats x H/4 x W/4
... | 1,707 | 28.964912 | 80 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/model/ResNet.py | import torch.nn as nn
from . import common
def build_model(args):
return ResNet(args)
class ResNet(nn.Module):
def __init__(self, args, in_channels=3, out_channels=3, n_feats=None, kernel_size=None, n_resblocks=None, mean_shift=True):
super(ResNet, self).__init__()
self.in_channels = in_chan... | 1,319 | 30.428571 | 127 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/model/discriminator.py | import torch.nn as nn
class Discriminator(nn.Module):
def __init__(self, args):
super(Discriminator, self).__init__()
# self.args = args
n_feats = args.n_feats
kernel_size = args.kernel_size
def conv(kernel_size, in_channel, n_feats, stride, pad=None):
if pad i... | 1,418 | 32.785714 | 102 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/model/common.py | import math
import torch
import torch.nn as nn
def default_conv(in_channels, out_channels, kernel_size, bias=True, groups=1):
return nn.Conv2d(
in_channels, out_channels, kernel_size,
padding=(kernel_size // 2), bias=bias, groups=groups)
def default_norm(n_feats):
return nn.BatchNorm2d(n_feat... | 5,120 | 30.611111 | 94 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/model/__init__.py | import os
import re
from importlib import import_module
import torch
import torch.nn as nn
from torch.nn.parallel import DataParallel, DistributedDataParallel
import torch.distributed as dist
from torch.nn.utils import parameters_to_vector, vector_to_parameters
from .discriminator import Discriminator
from utils im... | 4,594 | 32.540146 | 105 | py |
DeepDeblur-PyTorch | DeepDeblur-PyTorch-master/src/model/MSResNet.py | import torch
import torch.nn as nn
from . import common
from .ResNet import ResNet
def build_model(args):
return MSResNet(args)
class conv_end(nn.Module):
def __init__(self, in_channels=3, out_channels=3, kernel_size=5, ratio=2):
super(conv_end, self).__init__()
modules = [
comm... | 1,908 | 27.073529 | 78 | py |
PSENet.pytorch | PSENet.pytorch-master/eval.py | # -*- coding: utf-8 -*-
# @Time : 2018/6/11 15:54
# @Author : zhoujun
import torch
import shutil
import numpy as np
import config
import os
import cv2
from tqdm import tqdm
from models import PSENet
from predict import Pytorch_model
from cal_recall.script import cal_recall_precison_f1
from utils import draw_bbox
t... | 2,467 | 38.806452 | 122 | py |
PSENet.pytorch | PSENet.pytorch-master/predict.py | # -*- coding: utf-8 -*-
# @Time : 1/4/19 11:14 AM
# @Author : zhoujun
import torch
from torchvision import transforms
import os
import cv2
import time
import numpy as np
from pse import decode as pse_decode
class Pytorch_model:
def __init__(self, model_path, net, scale, gpu_id=None):
'''
初始化p... | 4,246 | 32.706349 | 122 | py |
PSENet.pytorch | PSENet.pytorch-master/train.py | # -*- coding: utf-8 -*-
# @Time : 2018/6/11 15:54
# @Author : zhoujun
import cv2
import os
import config
os.environ['CUDA_VISIBLE_DEVICES'] = config.gpu_id
import shutil
import glob
import time
import numpy as np
import torch
from tqdm import tqdm
from torch import nn
import torch.utils.data as Data
from torchvis... | 12,347 | 45.772727 | 159 | py |
PSENet.pytorch | PSENet.pytorch-master/pse/__init__.py | import subprocess
import os
import numpy as np
import cv2
import torch
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
if subprocess.call(['make', '-C', BASE_DIR]) != 0: # return value
raise RuntimeError('Cannot compile pse: {}'.format(BASE_DIR))
def pse_warpper(kernals, min_area=5):
'''
referenc... | 1,962 | 28.298507 | 91 | py |
PSENet.pytorch | PSENet.pytorch-master/dataset/data_utils.py | # -*- coding: utf-8 -*-
# @Time : 2018/6/11 15:54
# @Author : zhoujun
import os
import random
import pathlib
import pyclipper
from torch.utils import data
import glob
import numpy as np
import cv2
from dataset.augment import DataAugment
from utils.utils import draw_bbox
data_aug = DataAugment()
def check_and_va... | 8,637 | 36.556522 | 117 | py |
PSENet.pytorch | PSENet.pytorch-master/models/resnet.py | # -*- coding: utf-8 -*-
# @Time : 2019/1/2 17:30
# @Author : zhoujun
import torch
import torch.nn as nn
import math
import logging
import torch.utils.model_zoo as model_zoo
import torchvision.models.resnet
logger = logging.getLogger('project')
__all__ = ['ResNet', 'resnet50', 'resnet101',
'resnet152']
... | 7,039 | 29.742358 | 78 | py |
PSENet.pytorch | PSENet.pytorch-master/models/loss.py | # -*- coding: utf-8 -*-
# @Time : 3/29/19 11:03 AM
# @Author : zhoujun
import torch
from torch import nn
import numpy as np
class PSELoss(nn.Module):
def __init__(self, Lambda, ratio=3, reduction='mean'):
"""Implement PSE Loss.
"""
super(PSELoss, self).__init__()
assert reducti... | 4,220 | 38.083333 | 118 | py |
PSENet.pytorch | PSENet.pytorch-master/models/model.py | # -*- coding: utf-8 -*-
# @Time : 2019/1/2 17:29
# @Author : zhoujun
import torch
from torch import nn
import torch.nn.functional as F
from models.resnet import resnet18, resnet34, resnet50, resnet101, resnet152
from models.mobilenetv3 import MobileNetV3_Large, MobileNetV3_Small
from models.ShuffleNetV2 import shuf... | 5,276 | 44.102564 | 110 | py |
PSENet.pytorch | PSENet.pytorch-master/models/mobilenetv3.py | # -*- coding: utf-8 -*-
# @Time : 2019/5/23 15:22
# @Author : zhoujun
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
class hswish(nn.Module):
def forward(self, x):
out = x * F.relu6(x + 3, inplace=True) / 6
return out
class hsigmoid(nn.Module):
... | 7,437 | 35.460784 | 101 | py |
PSENet.pytorch | PSENet.pytorch-master/models/ShuffleNetV2.py | import torch
import torch.nn as nn
import logging
from torchvision.models.utils import load_state_dict_from_url
logger = logging.getLogger('project')
__all__ = [
'ShuffleNetV2', 'shufflenet_v2_x0_5', 'shufflenet_v2_x1_0',
'shufflenet_v2_x1_5', 'shufflenet_v2_x2_0'
]
model_urls = {
'shufflenetv2_x0.5': 'h... | 7,854 | 35.534884 | 112 | py |
PSENet.pytorch | PSENet.pytorch-master/utils/lr_scheduler.py | # -*- coding: utf-8 -*-
# @Time : 1/19/19 3:37 PM
# @Author : zhoujun
from torch.optim.lr_scheduler import MultiStepLR
class WarmupMultiStepLR(MultiStepLR):
def __init__(self, optimizer, milestones, gamma=0.1, warmup_factor=1.0 / 3,
warmup_iters=500, last_epoch=-1):
self.warmup_factor... | 739 | 36 | 79 | py |
PSENet.pytorch | PSENet.pytorch-master/utils/utils.py | # -*- coding: utf-8 -*-
# @Time : 1/4/19 11:18 AM
# @Author : zhoujun
import cv2
import time
import torch
import numpy as np
import matplotlib.pyplot as plt
def show_img(imgs: np.ndarray, color=False):
if (len(imgs.shape) == 3 and color) or (len(imgs.shape) == 2 and not color):
imgs = np.expand_dims(i... | 3,169 | 35.860465 | 112 | py |
iQPP | iQPP-main/QPP_Methods/Selfsupervised_Head/SelfSupervised-Head.py | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
from collections import Counter
from scipy.stats import kendalltau
from sklearn.cluster import KMeans
from ast import literal_eval
import torch.nn as nn
from sklearn.neural_network import MLPClassifier
from scipy.stats import kurt... | 3,243 | 28.225225 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Correlation_CNN/CorrelationCNNTrain.py | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import pickle
import torch
from torch.utils.data import DataLoader, Dataset,DataLoader,random_split
from sklearn.model_selection import KFold
from torch.optim import Adam
import torch.nn as nn
import numpy as np
from numpy import dot
from numpy.linal... | 9,091 | 26.635258 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Correlation_CNN/CorrelationCNNKFold.py | import pandas as pd
import pickle
import torch
from torch.utils.data import DataLoader, Dataset,DataLoader,random_split
from torch.optim import Adam
import torch.nn as nn
import numpy as np
from numpy import dot
from numpy.linalg import norm
import re
import argparse
parser = argparse.ArgumentParser()
parser.add_argu... | 7,361 | 21.722222 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Fine-Tuned_ViT/VitRegressorKFold.py | #!/usr/bin/env python
# coding: utf-8
import torch
import pandas as pd
import torch.nn as nn
import pandas as pd
import numpy as np
import pickle
from torchvision.models import vit_b_32
from torch.utils.data import Dataset, DataLoader
from sklearn.model_selection import train_test_split
from torchvision.models import... | 5,908 | 31.467033 | 172 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.