repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
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 |
PT-MAP | PT-MAP-master/data/__init__.py | from . import datamgr
from . import dataset
from . import additional_transforms
| 80 | 19.25 | 35 | py |
PyDraw | PyDraw-master/HS.py | # 调用函数
def hello():
print('© JY.Lin!The first author, 2018/07/31')
# ********************************************************************************
# ********************************************************************************
# *******************************************************************************... | 510 | 14.484848 | 82 | py |
PyDraw | PyDraw-master/ZJM.py | from tkinter import *
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
from tkinter.messagebox import *
import tkinter.colorchooser
import tkinter.filedialog
import tkinter as tk
import HS
canva_W = 0
canva_H = 0
flag_CK_GuDing = FALSE
canva_X = 60
canva_Y = 50
WangGe_KuanDu = 20
WangGe_ShuMu_X... | 289,749 | 38.784429 | 184 | 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 |
FMLD | FMLD-main/show_save_gt.py | # Copyright 2021 Borut Batagelj.
import glob
import os
import xml.etree.ElementTree as ET
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from tqdm import tqdm
show_annotations=False #show image with annotations
save_faces=True #save faces from images to folders: correctly_worn, without_mask, i... | 3,245 | 33.531915 | 131 | py |
GNNImpute | GNNImpute-main/example/test.py | # %%
import numpy as np
import scanpy as sc
from scipy import sparse
from sklearn.cluster import KMeans
from sklearn.metrics import mean_squared_error, mean_absolute_error
from sklearn.metrics.cluster import adjusted_rand_score, normalized_mutual_info_score
from scipy.stats import pearsonr
from sklearn.metrics.pairwis... | 2,432 | 25.445652 | 85 | py |
GNNImpute | GNNImpute-main/data/mask.py | # %%
import os
import copy
import numpy as np
import pandas as pd
import scanpy as sc
from scipy import sparse
# %%
# def mask(data_train, masked_prob):
# """
# 将表达矩阵中非零的值随机置为0并返回,同时返回置为0的元素的坐标
# :param data_train: 表达矩阵
# :param masked_prob: 置0比例
# :return:
# """
# index_pair_train = np.... | 2,838 | 30.898876 | 121 | py |
GNNImpute | GNNImpute-main/data/PBMC/preprocess.py | # %%
import os
import sys
import codecs
import scanpy as sc
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
# %%
adata = sc.read_10x_mtx('./data/PBMC/', var_names='gene_symbols', cache=True)
# %%
adata.var['mt'] = adata.var_names.str.startswith('MT-')
sc.pp.calculate_qc_metrics(adata, qc_vars=['mt'], pe... | 1,769 | 32.396226 | 117 | py |
GNNImpute | GNNImpute-main/data/Klein/preprocess.py | # %%
import os
import scanpy as sc
from scipy import sparse
# %%
adataD0 = sc.read_csv('./data/Klein/GSM1599494_ES_d0_main.csv.bz2')
adataD2 = sc.read_csv('./data/Klein/GSM1599497_ES_d2_LIFminus.csv.bz2')
adataD4 = sc.read_csv('./data/Klein/GSM1599498_ES_d4_LIFminus.csv.bz2')
adataD7 = sc.read_csv('./data/Klein/GSM15... | 1,126 | 26.487805 | 95 | 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/api.py | from .model import GNNImpute as Model
from .train import train
from .utils import adata2gdata, train_val_split, normalize
def GNNImpute(adata,
layer='GATConv',
no_cuda=False,
epochs=3000,
lr=0.001,
weight_decay=0.0005,
hidden=50,
... | 1,004 | 28.558824 | 101 | py |
GNNImpute | GNNImpute-main/GNNImpute/__init__.py | 0 | 0 | 0 | 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/experiment/__init__.py | 0 | 0 | 0 | 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/misc.py | import math
def factorize(n):
def prime(n):
return not [x for x in range(2, int(math.sqrt(n)) + 1) if n % x == 0]
primes = []
candidates = range(2, n + 1)
candidate = 2
while not primes and candidate in candidates:
if n % candidate == 0 and prime(candidate):
primes += [... | 453 | 24.222222 | 77 | 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 |
dcstfn | dcstfn-master/toolbox/__init__.py | 1 | 0 | 0 | py | |
dcstfn | dcstfn-master/utils/evaluate.py | import argparse
from pathlib import Path
import numpy as np
from osgeo import gdal_array
from math import sqrt
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from skimage.measure import compare_psnr, compare_ssim
def evaluate(y_true, y_pred, func):
assert y_true.shape == y_pred.shap... | 2,272 | 28.519481 | 80 | py |
dcstfn | dcstfn-master/utils/draw_loss.py | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context("paper", rc={'font.sans-serif': 'Helvetica',
'font.size': 12})
df_green = pd.read_csv('~/Resources/Experiments/dcfnex-12/dcstfn-green/train/history.csv')
df_red = pd.read_csv('~/Resources/Experiments... | 2,234 | 35.048387 | 100 | py |
dcstfn | dcstfn-master/utils/draw_sr.py | import argparse
from pathlib import Path
import numpy as np
from scipy.stats import gaussian_kde
from sklearn.metrics import r2_score
import matplotlib.pyplot as plt
from osgeo import gdal_array
import seaborn as sns
sns.set_context("paper", rc={'font.sans-serif': 'Arial',
'font.size': 12})... | 2,157 | 32.2 | 95 | py |
dcstfn | dcstfn-master/utils/draw_fit.py | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context("paper", rc={'font.sans-serif': 'Helvetica',
'font.size': 12})
df_green = pd.read_csv('~/Resources/Experiments/dcfnex-12/dcstfn-green/train/history.csv')
df_red = pd.read_csv('~/Resources/Experiments... | 1,820 | 34.019231 | 100 | py |
dcstfn | dcstfn-master/utils/__init__.py | 0 | 0 | 0 | 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 |
MRI-ROI-prediction | MRI-ROI-prediction-main/demo.py | import os
import numpy as np
import time
import glob
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
FLAGS = tf.compat.v1.flags.FLAGS
tf.compat.v1.flags.DEFINE_string('EXP','newattn2AsS/ckpt-80546',"exp and ckpt name")
tf.compat.v1.flags.DEFINE_integer('mod', 0, "model") # 0=share, 1=chstack, 2=3D
cla... | 4,214 | 39.142857 | 144 | 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/hrnet_config.py | """Source: https://github.com/HRNet/HRNet-Semantic-Segmentation"""
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Create by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Ke Sun (sunk@mail.ustc.edu.cn), Rainbowsecret (yuyua... | 3,735 | 27.519084 | 81 | 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/__init__.py | from models.deeplab import deeplab
from models.deeplabv3 import deeplabv3plus
from models.hrnet import hrnet18, hrnet32, hrnet48
| 129 | 31.5 | 50 | 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/__init__.py | from models.backbone.resnet import * | 36 | 36 | 36 | 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/__init__.py | from datasets.bdd import *
from datasets.cityscapes import *
from datasets.synthia import *
from datasets.gta import *
from datasets.mapillary import *
from datasets.wilddash import *
from datasets.idd import * | 210 | 29.142857 | 33 | 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/parser.py | import argparse
import os
def base_parser():
parser = argparse.ArgumentParser()
parser.add_argument("--dataset-root", type=str, default=os.path.join(os.getcwd(), "datasets", "gta"))
parser.add_argument("--checkpoints-root", type=str, default=os.path.join(os.getcwd(), "checkpoints", "runs"))
parser.add_... | 3,512 | 72.1875 | 218 | 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/multi_env.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 14 09:54:26 2018
@author: edward
A class that can be used to implement many parallel environments
"""
import multiprocessing as mp
import numpy as np
try:
from gym.spaces.box import Box
from baselines.common.atari_wrappers import make_atar... | 6,831 | 28.704348 | 98 | py |
drlviz | drlviz-master/arguments.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 14 10:37:33 2018
@author: edward
PongNoFrameskip-v4
"""
import argparse
def parse_game_args():
""" Defines the arguments used for both training and testing the network"""
parser = argparse.ArgumentParser(description='Parameters')
... | 6,390 | 70.808989 | 144 | 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/splitter.py | import ujson as ujson
def split_json(file):
fi = None
with open(file, "r") as f:
fi = ujson.load(f)
with open("data/"+file, "w") as ujson_file:
ujson.dump(fi["episode0"], ujson_file, indent=4)
if __name__ == '__main__':
split_json('health_gathering_supreme.json')
| 300 | 20.5 | 56 | py |
drlviz | drlviz-master/environments.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 8 11:03:06 2018
@author: edward
"""
from vizdoom import DoomGame, ScreenResolution, GameVariable, Button, AutomapMode
import numpy as np
from cv2 import resize
import cv2
class DoomEnvironment():
"""
A wrapper class for the Doom Maze... | 12,227 | 34.239193 | 195 | 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 |
Halo-FDCA | Halo-FDCA-master/HaloFitting.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author: J.M. Boxelaar
Version: October 2020
'''
from astropy.coordinates import SkyCoord
import logging
import os
from datetime import datetime
import astropy.units as u
import numpy as np
import argparse
import FDCA
def str2bool(v):
if isinstance(v, bool):
... | 8,374 | 53.383117 | 231 | py |
Halo-FDCA | Halo-FDCA-master/FDCA/fdca_utils.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author: J.M. Boxelaar
'''
from __future__ import division
import sys
import time
import os
import logging
import pyregion
import numpy as np
import pandas as pd
from scipy.optimize import curve_fit
from scipy import ndimage
from skimage.measure import block_reduce
f... | 12,390 | 35.337243 | 118 | py |
Halo-FDCA | Halo-FDCA-master/FDCA/HaloObject.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author: J.M. Boxelaar
Version: 08 June 2020
'''
# Built in module imports
import sys
import os
import logging
import time
from multiprocessing import Pool
# Scipy, astropy, emcee imports
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot... | 20,320 | 43.85872 | 136 | py |
Halo-FDCA | Halo-FDCA-master/FDCA/plotting_fits.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author: J.M. Boxelaar
'''
import numpy as np
import astropy.units as u
import sys
import scipy.stats as stats
from astropy.coordinates import SkyCoord
import matplotlib.pyplot as plt
import os
#import aplpy
from scipy.optimize import curve_fit
import matplotlib.color... | 13,664 | 41.306502 | 152 | py |
Halo-FDCA | Halo-FDCA-master/FDCA/markov_chain_monte_carlo.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author: J.M. Boxelaar
Version: 08 June 2020
'''
from __future__ import division
import sys
import os
import logging
from multiprocessing import Pool, cpu_count, freeze_support, set_start_method
import numpy as np
import pandas as pd
from scipy.optimize import curve_... | 44,842 | 43.050098 | 142 | py |
Halo-FDCA | Halo-FDCA-master/FDCA/__init__.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author: J.M. Boxelaar
Version: 13 October 2020
'''
import logging
import sys, os
import logging.config
import logging.handlers
from . import HaloObject
from . import markov_chain_monte_carlo
from . import fdca_utils as utils
#from . import plotting_fits
__version__ ... | 866 | 28.896552 | 85 | py |
Halo-FDCA | Halo-FDCA-master/FDCA/.ipynb_checkpoints/__init__-checkpoint.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author: J.M. Boxelaar
Version: 13 October 2020
'''
import logging
import sys, os
import logging.config
import logging.handlers
from . import HaloObject
from . import markov_chain_monte_carlo
from . import fdca_utils as utils
#from . import plotting_fits
__version__ ... | 866 | 28.896552 | 85 | py |
Halo-FDCA | Halo-FDCA-master/FDCA/.ipynb_checkpoints/HaloObject-checkpoint.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author: J.M. Boxelaar
Version: 08 June 2020
'''
# Built in module imports
import sys
import os
import logging
import time
from multiprocessing import Pool
# Scipy, astropy, emcee imports
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot... | 20,320 | 43.85872 | 136 | py |
Halo-FDCA | Halo-FDCA-master/FDCA/.ipynb_checkpoints/markov_chain_monte_carlo-checkpoint.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author: J.M. Boxelaar
Version: 08 June 2020
'''
from __future__ import division
import sys
import os
import logging
from multiprocessing import Pool, cpu_count, freeze_support, set_start_method
import numpy as np
import pandas as pd
from scipy.optimize import curve_... | 44,842 | 43.050098 | 142 | py |
spyn-repr | spyn-repr-master/scopes.py | from collections import deque
from collections import defaultdict
from spn.linked.nodes import SumNode
from spn.linked.nodes import ProductNode
from spn.linked.nodes import CategoricalIndicatorNode
from spn.linked.layers import CategoricalIndicatorLayer
from spn.linked.layers import SumLayer
from spn.linked.layers im... | 1,122 | 22.893617 | 65 | py |
spyn-repr | spyn-repr-master/ocr_letters.py | import numpy
import matplotlib
import matplotlib.pyplot as pyplot
import pickle
import os
def load_ocr_letters_data_split_from_txt(data_path):
data = numpy.loadtxt(data_path, delimiter=' ')
x, y = data[:, :-1].astype(numpy.int32), data[:, -1].astype(numpy.int32)
print('Loaded dataset:\n\tx: {}\ty: {... | 2,250 | 27.858974 | 86 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.