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 |
|---|---|---|---|---|---|---|
harth-ml-experiments | harth-ml-experiments-main/experiments/traditional_machine_learning/src/models.py | import pickle
import sklearn.ensemble
import sklearn.svm
import sklearn.linear_model
import xgboost
from sklearn.pipeline import make_pipeline
class Model:
@classmethod
def create( cls, x, y, scale=False, **args ):
model = cls()
model.clf = model.build( **args )
if scale == 'standardize':
prin... | 2,495 | 25.273684 | 103 | py |
RRHF | RRHF-main/train_alpaca_prompt.py | # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
#
# 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/LIC... | 12,574 | 37.106061 | 171 | py |
RRHF | RRHF-main/apply_delta.py | """
From fastchat
Apply the delta weights on top of a base model.
Usage:
python apply_delta.py --base ~/model_weights/llama-7b --target ~/model_weights/wombat-7b --delta GanjinZero/wombat-7b-delta
"""
import argparse
import torch
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModelForCausalLM
def ... | 2,035 | 38.153846 | 123 | py |
RRHF | RRHF-main/train.py | # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
#
# 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/LIC... | 12,044 | 36.640625 | 171 | py |
RRHF | RRHF-main/single_sentence_inference.py | import transformers
from transformers import LlamaForCausalLM, LlamaTokenizer
import torch
from tqdm import trange
import json
import os
from train import smart_tokenizer_and_embedding_resize, DEFAULT_PAD_TOKEN, DEFAULT_EOS_TOKEN, DEFAULT_BOS_TOKEN, DEFAULT_UNK_TOKEN
path = **path_to_your_model**
device = "cuda:7"
mo... | 3,948 | 34.9 | 254 | py |
RRHF | RRHF-main/data_generation/response_gen.py | ## model is modified based on Alpaca train.py
import os
import argparse
import torch
import transformers
from transformers import GenerationConfig, LlamaForCausalLM, LlamaTokenizer
from torch.utils.data import Dataset, DataLoader
from dataclasses import dataclass
from typing import Dict, Sequence
import torch.distribut... | 9,855 | 37.054054 | 126 | py |
RRHF | RRHF-main/data_generation/scoring_responses.py | #### The code is modified from trlX
import json
import math
import os
import torch
from torch import nn
from transformers import AutoModelForCausalLM, AutoTokenizer
from tqdm import tqdm
def create_reward_fn():
reward_tokenizer = AutoTokenizer.from_pretrained("gpt2")
reward_tokenizer.pad_token = reward_tokeni... | 3,406 | 35.634409 | 114 | py |
DIALKI | DIALKI-main/train_reader.py | import collections
import json
import os
from typing import List
import time
import heapq
import argparse
import glob
import logging
import math
import numpy as np
import torch
import transformers as tfs
import config
from data_utils import data_collator, reader_dataset
from data_utils import utils as du
from data_ut... | 35,116 | 37.170652 | 90 | py |
DIALKI | DIALKI-main/models/reader.py | import logging
import torch
import torch.nn as nn
from torch import Tensor as T
from data_utils import utils as d_utils
from models import loss
from models import perturbation
from utils import model_utils
logger = logging.getLogger()
def _pad_to_len(seq: T, pad_id: int, max_len: int):
s_len = seq.size(0)
... | 28,105 | 36.375 | 169 | py |
DIALKI | DIALKI-main/models/hf_models.py | import logging
import torch
from torch import nn
import transformers as tfs
from transformers.models.bert import modeling_bert
logger = logging.getLogger(__name__)
class HFBertEncoder(modeling_bert.BertModel):
def __init__(self, config, coordinator_config, args):
modeling_bert.BertModel.__init__(self, ... | 5,877 | 38.986395 | 157 | py |
DIALKI | DIALKI-main/models/perturbation.py | # Copyright (c) Microsoft. All rights reserved.
import torch
import logging
from .loss import stable_kl
logger = logging.getLogger(__name__)
def generate_noise(embed, mask, epsilon=1e-5):
noise = embed.data.new(embed.size()).normal_(0, 1) * epsilon
noise.detach()
noise.requires_grad_()
return noise
... | 3,381 | 34.978723 | 126 | py |
DIALKI | DIALKI-main/models/loss.py | import torch
import torch.nn.functional as F
def stable_kl(logit, target, epsilon=1e-6, reduce=True):
logit = logit.view(-1, logit.size(-1)).float()
target = target.view(-1, target.size(-1)).float()
bs = logit.size(0)
p = F.log_softmax(logit, 1).exp()
y = F.log_softmax(target, 1).exp()
rp = -(... | 2,119 | 29.285714 | 98 | py |
DIALKI | DIALKI-main/utils/checkpoint.py | import os
import glob
import torch
import logging
import collections
from .dist_utils import is_local_master
logger = logging.getLogger()
CheckpointState = collections.namedtuple(
"CheckpointState",
[
"model_dict",
"optimizer_dict",
"scheduler_dict",
"amp_dict",
"offse... | 1,014 | 22.068182 | 65 | py |
DIALKI | DIALKI-main/utils/sampler.py | import math
from typing import Optional, Iterator
import torch
import torch.distributed as dist
from torch.utils.data import Sampler, Dataset
def get_length_grouped_indices(lengths, batch_size, mega_batch_mult=None, generator=None):
"""
Return a list of indices so that each slice of :obj:`batch_size` consecu... | 9,444 | 43.342723 | 119 | py |
DIALKI | DIALKI-main/utils/model_utils.py | import os
import logging
from typing import List
import torch
from torch import nn
from torch.optim.lr_scheduler import LambdaLR
from transformers.optimization import AdamW
logger = logging.getLogger()
def setup_for_distributed_mode(
model: nn.Module,
optimizer: torch.optim.Optimizer,
device: object,
... | 4,543 | 29.702703 | 99 | py |
DIALKI | DIALKI-main/utils/dist_utils.py | import pickle
import torch
import torch.distributed as dist
from utils import model_utils
def get_rank():
if not dist.is_available():
return -1
if not dist.is_initialized():
return -1
return dist.get_rank()
def get_world_size():
if not dist.is_available():
return 1
if no... | 4,794 | 30.546053 | 95 | py |
DIALKI | DIALKI-main/utils/options.py | import argparse
import logging
import os
import random
import socket
import numpy as np
import torch
from models import loss
from utils import dist_utils
logger = logging.getLogger()
def add_data_params(parser: argparse.ArgumentParser):
parser.add_argument(
'--do_lower_case',
action='store_true... | 13,519 | 28.455338 | 80 | py |
DIALKI | DIALKI-main/data_utils/data_collator.py | import collections
import torch
import numpy as np
import config
def _pad(target, fill_value, pad_len, dim=0):
if pad_len == 0:
return target
size = list(target.size())
size[dim] = pad_len
pad = torch.full(size, fill_value)
return torch.cat([target, pad], dim=dim)
class DataCollator:
... | 14,468 | 38.105405 | 88 | py |
DIALKI | DIALKI-main/data_utils/doc2dial_reader.py | import os
import sys
import math
import json
import pickle
import logging
import concurrent.futures
import numpy as np
from collections import defaultdict
from tqdm import tqdm
from typing import List
import torch
from .data_class import ReaderSample, ReaderPassage, SpanPrediction
from .utils import get_word_idxs
fr... | 11,090 | 35.725166 | 131 | py |
DIALKI | DIALKI-main/data_utils/data_class.py | import torch
import collections
from typing import List
class ReaderPassage:
"""
Container to collect and cache all Q&A passages related attributes before generating the reader input
"""
def __init__(
self,
id=None,
text: List[str] = None,
type: List[int] = None,
... | 2,753 | 27.102041 | 105 | py |
DIALKI | DIALKI-main/data_utils/reader_dataset.py | import glob
import logging
import os
import pickle
import torch
from utils import dist_utils
logger = logging.getLogger()
class ReaderDataset(torch.utils.data.Dataset):
def __init__(self, data_dir):
paths = glob.glob(os.path.join(data_dir, '*'))
if dist_utils.is_local_master():
log... | 867 | 21.842105 | 56 | py |
uncertainty_benchmarking | uncertainty_benchmarking-master/CFGP/deprecated/LBFGS.py | import torch
import numpy as np
import matplotlib.pyplot as plt
from functools import reduce
from copy import deepcopy
from torch.optim import Optimizer
#%% Helper Functions for L-BFGS
def is_legal(v):
"""
Checks that tensor is not NaN or Inf.
Inputs:
v (tensor): tensor to be checked
"""
l... | 42,114 | 38.286381 | 128 | py |
uncertainty_benchmarking | uncertainty_benchmarking-master/CFGP/deprecated/run_gp.py | '''
It turns out that we need multiple GPUs to do GP fitting (because of the cubic
memory requirements). And our current setup has multiple GPUs, but not inside
Jupyter. So we turn the things into a Python script and run it here.
'''
import gc
import pickle
import numpy as np
import torch
import gpytorch
from LBFGS im... | 6,510 | 37.755952 | 104 | py |
uncertainty_benchmarking | uncertainty_benchmarking-master/CFGP/Matern/LBFGS.py | import torch
import numpy as np
import matplotlib.pyplot as plt
from functools import reduce
from copy import deepcopy
from torch.optim import Optimizer
#%% Helper Functions for L-BFGS
def is_legal(v):
"""
Checks that tensor is not NaN or Inf.
Inputs:
v (tensor): tensor to be checked
"""
l... | 42,114 | 38.286381 | 128 | py |
uncertainty_benchmarking | uncertainty_benchmarking-master/CFGP/Matern/run_gp.py | '''
It turns out that we need multiple GPUs to do GP fitting (because of the cubic
memory requirements). And our current setup has multiple GPUs, but not inside
Jupyter. So we turn the things into a Python script and run it here.
'''
import gc
import pickle
import numpy as np
import torch
import gpytorch
from LBFGS im... | 6,493 | 37.654762 | 104 | py |
uncertainty_benchmarking | uncertainty_benchmarking-master/NN_ensemble/fit_ensembles.py | import pickle
import numpy as np
from sklearn.model_selection import KFold
import torch
from torch.optim import Adam
import skorch.callbacks.base
from skorch.callbacks import Checkpoint # needs skorch >= 0.4
from skorch.callbacks.lr_scheduler import LRScheduler
from skorch import NeuralNetRegressor
from cgcnn.model im... | 2,730 | 34.467532 | 90 | py |
uncertainty_benchmarking | uncertainty_benchmarking-master/BNN/data_pyro.py | from __future__ import print_function, division
import os
import csv
import re
import json
import functools
import random
import warnings
import torch
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.dataloader import default_collate
from torch.utils.data.sampler import SubsetR... | 18,658 | 40.372506 | 247 | py |
uncertainty_benchmarking | uncertainty_benchmarking-master/BNN/model_pyro.py | from __future__ import print_function, division
import torch
import torch.nn as nn
from data_pyro import collate_pool, MergeDataset
class ConvLayer(nn.Module):
"""
Convolutional operation on graphs
"""
def __init__(self, atom_fea_len, nbr_fea_len):
"""
Initialize ConvLayer.
P... | 7,109 | 38.065934 | 78 | py |
uncertainty_benchmarking | uncertainty_benchmarking-master/NN/fit_cgcnn_blocked.py | '''
This job takes longer than 4 hours, which is the time limit for Jupyter-GPU on
NERSC. So we use this Python script to do the fitting in a SLURM job instead.
'''
import pickle
import numpy as np
import torch
from torch.optim import Adam
from skorch import callbacks # needs skorch >= 0.4
from skorch import NeuralNe... | 3,498 | 30.809091 | 99 | py |
uncertainty_benchmarking | uncertainty_benchmarking-master/GP/deprecated/RBF/LBFGS.py | import torch
import numpy as np
import matplotlib.pyplot as plt
from functools import reduce
from copy import deepcopy
from torch.optim import Optimizer
#%% Helper Functions for L-BFGS
def is_legal(v):
"""
Checks that tensor is not NaN or Inf.
Inputs:
v (tensor): tensor to be checked
"""
l... | 42,114 | 38.286381 | 128 | py |
uncertainty_benchmarking | uncertainty_benchmarking-master/GP/deprecated/RBF/run_gp.py | '''
It turns out that we need multiple GPUs to do GP fitting (because of the cubic
memory requirements). And our current setup has multiple GPUs, but not inside
Jupyter. So we turn the things into a Python script and run it here.
'''
import gc
import pickle
import numpy as np
from sklearn.preprocessing import Standard... | 6,606 | 37.637427 | 105 | py |
uncertainty_benchmarking | uncertainty_benchmarking-master/GP/Matern/LBFGS.py | import torch
import numpy as np
import matplotlib.pyplot as plt
from functools import reduce
from copy import deepcopy
from torch.optim import Optimizer
#%% Helper Functions for L-BFGS
def is_legal(v):
"""
Checks that tensor is not NaN or Inf.
Inputs:
v (tensor): tensor to be checked
"""
l... | 42,114 | 38.286381 | 128 | py |
uncertainty_benchmarking | uncertainty_benchmarking-master/GP/Matern/run_gp.py | '''
It turns out that we need multiple GPUs to do GP fitting (because of the cubic
memory requirements). And our current setup has multiple GPUs, but not inside
Jupyter. So we turn the things into a Python script and run it here.
'''
import gc
import pickle
import numpy as np
from sklearn.preprocessing import Standard... | 6,609 | 37.654971 | 105 | py |
CCSL | CCSL-main/main.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from pytz import timezone
from datetime import datetime
import numpy as np
import torch
from data_loader.synthetic_dataset import SyntheticDataset
from data_loader.real_dataset import RealDataset
from models.Causal_CCSL import Causal_CCSL
from trainers.tra... | 4,900 | 38.524194 | 233 | py |
CCSL | CCSL-main/data_loader/synthetic_dataset.py | import logging
import numpy as np
import os,sys
sys.path.append(os.getcwd())
from helpers.torch_utils import set_seed
from helpers.analyze_utils import plot_timeseries
class SyntheticDataset(object):
"""
A Class for generating data.
"""
_logger = logging.getLogger(__name__)
def __init__(self, num... | 8,650 | 33.466135 | 201 | py |
CCSL | CCSL-main/helpers/config_utils.py | import sys
import yaml
import argparse
from helpers.torch_utils import get_device
def load_yaml_config(path, skip_lines=0):
with open(path, 'r') as infile:
for i in range(skip_lines):
# Skip some lines (e.g., namespace at the first line)
_ = infile.readline()
return yaml.s... | 4,026 | 32.558333 | 121 | py |
CCSL | CCSL-main/helpers/torch_utils.py | # -*- coding: utf-8 -*-
import numpy as np
import torch
import random
def is_cuda_available():
return torch.cuda.is_available()
def get_device(cuda_number=0):
"""cuda_number : set the number of CUDA, default 0"""
return torch.device('cpu')#('cuda:{}'.format(cuda_number) if torch.cuda.is_available() el... | 539 | 19 | 102 | py |
CCSL | CCSL-main/models/Causal_CCSL.py | import logging
import numpy as np
import torch
import os,sys
sys.path.append(os.getcwd())
from helpers.torch_utils import set_seed
class Causal_CCSL(object):
_logger = logging.getLogger(__name__)
def __init__(self, num_samples, num_variables, max_lag, device ,prior_mu, prior_sigma, prior_nu, prior_omega):
... | 2,406 | 31.093333 | 123 | py |
CCSL | CCSL-main/trainers/trainer.py | import logging
import numpy as np
import copy
import torch
from itertools import chain
from torch import optim
from torch.distributions import Normal,Categorical
from torch.nn.utils import clip_grad_value_
from helpers.analyze_utils import plot_losses, AUC_score
class Trainer(object):
"""
"""
_logger = ... | 21,356 | 38.187156 | 203 | py |
LCaaS | LCaaS-master/Lib/site-packages/werkzeug/testapp.py | # -*- coding: utf-8 -*-
"""
werkzeug.testapp
~~~~~~~~~~~~~~~~
Provide a small test application that can be used to test a WSGI server
and check it for WSGI compliance.
:copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
impo... | 9,396 | 39.679654 | 83 | py |
FiMDP | FiMDP-master/docs/source/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | 5,599 | 27.865979 | 79 | py |
Noise2Fast | Noise2Fast-main/N2F_4D.py | #Copyright 2021, Jason Lequyer and Laurence Pelletier, All rights reserved.
#Sinai Health SystemLunenfeld-Tanenbaum Research Institute
#600 University Avenue, Room 1070
#Toronto, ON, M5G 1X5, Canada
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import os
from tifffile im... | 8,651 | 35.817021 | 110 | py |
Noise2Fast | Noise2Fast-main/DIP.py | import time
from pathlib import Path
import os
#os.environ['CUDA_VISIBLE_DEVICES'] = '3'
import numpy as np
import torch
import torch.optim
from torch.optim import Adam
from torch.nn import MSELoss
import torch.nn as nn
import sys
from tifffile import imread, imwrite
if __name__ == "__main__":
folder = sys.arg... | 18,212 | 34.365049 | 148 | py |
Noise2Fast | Noise2Fast-main/Ne2Ne.py | import argparse
import os
from torch.utils.data import Dataset
import numpy as np
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import fnmatch
import sys
from tifffile import imread, imwrite
from pathlib import Path
from collections import OrderedDict
import torch.nn.... | 11,915 | 38.852843 | 151 | py |
Noise2Fast | Noise2Fast-main/N2S.py | import sys
sys.path.append("..")
import numpy as np
import os
import torch
from tifffile import imread, imwrite
import torch.nn as nn
from torch.nn import MSELoss, L1Loss
from torch.optim import Adam
import time
from pathlib import Path
if __name__ == "__main__":
folder = sys.argv[1]
outfolder = folder+'_noi... | 6,440 | 34.98324 | 139 | py |
Noise2Fast | Noise2Fast-main/N2F.py | #Copyright 2021, Jason Lequyer and Laurence Pelletier, All rights reserved.
#Sinai Health SystemLunenfeld-Tanenbaum Research Institute
#600 University Avenue, Room 1070
#Toronto, ON, M5G 1X5, Canada
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import os
from tifffile im... | 7,408 | 33.300926 | 106 | py |
Noise2Fast | Noise2Fast-main/PatchSimilarity/patchcompare.py | import torch
from torch import nn
from tifffile import imread, imwrite
import numpy as np
import sys
import torch.nn.functional as F
psize = 5
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
inimg = imread('just11/11.tif').astype(np.float32)
inimg2 = imread('just11/12.tif').astype(np.floa... | 5,210 | 25.723077 | 75 | py |
Noise2Fast | Noise2Fast-main/Modified Architectures/S2S/network/pconv_layer.py | from keras.utils import conv_utils
from keras import backend as K
from keras.engine import InputSpec
from keras.layers import Conv2D
class PConv2D(Conv2D):
def __init__(self, *args, n_channels=3, mono=False, **kwargs):
super().__init__(*args, **kwargs)
self.input_spec = [InputSpec(ndim=4), InputSp... | 5,653 | 38.263889 | 120 | py |
Noise2Fast | Noise2Fast-main/Modified Architectures/N2S/N2S_timed.py | import sys
sys.path.append("..")
import numpy as np
from skimage.measure import compare_psnr
import os
import torch
from tifffile import imread, imwrite
import torch.nn as nn
from torch.nn import MSELoss, L1Loss
from torch.optim import Adam
import time
from pathlib import Path
if __name__ == "__main__":
folder =... | 6,566 | 35.483333 | 139 | py |
Noise2Fast | Noise2Fast-main/Modified Architectures/N2S/N2S_timed_N2F.py | import sys
sys.path.append("..")
import numpy as np
from skimage.measure import compare_psnr
import os
import torch
from tifffile import imread, imwrite
import torch.nn as nn
from torch.nn import MSELoss, L1Loss
from torch.optim import Adam
import time
from pathlib import Path
import torch.nn.functional as F
if __na... | 6,577 | 32.907216 | 103 | py |
Noise2Fast | Noise2Fast-main/N2F+DIP/N2FDIP.py |
#Copyright 2021, Jason Lequyer and Laurence Pelletier, All rights reserved.
#Sinai Health SystemLunenfeld-Tanenbaum Research Institute
#600 University Avenue, Room 1070
#Toronto, ON, M5G 1X5, Canada
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import os
from tifffil... | 8,428 | 31.295019 | 76 | py |
Noise2Fast | Noise2Fast-main/N2F+DIP/N2FDIPGT.py |
#Copyright 2021, Jason Lequyer and Laurence Pelletier, All rights reserved.
#Sinai Health SystemLunenfeld-Tanenbaum Research Institute
#600 University Avenue, Room 1070
#Toronto, ON, M5G 1X5, Canada
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import os
from tifffil... | 8,413 | 31.237548 | 76 | py |
sftrackpp | sftrackpp-main/pi.py | import torch
from torch import nn
MARGIN_MIN = 0.05
MARGIN_MAX = 0.05
EPSILON = 0.0001
def filt2D_batch(conv_filter, matrix):
return conv_filter(matrix[:, None])[:, 0]
def filt3D_batch(conv_filter, matrix):
return conv_filter(matrix)
def gauss_3D(kernel_size):
gauss_kernel = torch.zeros(kernel_size)... | 3,551 | 28.6 | 79 | py |
sftrackpp | sftrackpp-main/phase1.py | import os
import sys
import torch
from torch import nn, optim
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import DataLoader
from tqdm import tqdm
# our code
from datasets import davis17
from models.unet_model import UNetMedium
sys.path.append(os.path.dirname(os.path.dirname(os.path.r... | 3,991 | 30.1875 | 77 | py |
sftrackpp | sftrackpp-main/phase2.py | import os
import sys
import numpy as np
import torch
from torch import nn, optim
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import DataLoader
from tqdm import tqdm
# our code
import pi
from datasets import davis17
from models.unet_model import UNetMedium, UNetSmall
sys.path.append(o... | 6,754 | 35.122995 | 79 | py |
sftrackpp | sftrackpp-main/phase3-train.py | import os
import sys
import torch
from torch import nn, optim
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import DataLoader
from tqdm import tqdm
# our code
import pi
from datasets import (got10kdataset, lasotdataset, nfsdataset, otbdataset,
trackingnetdataset, u... | 9,639 | 33.676259 | 79 | py |
sftrackpp | sftrackpp-main/phase3-train-multi-iters.py | import os
import sys
import time
import numpy as np
import torch
from PIL import Image
from torch import nn, optim
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import DataLoader
from tqdm import tqdm
# our code
import pi
from datasets import (got10kdataset, lasotdataset, nfsdataset, ot... | 10,218 | 32.950166 | 79 | py |
sftrackpp | sftrackpp-main/models/unet_model.py | """ Full assembly of the parts to form the complete network """
import torch.nn.functional as F
from .unet_parts import *
def get_unet(model_type, n_channels, n_classes, from_exp, to_exp):
assert (model_type in [0, 1, 2])
if model_type == 0:
return UNetSmall(n_channels=n_channels,
... | 5,161 | 33.644295 | 78 | py |
sftrackpp | sftrackpp-main/models/unet_parts.py | """ Parts of the U-Net model """
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,
mid_channels=None,
with_dr... | 3,663 | 35.64 | 122 | py |
sftrackpp | sftrackpp-main/preprocess_db/main_tracking.py | import os
import random
import sys
import numpy as np
from torch.utils.data import DataLoader
from tqdm import tqdm
# from our project
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from datasets import (got10kdataset, lasotdataset, nfsdataset, otbdataset,
tracking... | 7,730 | 35.63981 | 107 | py |
sftrackpp | sftrackpp-main/preprocess_db/main_davis17.py | import glob
import os
import sys
import numpy as np
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
# from our project
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from datasets import davis17
from utils import utils
RAW_DATA_PATH = "/data/saliency/davis2017"
... | 8,549 | 37.340807 | 129 | py |
sftrackpp | sftrackpp-main/datasets/davis17.py | import glob
import os
import random
import sys
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
# from our project
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from utils import utils
PREPROC_PATH = "/data/sftrack-preprocessed/datasets/davis2017/full_size... | 13,086 | 39.391975 | 91 | py |
sftrackpp | sftrackpp-main/datasets/dataset.py | import random
import time
import numpy as np
from skimage.transform import resize
from torch.utils.data import Dataset
from utils import utils
class TestDatasetWrapper(Dataset):
def __init__(self,
dataset,
trackers,
dataset_part=5,
start_idx=0,
... | 6,920 | 35.619048 | 81 | py |
sftrackpp | sftrackpp-main/utils/utils.py | import math
import os
import jpeg4py
import numpy as np
import pi
import torch
from PIL import Image
from skimage.measure import regionprops
FRAME_W, FRAME_H = 854, 480
def jpeg4py_loader(path):
""" Image reading using jpeg4py https://github.com/ajkxyz/jpeg4py"""
try:
return jpeg4py.JPEG(path).decod... | 9,058 | 31.586331 | 80 | py |
mclf | mclf-master/docs/conf.py | # -*- coding: utf-8 -*-
#
# MCLF documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 8 22:41:05 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... | 11,735 | 30.718919 | 252 | py |
ODNL | ODNL-master/test.py | import numpy as np
import os
import argparse
import torch
import torch.backends.cudnn as cudnn
import torchvision.transforms as trn
from models.utils import build_model
from datasets.utils import build_dataset, build_ood_noise
from common.ood_tools import get_ood_scores
if __package__ is None:
import sys
from... | 7,408 | 43.10119 | 118 | py |
ODNL | ODNL-master/train.py | # -*- coding: utf-8 -*-
import numpy as np
import os
import argparse
import time
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torchvision.transforms as trn
import torchvision.datasets as dset
import torch.nn.functional as F
from tqdm import tqdm
from models.wrn import WideResNet
from d... | 7,020 | 36.545455 | 152 | py |
ODNL | ODNL-master/common/ood_tools.py | import torch
import numpy as np
import torch.nn.functional as F
def get_ood_scores(args, net, loader, ood_num_examples, device, in_dist=False):
_score = []
_right_score = []
_wrong_score = []
concat = lambda x: np.concatenate(x, axis=0)
to_np = lambda x: x.data.cpu().numpy()
with torch.no_gr... | 1,907 | 38.75 | 112 | py |
ODNL | ODNL-master/common/utils.py | import numpy as np
def cosine_annealing(step, total_steps, lr_max, lr_min):
return lr_min + (lr_max - lr_min) * 0.5 * (
1 + np.cos(step / total_steps * np.pi))
import os
import os.path
import copy
import hashlib
import errno
import numpy as np
from numpy.testing import assert_array_almost_equal
impor... | 11,478 | 27.273399 | 93 | py |
ODNL | ODNL-master/common/loss_function.py | import torch.nn as nn
import torch
def gce_loss(outputs, labels):
q = 0.7
k = 10
soft_max = nn.Softmax(dim=1)
sm_outputs = soft_max(outputs)
label_one_hot = nn.functional.one_hot(labels, k).float().cuda()
sm_out = torch.pow((sm_outputs * label_one_hot).sum(dim=1), q)
target = torch.ones_lik... | 423 | 29.285714 | 67 | py |
ODNL | ODNL-master/models/resnet.py | import torch
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)
... | 3,927 | 34.387387 | 102 | py |
ODNL | ODNL-master/models/utils.py | from models.wrn import WideResNet
import torch
def build_model(model_type, num_classes, device, args):
if model_type == "wrn":
net = WideResNet(args.layers, num_classes, args.widen_factor, dropRate=args.droprate)
elif model_type == "resnet":
from models.resnet import ResNet34
net = ResN... | 553 | 38.571429 | 93 | py |
ODNL | ODNL-master/models/wrn.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... | 3,908 | 39.298969 | 116 | py |
ODNL | ODNL-master/algorithms/base_framework.py |
import abc, os
from models.utils import build_model
import torch
import torch.nn.functional as F
class SingleModel:
__metaclass__ = abc.ABCMeta
def __init__(self, args, device, num_classes, train_loader):
self.device = device
self.args = args
self.num_classes = num_classes
# Cr... | 2,008 | 33.050847 | 104 | py |
ODNL | ODNL-master/algorithms/standard.py | from algorithms.base_framework import SingleModel
import torch.nn.functional as F
class Standard(SingleModel):
def train_batch(self, index, inputs, targets, epoch):
inputs, targets = inputs.to(self.device), targets.to(self.device)
logits = self.net(inputs)
loss = F.cross_entropy(logits, ta... | 348 | 28.083333 | 73 | py |
ODNL | ODNL-master/algorithms/odnl.py | from algorithms.base_framework import SingleModel
import torch.nn.functional as F
import torch
import numpy as np
import torch.nn as nn
from torch.autograd import Variable
from datasets.utils import build_dataset, build_ood_noise
class ODNL(SingleModel):
def __init__(self, args, device, num_classes, train_loader)... | 1,953 | 39.708333 | 149 | py |
ODNL | ODNL-master/datasets/random_images_300.py | import numpy as np
import torch
from bisect import bisect_left
import random
class RandomImages(torch.utils.data.Dataset):
def __init__(self, transform=None, exclude_cifar=True, data_num=50000):
self.transform = transform
self.data = np.load('./data/300K_random_images.npy').astype(np.uint8)
... | 776 | 25.793103 | 77 | py |
ODNL | ODNL-master/datasets/svhn_loader.py | import torch.utils.data as data
from PIL import Image
import os
import os.path
import numpy as np
class SVHN(data.Dataset):
url = ""
filename = ""
file_md5 = ""
split_list = {
'train': ["http://ufldl.stanford.edu/housenumbers/train_32x32.mat",
"train_32x32.mat", "e26dedcc434... | 5,121 | 40.306452 | 92 | py |
ODNL | ODNL-master/datasets/utils.py | import torchvision.transforms as trn
import torchvision.datasets as dset
from datasets.cifar import CIFAR10, CIFAR100
import datasets.svhn_loader as svhn
import torch
import numpy as np
from skimage.filters import gaussian as gblur
def build_dataset(args, dataset, mode="train", data_num=50000, origin_dataset=None):
... | 6,192 | 46.274809 | 111 | py |
ODNL | ODNL-master/datasets/validation_dataset.py | import torch
import numpy as np
class PartialDataset(torch.utils.data.Dataset):
def __init__(self, parent_ds, offset, length):
self.parent_ds = parent_ds
self.offset = offset
self.length = length
assert len(parent_ds) >= offset + length, Exception("Parent Dataset not long enough")
... | 2,610 | 34.283784 | 113 | py |
ODNL | ODNL-master/datasets/tools.py | import numpy as np
import random
import torch
from PIL import Image
from math import inf
import torch.nn.functional as F
import torch.nn as nn
def load_image(idx):
data_file = open('./data/tiny_images.bin', "rb")
data_file.seek(idx * 3072)
data = data_file.read(3072)
return np.fromstring(data, dtype=... | 1,963 | 30.174603 | 91 | py |
ODNL | ODNL-master/datasets/cifar.py | from __future__ import print_function
from PIL import Image
import os
import os.path
import numpy as np
import sys, json
if sys.version_info[0] == 2:
import cPickle as pickle
else:
import pickle
import random
import torch.utils.data as data
import torch
from datasets.tools import DependentLabelGenerator
from ... | 19,521 | 45.480952 | 163 | py |
DIVA-DAF | DIVA-DAF-main/playground.py | import warnings
from datetime import datetime
from pathlib import Path
import pytorch_lightning
import torch
import torchmetrics
from pytorch_lightning import Trainer
from pytorch_lightning.loggers import WandbLogger
from torchvision.models.segmentation import fcn_resnet50
from src.callbacks.model_callbacks import Sa... | 7,091 | 54.40625 | 168 | py |
DIVA-DAF | DIVA-DAF-main/tools/summary_models.py | import torch
from torch.nn import Identity
from torchinfo import summary
from torchvision.models.segmentation import fcn_resnet50
from src.models.backbone_header_model import BackboneHeaderModel
from src.models.backbones import ResNet50
from src.models.backbones.unet import UNet
from src.models.headers.fully_connected... | 687 | 35.210526 | 77 | py |
DIVA-DAF | DIVA-DAF-main/tools/generate_cropped_dataset.py | """
Load a dataset of historic documents by specifying the folder where its located.
"""
import argparse
# Utils
import itertools
import logging
import math
from datetime import datetime
from pathlib import Path
from torchvision.datasets.folder import has_file_allowed_extension, pil_loader
from torchvision.transforms... | 13,604 | 38.780702 | 120 | py |
DIVA-DAF | DIVA-DAF-main/tools/generate_tiles_dataset.py | """
Load a dataset of historic documents by specifying the folder where its located.
"""
import argparse
# Utils
import itertools
import json
import logging
import random
import multiprocessing
from datetime import datetime
from pathlib import Path
import numpy as np
from PIL import Image
from torchvision.datasets.fo... | 14,010 | 43.479365 | 141 | py |
DIVA-DAF | DIVA-DAF-main/src/execute.py | import os
import shutil
import sys
from pathlib import Path
from typing import List, Optional
import hydra
import torch
import wandb
from hydra.core.hydra_config import HydraConfig
from hydra.utils import to_absolute_path
from omegaconf import DictConfig, OmegaConf
from pytorch_lightning import LightningModule, Lightn... | 13,426 | 39.200599 | 119 | py |
DIVA-DAF | DIVA-DAF-main/src/datamodules/base_datamodule.py | from typing import Optional
import pytorch_lightning as pl
import torch
from omegaconf import OmegaConf
from src.utils import utils
log = utils.get_logger(__name__)
class AbstractDatamodule(pl.LightningDataModule):
def __init__(self):
super().__init__()
self.num_classes = -1
self.class_... | 1,953 | 36.576923 | 108 | py |
DIVA-DAF | DIVA-DAF-main/src/datamodules/RolfFormat/datamodule.py | from typing import Union, List, Optional
import torch
from torch.utils.data import DataLoader
from torchvision import transforms
from src.datamodules.RGB.utils.single_transform import IntegerEncoding
from src.datamodules.RolfFormat.datasets.dataset import DatasetRolfFormat, DatasetSpecs
from src.datamodules.RolfForma... | 10,907 | 46.220779 | 156 | py |
DIVA-DAF | DIVA-DAF-main/src/datamodules/RolfFormat/datasets/dataset.py | """
Load a dataset of historic documents by specifying the folder where its located.
"""
# Utils
import re
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import List, Tuple
import torch.utils.data as data
from torch import is_tensor
from torchvision.datasets.folder import pil_loader
fr... | 6,931 | 31.392523 | 109 | py |
DIVA-DAF | DIVA-DAF-main/src/datamodules/IndexedFormats/datamodule.py | from pathlib import Path
from typing import Union, List, Optional
import torch
from torch.utils.data import DataLoader
from torchvision import transforms
from src.datamodules.IndexedFormats.datasets.full_page_dataset import DatasetIndexed
from src.datamodules.IndexedFormats.utils.image_analytics import get_analytics
... | 8,937 | 48.10989 | 115 | py |
DIVA-DAF | DIVA-DAF-main/src/datamodules/IndexedFormats/datasets/full_page_dataset.py | """
Load a dataset of historic documents by specifying the folder where its located.
"""
# Utils
from pathlib import Path
from typing import List, Tuple, Union, Optional
import numpy as np
import torch
import torch.utils.data as data
from omegaconf import ListConfig
from torch import is_tensor
from torchvision.datase... | 6,746 | 35.080214 | 119 | py |
DIVA-DAF | DIVA-DAF-main/src/datamodules/RGB/datamodule.py | from pathlib import Path
from typing import Union, List, Optional
import torch
from torch.utils.data import DataLoader
from torchvision import transforms
from src.datamodules.RGB.datasets.full_page_dataset import DatasetRGB
from src.datamodules.RGB.utils.image_analytics import get_analytics
from src.datamodules.RGB.u... | 9,304 | 48.232804 | 114 | py |
DIVA-DAF | DIVA-DAF-main/src/datamodules/RGB/datamodule_cropped.py | from pathlib import Path
from typing import Union, List, Optional
import torch
from torch.utils.data import DataLoader
from torchvision import transforms
from src.datamodules.RGB.datasets.cropped_dataset import CroppedDatasetRGB
from src.datamodules.RGB.utils.image_analytics import get_analytics
from src.datamodules.... | 7,909 | 51.039474 | 115 | py |
DIVA-DAF | DIVA-DAF-main/src/datamodules/RGB/datasets/full_page_dataset.py | """
Load a dataset of historic documents by specifying the folder where its located.
"""
from dataclasses import dataclass
# Utils
from pathlib import Path
from typing import List, Tuple, Union, Optional
import torch.utils.data as data
from omegaconf import ListConfig
from torch import is_tensor
from torchvision.data... | 7,359 | 34.047619 | 119 | py |
DIVA-DAF | DIVA-DAF-main/src/datamodules/RGB/datasets/cropped_dataset.py | """
Load a dataset of historic documents by specifying the folder where its located.
"""
# Utils
import re
from pathlib import Path
from typing import List, Tuple, Union, Optional
import torch.utils.data as data
from omegaconf import ListConfig
from torch import is_tensor
from torchvision.datasets.folder import pil_l... | 7,655 | 35.28436 | 118 | py |
DIVA-DAF | DIVA-DAF-main/src/datamodules/RGB/utils/image_analytics.py | # Utils
import errno
import json
import logging
import os
from pathlib import Path
import numpy as np
# Torch related stuff
import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from PIL import Image
from torchvision.datasets.folder import pil_loader
from src.datamodules.uti... | 7,215 | 36.195876 | 113 | py |
DIVA-DAF | DIVA-DAF-main/src/datamodules/RGB/utils/functional.py | from typing import List
import torch
from torch.nn.functional import one_hot
def gt_to_int_encoding(matrix: torch.Tensor, class_encodings: torch.Tensor):
"""
Convert ground truth tensor or numpy matrix to one-hot encoded matrix
Parameters
-------
matrix: float tensor from to_tensor() or numpy ar... | 1,992 | 34.589286 | 109 | py |
DIVA-DAF | DIVA-DAF-main/src/datamodules/RotNet/datamodule_cropped.py | from pathlib import Path
from typing import Union, List, Optional
import numpy as np
import torch
from torch.utils.data import DataLoader
from torchvision import transforms
from src.datamodules.RotNet.utils.image_analytics import get_analytics_data
from src.datamodules.RotNet.datasets.cropped_dataset import CroppedRo... | 5,282 | 47.027273 | 116 | py |
DIVA-DAF | DIVA-DAF-main/src/datamodules/RotNet/datasets/cropped_dataset.py | """
Load a dataset of historic documents by specifying the folder where its located.
"""
# Utils
from pathlib import Path
from typing import List, Union, Optional
import torchvision.transforms.functional
from omegaconf import ListConfig
from torch import is_tensor
from torchvision.datasets.folder import has_file_allo... | 5,870 | 33.535294 | 120 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.