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 |
|---|---|---|---|---|---|---|
PT-MAP | PT-MAP-master/test_standard.py | import collections
import pickle
import random
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.optim as optim
import math
import torch.nn.functional as F
import torch.optim as optim
from numpy imp... | 6,764 | 28.159483 | 122 | py |
PT-MAP | PT-MAP-master/wrn_mixup_model.py | ### dropout has been removed in this code. original code had dropout#####
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from torch.autograd import Variable
import sys, os
import numpy as np
import random
act = torch.nn.ReLU()
import math
from torch.nn.utils.weight_no... | 7,986 | 36.674528 | 206 | py |
PT-MAP | PT-MAP-master/res_mixup_model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import random
from torch.nn.utils.weight_norm import WeightNorm
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
... | 7,280 | 35.58794 | 206 | py |
PT-MAP | PT-MAP-master/save_plk.py | from __future__ import print_function
import argparse
import csv
import os
import collections
import pickle
import random
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 transfor... | 3,145 | 27.342342 | 108 | py |
PT-MAP | PT-MAP-master/FSLTask.py | import os
import pickle
import numpy as np
import torch
# from tqdm import tqdm
# ========================================================
# Usefull paths
_datasetFeaturesFiles = {"miniimagenet": "./checkpoints/miniImagenet/WideResNet28_10_S2M2_R/last/output.plk",
"cub": "./checkpoints/CUB/W... | 5,459 | 32.090909 | 109 | py |
PT-MAP | PT-MAP-master/train_cifar.py | #!/usr/bin/env python3 -u
# Copyright (c) 2017-present, Facebook, Inc.
# 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 __future__ import print_function
import argparse
import csv
import os
import numpy as np
import t... | 11,421 | 35.375796 | 199 | py |
PT-MAP | PT-MAP-master/train.py | #!/usr/bin/env python3 -u
# Copyright (c) 2017-present, Facebook, Inc.
# 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 __future__ import print_function
import argparse
import csv
import os
import numpy as np
import t... | 13,168 | 35.278237 | 199 | py |
PT-MAP | PT-MAP-master/data/additional_transforms.py | # Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from PIL import ImageEnhance
transformtypedict=dict(Brightness=ImageEnhance.Brightness, Contrast=ImageEnhance.Contrast... | 850 | 24.787879 | 150 | py |
PT-MAP | PT-MAP-master/data/dataset.py | # This code is modified from https://github.com/facebookresearch/low-shot-shrink-hallucinate
import torch
from PIL import Image
import json
import numpy as np
import torchvision.transforms as transforms
import os
identity = lambda x:x
class SimpleDataset:
def __init__(self, data_file, transform, target_transform=i... | 2,920 | 32.193182 | 108 | py |
PT-MAP | PT-MAP-master/data/datamgr.py | # This code is modified from https://github.com/facebookresearch/low-shot-shrink-hallucinate
import torch
from PIL import Image
import numpy as np
import torchvision.transforms as transforms
import data.additional_transforms as add_transforms
from data.dataset import SimpleDataset, SetDataset, EpisodicBatchSampler
fro... | 3,515 | 40.857143 | 123 | py |
GSA | GSA-main/GSA_CVPR/utils.py | import torch
import torch.nn.functional as F
def cutmix_data(x, y, Basic_model,alpha=1.0, cutmix_prob=0.5,):
assert alpha > 0
# generate mixed sample
lam = np.random.beta(alpha, alpha)
batch_size = x.size()[0]
index = torch.randperm(batch_size)
if torch.cuda.is_available():
index = in... | 32,557 | 37.759524 | 175 | py |
GSA | GSA-main/GSA_CVPR/buffer.py | import numpy as np
import math
import pdb
import torch
import torch.nn as nn
import torch.nn.functional as F
class Buffer(nn.Module):
def __init__(self, args, input_size=None):
super().__init__()
self.args = args
self.k = 0.03
self.place_left = True
if input_size is Non... | 16,903 | 38.962175 | 193 | py |
GSA | GSA-main/GSA_CVPR/Resnet18.py | # Copyright 2020-present, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Davide Abati, Simone Calderara.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
import torch.nn.functional as F
f... | 11,584 | 37.108553 | 151 | py |
GSA | GSA-main/GSA_CVPR/conf.py | # Copyright 2020-present, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Davide Abati, Simone Calderara.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import random
import torch
import numpy as np
from abc import abstra... | 3,209 | 25.311475 | 107 | py |
GSA | GSA-main/GSA_CVPR/test_cifar100.py | import ipaddress
import sys, argparse
import numpy as np
import torch
from torch.nn.functional import relu, avg_pool2d
from buffer import Buffer
# import utils
import datetime
from torch.nn.functional import relu
import torch
import torch.nn as nn
import torch.nn.functional as F
from CSL import tao as TL
from CSL impor... | 33,352 | 38.65874 | 187 | py |
GSA | GSA-main/GSA_CVPR/cifar.py | import os,sys
import numpy as np
import torch
#import utils
from torchvision import datasets,transforms
from sklearn.utils import shuffle
import torch.utils.data as Data
def get(seed=0,pc_valid=0.10):
data = {}
taskcla = []
size = [3, 32, 32]
t_num=2
# CIFAR10
if not os.path.isdir('./data/bin... | 75,193 | 45.04654 | 239 | py |
GSA | GSA-main/GSA_CVPR/CSL/base_model.py | from abc import *
import torch.nn as nn
import torch
import torch.nn.functional as F
class BaseModel(nn.Module, metaclass=ABCMeta):
def __init__(self, last_dim=300, num_classes=10, simclr_dim=400):
super(BaseModel, self).__init__()
self.linear = nn.Linear(last_dim, num_classes)
self.out_nu... | 1,540 | 29.82 | 76 | py |
GSA | GSA-main/GSA_CVPR/CSL/tao.py | import math
import numbers
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
if torch.__version__ >= '1.4.0':
kwargs = {'align_corners': False}
else:
kwargs = {}
def rgb2hsv(rgb):
"""Convert a 4-d RGB tensor to the HSV counterpart.
... | 23,890 | 36.388106 | 117 | py |
GSA | GSA-main/GSA_CVPR/CSL/utils.py | import os
import pickle
import random
import shutil
import sys
from datetime import datetime
import numpy as np
import torch
from matplotlib import pyplot as plt
from tensorboardX import SummaryWriter
class Logger(object):
"""Reference: https://gist.github.com/gyglim/1f8dfb1b5c82627ae3efcfbbadb9f514"""
def ... | 6,511 | 30.61165 | 119 | py |
GSA | GSA-main/GSA_CVPR/CSL/classifier.py | import torch.nn as nn
#from models.resnet import ResNet18, ResNet34, ResNet50
#from models.resnet_imagenet import resnet18, resnet50
from CSL import tao as TL
def get_simclr_augmentation(P, image_size):
# parameter for resizecrop
#P.resize_fix = False
resize_scale = (P.resize_factor, 1.0) # resize scali... | 2,686 | 27.585106 | 100 | py |
GSA | GSA-main/GSA_CVPR/CSL/shedular.py | from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau
class GradualWarmupScheduler(_LRScheduler):
""" Gradually warm-up(increasing) learning rate in optimizer.
Proposed in 'Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour'.
Args:
optimi... | 3,069 | 46.96875 | 152 | py |
GSA | GSA-main/GSA_CVPR/CSL/contrastive_learning.py | import torch
import torch.distributed as dist
import diffdist.functional as distops
import torch.nn as nn
import torch.nn.functional as F
def get_similarity_matrix(outputs, chunk=2, multi_gpu=False):
'''
Compute similarity matrix
- outputs: (B', d) tensor for B' = B * chunk
- sim_matrix: ... | 9,602 | 37.107143 | 112 | py |
GSA | GSA-main/GSA_CVPR/CSL/general_loss.py | import torch
import numpy
def generalized_contrastive_loss(
hidden1,
hidden2,
lambda_weight=0.5,
temperature=0.5,
dist='normal',
hidden_norm=True,
loss_scaling=2.0):
"""Generalized contrastive loss.
Both hidden1 and hidden2 should have shape of (n, d).
Configurations to get followin... | 6,102 | 30.621762 | 130 | py |
FMLD | FMLD-main/mask-test.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 31 22:57:43 2020
@author: borut batagelj
"""
import os
import torch
from torchvision import transforms, datasets
from torch.utils.data import DataLoader
from torch import nn
# Applying Transforms to the Data
image_transforms = {
'test': trans... | 3,464 | 28.615385 | 112 | py |
GNNImpute | GNNImpute-main/GNNImpute/layer.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def layer(layer_type, **kwargs):
if layer_type == 'GCNConv':
return GraphConvolution(in_features=kwargs['in_channels'], out_features=kwargs['out_channels'])
elif layer_type == 'GATConv':
return MultiHeadAttentionLay... | 4,298 | 35.74359 | 111 | py |
GNNImpute | GNNImpute-main/GNNImpute/utils.py | import torch
import numpy as np
import scanpy as sc
import scipy.sparse as sp
from sklearn.decomposition import PCA
from sklearn.neighbors import kneighbors_graph
def normalize(adata, filter_min_counts=True, size_factors=True, normalize_input=True, logtrans_input=True):
if filter_min_counts:
sc.pp.filter... | 2,914 | 28.15 | 115 | py |
GNNImpute | GNNImpute-main/GNNImpute/model.py | import torch
import torch.nn.functional as F
from .layer import layer
class GNNImpute(torch.nn.Module):
def __init__(self, input_dim, h_dim=512, z_dim=50, layerType='GATConv', heads=3):
super(GNNImpute, self).__init__()
#### Encoder ####
self.encode_conv1 = layer(layerType, in_channels=in... | 1,491 | 32.155556 | 87 | py |
GNNImpute | GNNImpute-main/GNNImpute/train.py | import os
import time
import glob
import torch
def train(gdata, model,
no_cuda=False,
epochs=3000,
lr=0.001,
weight_decay=0.0005,
patience=200,
fastmode=False,
verbose=True):
device = torch.device('cuda' if torch.cuda.is_available() and not no_... | 2,321 | 27.317073 | 89 | py |
dcstfn | dcstfn-master/experiment/run.py | import sys
sys.path.append('..')
import os
os.environ['KERAS_BACKEND'] = 'tensorflow'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import argparse
from functools import partial
import json
from keras import optimizers
from pathlib import Path
from toolbox.data import load_train_set
from toolbox.model import get_model
fr... | 1,517 | 28.192308 | 71 | py |
dcstfn | dcstfn-master/toolbox/experiment.py | from functools import partial
from pathlib import Path
import time
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from keras import backend as K
from keras.callbacks import CSVLogger, ModelCheckpoint
from keras.utils.vis_utils import plot_model
from keras.preprocessing.image import img_to_arra... | 7,661 | 37.119403 | 114 | py |
dcstfn | dcstfn-master/toolbox/model.py | import keras.layers
from keras.layers import Input, Conv2D, Conv2DTranspose, MaxPooling2D, Dense
from keras.models import Model, Sequential
##################################################################
# Deep Convolutional SpatioTemporal Fusion Network (DCSTFN)
####################################################... | 3,336 | 43.493333 | 87 | py |
dcstfn | dcstfn-master/toolbox/data.py | from pathlib import Path
import numpy as np
from functools import partial
from keras.preprocessing.image import img_to_array
from osgeo import gdal_array
from PIL import Image
repo_dir = Path(__file__).parents[1]
data_dir = repo_dir / 'data'
input_suffix = 'input'
pred_suffix = 'pred'
valid_suffix = 'valid'
modis_p... | 3,794 | 32 | 91 | py |
dcstfn | dcstfn-master/toolbox/metrics.py | from keras import backend as K
import tensorflow as tf
import numpy as np
def cov(x, y):
return K.mean((x - K.mean(x)) * K.transpose((y - K.mean(y))))
def psnr(y_true, y_pred, data_range=10000):
"""Peak signal-to-noise ratio averaged over samples and channels."""
mse = K.mean(K.square(y_true - y_pred), ... | 1,180 | 25.840909 | 74 | py |
MRI-ROI-prediction | MRI-ROI-prediction-main/lrmain.py | import os
import numpy as np
import time
import glob
import random
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
FLAGS = tf.compat.v1.flags.FLAGS
tf.compat.v1.flags.DEFINE_string('EXP','temp',"exp. name")
tf.compat.v1.flags.DEFINE_integer('mod', 0, "model") # 0=share, 1=chstack, 2=3D
class ConvNet(o... | 7,202 | 42.920732 | 201 | py |
MRI-ROI-prediction | MRI-ROI-prediction-main/main.py | import os
import numpy as np
import time
import glob
import random
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
FLAGS = tf.compat.v1.flags.FLAGS
tf.compat.v1.flags.DEFINE_string('EXP','temp',"exp. name")
tf.compat.v1.flags.DEFINE_integer('mod', 0, "model") # 0=share, 1=chstack, 2=3D
class ConvNet(o... | 7,211 | 42.709091 | 201 | py |
MRI-ROI-prediction | MRI-ROI-prediction-main/bmbn2D.py | import tensorflow as tf
def inference(self):
conv0 = tf.keras.layers.Conv2D(filters=16,
kernel_size=[5,5],
padding='SAME',
name='conv0')(self.img)
pool0 = tf.keras.layers.MaxPool2D(pool_size=[2, 2], st... | 2,898 | 44.296875 | 91 | py |
MRI-ROI-prediction | MRI-ROI-prediction-main/bmbn.py | import tensorflow as tf
def inference(self):
conv0 = tf.keras.layers.Conv3D(filters=16,
kernel_size=[5,5,5],
padding='SAME',
name='conv0')(tf.expand_dims(self.img, axis=-1))
pool0 = tf.keras.layers.Max... | 2,932 | 44.828125 | 114 | py |
MRI-ROI-prediction | MRI-ROI-prediction-main/share.py | import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
def inference(self):
encoder_input = keras.Input(shape=(512, 512, 1), name="one_slice")
x = layers.Conv2D(16, 5, activation="relu", strides=2)(encoder_input)
x = layers.LayerNormalization()(x)
x2 = layers.Conv2D(3... | 1,724 | 42.125 | 92 | py |
self-adaptive | self-adaptive-master/eval.py | import glob
from datetime import datetime
from tqdm import tqdm
from torch.utils.data import DataLoader
from utils.parser import val_parser
from loss.semantic_seg import CrossEntropyLoss
import models.backbone
import models
from utils.modeling import freeze_layers
from utils.self_adapt_norm import reinit_alpha
from ut... | 7,737 | 38.886598 | 114 | py |
self-adaptive | self-adaptive-master/train.py | import pathlib, os
from torch.utils.data import DataLoader
from torch.nn import SyncBatchNorm
from datetime import datetime
from tqdm import tqdm
from shutil import copyfile
from utils.parser import train_parser
import models.backbone
from loss.semantic_seg import CrossEntropyLoss
import datasets
from optimizer.schedu... | 9,999 | 44.248869 | 120 | py |
self-adaptive | self-adaptive-master/models/hrnet.py | """Source: https://github.com/HRNet/HRNet-Semantic-Segmentation"""
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by RainbowSecret (yhyuan@pku.edu.cn)
# ---------------------------------------------------------------... | 23,160 | 38.322581 | 268 | py |
self-adaptive | self-adaptive-master/models/deeplabv3.py | """Source: https://github.com/VainF/DeepLabV3Plus-Pytorch"""
from torch import nn
from torch.nn import functional as F
import torch
from typing import Dict
from collections import OrderedDict
from utils.dropout import add_dropout
from utils.self_adapt_norm import replace_batchnorm
from models.backbone_v3 import resne... | 12,863 | 36.614035 | 120 | py |
self-adaptive | self-adaptive-master/models/deeplab.py | import torch
from typing import Dict
from utils.dropout import add_dropout
from utils.self_adapt_norm import replace_batchnorm
import models.backbone
class DeepLab(torch.nn.Module):
def __init__(self,
backbone_name: str,
num_classes: int = 19,
dropout: bool = Fa... | 2,839 | 29.869565 | 87 | py |
self-adaptive | self-adaptive-master/models/backbone/resnet.py | '''
Source: torchvision
'''
import torch
import torch.nn as nn
from torch.hub import load_state_dict_from_url
# __all__ = {'resnet18': resnet18, 'resnet50': resnet50}
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resn... | 10,374 | 38.150943 | 106 | py |
self-adaptive | self-adaptive-master/models/backbone_v3/resnet.py | import torch
import torch.nn as nn
from torch.hub import load_state_dict_from_url
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
'wide_resnet50_2', 'wide_resnet101_2']
model_urls = {
'resnet18': 'https://download.py... | 13,547 | 39.807229 | 107 | py |
self-adaptive | self-adaptive-master/datasets/labels.py | import torch
from collections import namedtuple
from cityscapesscripts.helpers.labels import labels as cs_labels
from cityscapesscripts.helpers.labels import Label
synthia_cs_labels = [
# name id trainId category catId hasInstances ignoreInEval color
Label('unlabeled', 0, 255, '... | 15,789 | 38.673367 | 118 | py |
self-adaptive | self-adaptive-master/datasets/wilddash.py | import os
import torch
from PIL import Image
from typing import Callable, Optional, Tuple, List
class WilddashDataset(object):
"""
Unzip the downloaded wd_public_02.zip to /path/to/wilddash
The wilddash dataset is required to have following folder structure after unzipping:
wilddash/
/image... | 1,608 | 30.54902 | 88 | py |
self-adaptive | self-adaptive-master/datasets/cityscapes.py | import torchvision
from typing import Any, List, Callable
class CityscapesDataset(torchvision.datasets.Cityscapes):
def __init__(self,
transforms: List[Callable],
*args: Any,
**kwargs: Any):
super(CityscapesDataset, self).__init__(*args,
... | 704 | 29.652174 | 71 | py |
self-adaptive | self-adaptive-master/datasets/idd.py | import os
from typing import Tuple, List, Callable, Optional
from PIL import Image
import torch
class IDDDataset(object):
"""
Follow these steps to prepare the IDD dataset:
- Unpack the downloaded dataset: tar -xf idd-segmentation.tar.gz -C /path/to/IDD_Segmentation/
- Rename the directory from IDD_Seg... | 2,650 | 37.42029 | 129 | py |
self-adaptive | self-adaptive-master/datasets/self_adapt_augment.py | import torchvision.transforms.functional as F
import torchvision.transforms as tf
from PIL import Image, ImageFilter
import torch
from typing import List, Any
import os
import datasets
from utils import transforms
class TrainTestAugDataset:
def __init__(self,
device,
source,
... | 9,098 | 43.385366 | 117 | py |
self-adaptive | self-adaptive-master/datasets/gta.py | import os
import glob
import argparse
import pathlib
import PIL.Image
import torch
from typing import List, Callable, Optional, Tuple
from tqdm import tqdm
import urllib.request
import shutil
import scipy.io
class GTADataset(object):
"""
Download, unzip, and split data: python datasets/gta.py --dataset-root /p... | 6,655 | 37.473988 | 126 | py |
self-adaptive | self-adaptive-master/datasets/bdd.py | import torch
import os
from PIL import Image
from typing import Callable, Optional, Tuple, List
class BerkeleyDataset(object):
"""
First unzip the images: unzip bdd100k_images_10k.zip -d /path/to/bdd100k
Second unzip the labels in the same directory: unzip bdd100k_sem_seg_labels_trainval.zip -d /path/to/b... | 2,054 | 31.619048 | 112 | py |
self-adaptive | self-adaptive-master/datasets/synthia.py | from PIL import Image
from typing import Optional, Callable, Tuple, List
import os
import torch
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
class SynthiaDataset(object):
"""
The Synthia dataset is required to have following folder structure:
synthia/
leftImg8bit/
... | 2,133 | 32.34375 | 75 | py |
self-adaptive | self-adaptive-master/datasets/mapillary.py | import os
from PIL import Image
from typing import Callable, Optional, Tuple, List
import torch
class MapillaryDataset(object):
"""
The Mapillary dataset is required to have following folder structure:
mapillary/
training/
v1.2/labels/*.png
images... | 1,962 | 31.716667 | 100 | py |
self-adaptive | self-adaptive-master/loss/semantic_seg.py | import torch
from typing import Dict
class CrossEntropyLoss(torch.nn.Module):
def __init__(self,
ignore_index: int = 255):
super(CrossEntropyLoss, self).__init__()
self.criterion = torch.nn.CrossEntropyLoss(ignore_index=ignore_index, reduction="none")
self.ignore_index = ... | 1,961 | 30.645161 | 95 | py |
self-adaptive | self-adaptive-master/utils/montecarlo.py | import torch
import numpy as np
from typing import Union, List
class MonteCarloDropout(object):
def __init__(self,
size: Union[List, int],
passes: int = 10,
classes: int = 19):
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
... | 2,978 | 36.2375 | 96 | py |
self-adaptive | self-adaptive-master/utils/modeling.py | import functools
import torch
def rsetattr(obj, attr, val):
pre, _, post = attr.rpartition('.')
return setattr(rgetattr(obj, pre) if pre else obj, post, val)
def rgetattr(obj, attr, *args):
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return functools.reduce(_getattr, [obj] + attr... | 1,782 | 40.465116 | 103 | py |
self-adaptive | self-adaptive-master/utils/calibration.py | """
Guo et al.: O Calibration of Modern Neural Networks, 2017, ICML
https://arxiv.org/abs/1706.04599
Code based on implementation of G. Pleiss: https://gist.github.com/gpleiss/0b17bc4bd118b49050056cfcd5446c71
"""
import torch
import numpy as np
import matplotlib.pyplot as plt
import pickle
import os
import pathlib
cl... | 9,011 | 41.309859 | 122 | py |
self-adaptive | self-adaptive-master/utils/dropout.py | from utils.modeling import rsetattr
import torch, math
def add_dropout(model: torch.nn.Module,
dropout_start_perc: float = 0.0,
dropout_stop_perc: float = 1.0,
dropout_prob: float = 0.1):
# Add dropout layers after relu
dropout_cls = torch.nn.Dropout
dropout... | 854 | 39.714286 | 92 | py |
self-adaptive | self-adaptive-master/utils/distributed.py | import os
import torch
import torch.distributed
def init_process(opts,
gpu: int) -> int:
# Define world size
opts.world_size = opts.gpus
os.environ['MASTER_ADDR'] = '127.0.0.1'
os.environ['MASTER_PORT'] = '8888'
# Calculate rank
rank = gpu
# Initiate process group
to... | 702 | 24.107143 | 68 | py |
self-adaptive | self-adaptive-master/utils/metrics.py | # Adapted from score written by wkentaro
# https://github.com/wkentaro/pytorch-fcn/blob/master/torchfcn/utils.py
import numpy as np
class runningScore():
def __init__(self,
n_classes: int):
self.n_classes = n_classes
self.confusion_matrix = np.zeros((n_classes, n_classes))
... | 1,963 | 30.174603 | 96 | py |
self-adaptive | self-adaptive-master/utils/self_adapt_norm.py | import torch.nn as nn
from copy import deepcopy
from utils.modeling import *
class SelfAdaptiveNormalization(nn.Module):
def __init__(self,
num_features: int,
unweighted_stats: bool = False,
eps: float = 1e-5,
momentum: float = 0.1,
... | 4,140 | 43.053191 | 112 | py |
self-adaptive | self-adaptive-master/utils/transforms.py | import torch, random
import torchvision.transforms.functional as F
import torchvision.transforms as tf
import numpy as np
from PIL import Image, ImageFilter
from typing import Tuple, List, Callable
from datasets.labels import convert_ids_to_trainids, convert_trainids_to_ids
class Compose:
def __init__(self,
... | 6,474 | 26.553191 | 113 | py |
self-adaptive | self-adaptive-master/optimizer/schedulers.py | '''
Source: https://github.com/meetshah1995/pytorch-semseg
'''
from torch.optim.lr_scheduler import _LRScheduler
import torch
from typing import List
def get_scheduler(scheduler_type: str,
optimizer: torch.optim.Optimizer,
max_iter: int) -> _LRScheduler:
if scheduler_type == "... | 1,823 | 30.448276 | 102 | py |
drlviz | drlviz-master/distributions.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 14 11:35:22 2018
@author: edward
"""
import torch.nn as nn
import torch.nn.functional as F
class Categorical(nn.Module):
def __init__(self, num_inputs, num_outputs):
super(Categorical, self).__init__()
self.linear = nn.Linear(... | 991 | 22.069767 | 58 | py |
drlviz | drlviz-master/reduce.py | import ujson
from random import randint
import numpy as np
import torch
from torch.autograd import Variable
from arguments import parse_game_args
from doom_evaluation import BaseAgent
from environments import DoomEnvironment
from models import CNNPolicy
import base64
import io
from PIL import Image
def gen_classic(... | 11,617 | 64.638418 | 440 | py |
drlviz | drlviz-master/models.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 14 10:53:06 2018
@author: edward
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from distributions import Categorical
# A temporary solution from the master branch.
# https://github.com/pytorch/pytorch/blob/7752fe5d4e500... | 10,104 | 33.370748 | 104 | py |
drlviz | drlviz-master/doom_evaluation.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 14 14:31:17 2018
@author: edward
"""
if __name__ == '__main__': # changes backend for animation tests
import matplotlib
matplotlib.use("Agg")
import numpy as np
from collections import deque
from moviepy.editor import ImageSequenceClip
fr... | 10,654 | 32.296875 | 146 | py |
spyn-repr | spyn-repr-master/spn/factory.py | from spn.linked.spn import Spn as SpnLinked
from spn.linked.layers import Layer as LayerLinked
from spn.linked.layers import SumLayer as SumLayerLinked
from spn.linked.layers import ProductLayer as ProductLayerLinked
from spn.linked.layers import CategoricalInputLayer
from spn.linked.layers import CategoricalSmoothedL... | 56,522 | 36.358229 | 97 | py |
spyn-repr | spyn-repr-master/spn/theanok/layers.py | import numpy
import theano
import theano.tensor as T
from spn import LOG_ZERO
from .initializations import Initialization, sharedX, ndim_tensor
import os
#
# inspired by Keras
#
def exp_activation(x):
return T.exp(x)
def log_activation(x):
return T.log(x).clip(LOG_ZERO, 0.)
def log_sum_exp_activation(x... | 13,956 | 28.259958 | 105 | py |
normalizing_flows | normalizing_flows-master/test.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as D
from torch.utils.data import DataLoader, Dataset
import unittest
from unittest.mock import MagicMock
from maf import MADE, MADEMOG, MAF, MAFMOG, RealNVP, BatchNorm, LinearMaskedCoupling, train
from glow import Actnorm, ... | 17,209 | 45.016043 | 156 | py |
normalizing_flows | normalizing_flows-master/data.py | from functools import partial
import numpy as np
import torch
import torchvision.transforms as T
from torch.utils.data import DataLoader, TensorDataset
import datasets
# --------------------
# Helper functions
# --------------------
def logit(x, eps=1e-5):
x.clamp_(eps, 1 - eps)
return x.log() - (1 - x).log... | 4,218 | 36.336283 | 146 | py |
normalizing_flows | normalizing_flows-master/glow.py | """
Glow: Generative Flow with Invertible 1x1 Convolutions
arXiv:1807.03039v2
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as D
import torchvision.transforms as T
from torchvision.utils import save_image, make_grid
from torch.utils.data import DataLoader
from torch.... | 35,698 | 45.302205 | 181 | py |
normalizing_flows | normalizing_flows-master/bnaf.py | """
Implementation of Block Neural Autoregressive Flow
http://arxiv.org/abs/1904.04676
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as D
from torch.utils.data import DataLoader, TensorDataset
import math
import os
import time
import argparse
import pprint
from func... | 20,690 | 42.836864 | 163 | py |
normalizing_flows | normalizing_flows-master/maf.py | """
Masked Autoregressive Flow for Density Estimation
arXiv:1705.07057v4
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as D
import torchvision.transforms as T
from torchvision.utils import save_image
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot a... | 31,985 | 41.762032 | 169 | py |
normalizing_flows | normalizing_flows-master/planar_flow.py | """
Variational Inference with Normalizing Flows
arXiv:1505.05770v6
"""
import torch
import torch.nn as nn
import torch.distributions as D
import math
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os
import argparse
parser = argparse.ArgumentParser()
# action
parser.add_argument('-... | 12,324 | 39.811258 | 151 | py |
normalizing_flows | normalizing_flows-master/datasets/moons.py | import torch
import torch.distributions as D
from torch.utils.data import Dataset
from sklearn.datasets import make_moons
class MOONS(Dataset):
def __init__(self, dataset_size=25000, **kwargs):
self.x, self.y = make_moons(n_samples=dataset_size, shuffle=True, noise=0.05)
self.input_size = 2
... | 512 | 20.375 | 85 | py |
normalizing_flows | normalizing_flows-master/datasets/toy.py | import torch
import torch.distributions as D
from torch.utils.data import Dataset
class ToyDistribution(D.Distribution):
def __init__(self, flip_var_order):
super().__init__()
self.flip_var_order = flip_var_order
self.p_x2 = D.Normal(0, 4)
self.p_x1 = lambda x2: D.Normal(0.25 * x2*... | 1,214 | 27.255814 | 90 | py |
normalizing_flows | normalizing_flows-master/datasets/__init__.py | root = 'data/'
#from .power import POWER
#from .gas import GAS
#from .hepmass import HEPMASS
#from .miniboone import MINIBOONE
#from .bsds300 import BSDS300
#from .toy import TOY
#from .moons import MOONS
#from .mnist import MNIST
#from torchvision.datasets import MNIST, CIFAR10
| 283 | 19.285714 | 48 | py |
normalizing_flows | normalizing_flows-master/datasets/celeba.py | import os
from PIL import Image
import numpy as np
import torch
from torch.utils.data import Dataset
class CelebA(Dataset):
processed_file = 'processed.pt'
partition_file = 'Eval/list_eval_partition.txt'
attr_file = 'Anno/list_attr_celeba.txt'
img_folder = 'Img/img_align_celeba'
attr_names = '5_o_... | 5,419 | 43.793388 | 490 | py |
SpinalNet | SpinalNet-master/Regression/Regression_NN_and_SpinalNet.py | # -*- coding: utf-8 -*-
"""
This script performs regression on toy datasets.
There exist several relations between inputs and output.
We investigate both of the traditional feed-forward and SpinalNet
for all of these input-output relations.
----------
Multiplication:
y = x1*x2*x3*x4*x5*x6*x7*x8 + 0.2*torch.rand(x1... | 5,420 | 28.302703 | 105 | py |
SpinalNet | SpinalNet-master/Transfer Learning/Transfer_Learning_hymenoptera.py | '''
Most part of the code and dataset is copied from PyTorch demo:
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
'''
from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
impor... | 7,504 | 29.384615 | 78 | py |
SpinalNet | SpinalNet-master/Transfer Learning/Transfer_Learning_STL10.py | '''
We write this code with the help of PyTorch demo:
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
Data is downloaded from pytorch and divided into folders
using script 'Pytorch_data_to_folders.py'
Effects:
transforms.Resize((272,272)),
transforms.RandomRotation(15,),
... | 7,704 | 30.068548 | 93 | py |
SpinalNet | SpinalNet-master/Transfer Learning/Transfer_Learning_CIFAR100.py | '''
We write this code with the help of PyTorch demo:
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
Dataset is distributed in folders with following script:
https://au.mathworks.com/matlabcentral/answers/329597-save-cifar-100-images
Performances:
Data augmentation:
transforms.Res... | 8,199 | 28.818182 | 93 | py |
SpinalNet | SpinalNet-master/Transfer Learning/Transfer_Learning_CIFAR10.py | '''
We write this code with the help of PyTorch demo:
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
The dataset is downloaded from https://www.kaggle.com/swaroopkml/cifar10-pngs-in-folders
Performances:
Data augmentation:
transforms.Resize((272,272)),
transforms.RandomRotati... | 9,644 | 30.314935 | 93 | py |
SpinalNet | SpinalNet-master/Transfer Learning/Transfer_Learning_SVHN.py | '''
Data is downloaded from pytorch and divided into folders
using script 'Pytorch_data_to_folders.py'
Effects:
transforms.Resize((272,320)),
transforms.RandomRotation(15,),
transforms.CenterCrop(272),
transforms.RandomCrop(256),
transforms.ToTensor(),
wide_resnet101_2 Spinal... | 9,514 | 30.611296 | 93 | py |
SpinalNet | SpinalNet-master/Transfer Learning/Transfer_Learning_CINIC10.py | '''
We write this code with the help of PyTorch demo:
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
The Dataset is downloaded from https://www.kaggle.com/mengcius/cinic10
Effects:
transforms.Resize((272,272)),
transforms.RandomRotation(15,),
transforms.RandomC... | 10,712 | 31.761468 | 113 | py |
SpinalNet | SpinalNet-master/Transfer Learning/Transfer_Learning_Caltech101.py | '''
We write this code with the help of PyTorch demo:
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
Dataset is Downloaded from https://www.kaggle.com/huangruichu/caltech101/version/2
Effects:
transforms.Resize((230,230)),
transforms.RandomRotation(15,),
transfo... | 10,203 | 30.788162 | 93 | py |
SpinalNet | SpinalNet-master/Transfer Learning/Pytorch_data_to_folders.py | # -*- coding: utf-8 -*-
"""
We need to create train and val folders manually before running the script
@author: Dipu
"""
import torchvision
import matplotlib
import matplotlib.pyplot as plt
import numpy
import imageio
import os
data_train = torchvision.datasets.SVHN('./data', split='train', download=True,
... | 1,195 | 28.170732 | 83 | py |
SpinalNet | SpinalNet-master/Transfer Learning/Transfer_Learning_Fruits360.py | '''
We write this code with the help of PyTorch demo:
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
Dataset is Downloaded from https://www.kaggle.com/moltean/fruits
Effects:
transforms.Resize((140,140)),
transforms.RandomRotation(15,),
transforms.RandomResizedC... | 9,786 | 32.064189 | 93 | py |
SpinalNet | SpinalNet-master/Transfer Learning/Transfer_Learning_Stanford_Cars.py |
'''
Stanford Cars
We write this code with the help of PyTorch demo:
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
Dataset is downloaded from https://www.kaggle.com/jutrera/stanford-car-dataset-by-classes-folder?
Effect:
transforms.Resize((456,456)),
transforms.RandomRotat... | 9,929 | 30.52381 | 97 | py |
SpinalNet | SpinalNet-master/Transfer Learning/Transfer_Learning_Oxford102flower.py | '''
We write this code with the help of PyTorch demo:
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
The dataset is downloaded from https://www.kaggle.com/c/oxford-102-flower-pytorch/data
Effects:
transforms.Resize((464,464)),
transforms.RandomRotation(15,),
tra... | 9,691 | 30.986799 | 93 | py |
SpinalNet | SpinalNet-master/Transfer Learning/Transfer_Learning_Bird225.py | '''
We write this code with the help of PyTorch demo:
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
Data Link:
https://www.kaggle.com/gpiosenka/100-bird-species
Version 30
Downloaded on 20/08/2020
Performances:
Data augmentation:
transforms.Resize((230,230)),
t... | 8,387 | 28.850534 | 120 | py |
SpinalNet | SpinalNet-master/Transfer Learning/Transfer_Learning_MNIST.py | # Execution info: https://www.kaggle.com/dipuk0506/transfer-learning-on-mnist
from __future__ import print_function, division
import matplotlib
import imageio
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import torchvision
from torchvision impo... | 10,753 | 29.725714 | 93 | py |
SpinalNet | SpinalNet-master/CIFAR-10/ResNet_default_and_SpinalFC_CIFAR10.py | # -*- coding: utf-8 -*-
"""
This Script contains the default and Spinal ResNet code for CIFAR-10.
This code trains both NNs as two different models.
There is option of choosing ResNet18(), ResNet34(), SpinalResNet18(), or
SpinalResNet34().
This code randomly changes the learning rate to get a good result.
@author: ... | 13,289 | 29.906977 | 101 | py |
SpinalNet | SpinalNet-master/CIFAR-10/VGG_default_and_SpinalFC_CIFAR10.py | # -*- coding: utf-8 -*-
"""
This Script contains the default and Spinal VGG code for CIFAR-10.
This code trains both NNs as two different models.
There is option of choosing NN among:
vgg11_bn(), vgg13_bn(), vgg16_bn(), vgg19_bn() and
Spinalvgg11_bn(), Spinalvgg13_bn(), Spinalvgg16_bn(), Spinalvgg19_bn()
Thi... | 8,991 | 28.578947 | 116 | py |
SpinalNet | SpinalNet-master/CIFAR-10/CNN_dropout_CIFAR10.py | # -*- coding: utf-8 -*-
"""
This Script contains the default CNN dropout code for comparison.
The code is collected and changed from:
https://zhenye-na.github.io/2018/09/28/pytorch-cnn-cifar10.html
@author: Dipu
"""
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transfo... | 4,878 | 27.04023 | 97 | py |
SpinalNet | SpinalNet-master/CIFAR-10/CNN_dropout_SpinalFC_CIFAR10.py | # -*- coding: utf-8 -*-
"""
This Script contains the CNN dropout with Spinal fully-connected layer.
@author: Dipu
"""
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import random
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else ... | 7,532 | 29.746939 | 93 | py |
SpinalNet | SpinalNet-master/MNIST_VGG/EMNIST_digits_VGG_and _SpinalVGG.py | # -*- coding: utf-8 -*-
"""
This Script contains the default and Spinal VGG code for EMNIST(Digits).
This code trains both NNs as two different models.
This code randomly changes the learning rate to get a good result.
@author: Dipu
"""
import torch
import torchvision
import torch.nn as nn
import math
import torch... | 11,675 | 32.551724 | 116 | py |
SpinalNet | SpinalNet-master/MNIST_VGG/KMNIST_VGG_and_SpinalVGG.py | # -*- coding: utf-8 -*-
"""
This Script contains the default and Spinal VGG code for kMNIST.
This code trains both NNs as two different models.
This code randomly changes the learning rate to get a good result.
@author: Dipu
"""
import torch
import torchvision
import torch.nn as nn
import math
import torch.nn.func... | 11,721 | 32.301136 | 116 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.