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 |
|---|---|---|---|---|---|---|
PMNet-PMNet | PMNet-PMNet/dataloaders/loader_radio.py | # https://github.com/RonLevie/RadioUNet
# This loader only contains the DPM simulations without cars for comparision with our model
from __future__ import print_function, division
import os
import torch
import pandas as pd
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.... | 5,604 | 34.700637 | 111 | py |
PMNet-PMNet | PMNet-PMNet/dataloaders/loader.py |
from __future__ import print_function, division
import os
import torch
import pandas as pd
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils, datasets, models
import warnings
warnings.filterwar... | 2,553 | 34.472222 | 164 | py |
zephyr | zephyr-main/samples/modules/tflite-micro/magic_wand/train/train.py | # Lint as: python3
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | 7,605 | 36.46798 | 100 | py |
zephyr | zephyr-main/samples/modules/tflite-micro/magic_wand/train/train_test.py | # Lint as: python3
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | 3,041 | 37.506329 | 81 | py |
bonet | bonet-main/mingpt/model_discrete_new.py | """
GPT model:
- the initial stem consists of a combination of token encoding and a positional encoding
- the meat of it is a uniform sequence of Transformer blocks
- each Transformer is a sequential combination of a 1-hidden-layer MLP block and a self-attention block
- all blocks feed into a central residual p... | 15,930 | 42.056757 | 178 | py |
bonet | bonet-main/mingpt/model_discrete.py | """
GPT model:
- the initial stem consists of a combination of token encoding and a positional encoding
- the meat of it is a uniform sequence of Transformer blocks
- each Transformer is a sequential combination of a 1-hidden-layer MLP block and a self-attention block
- all blocks feed into a central residual p... | 14,589 | 41.16763 | 178 | py |
bonet | bonet-main/mingpt/utils.py | import random
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def top_k_logits(logits, k):
v, ix = torch.topk(logits, k)
out = logits.c... | 2,206 | 40.641509 | 123 | py |
bonet | bonet-main/mingpt/model.py | """
GPT model:
- the initial stem consists of a combination of token encoding and a positional encoding
- the meat of it is a uniform sequence of Transformer blocks
- each Transformer is a sequential combination of a 1-hidden-layer MLP block and a self-attention block
- all blocks feed into a central residual p... | 28,092 | 44.165595 | 178 | py |
bonet | bonet-main/mingpt/trainer.py | """
Simple training loop; Boilerplate that could apply to any arbitrary neural network,
so nothing in this file really has anything to do with GPT specifically.
"""
import math
import logging
from tqdm import tqdm
import numpy as np
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import Lambda... | 5,980 | 41.41844 | 140 | py |
bonet | bonet-main/scripts/test_desbench.py | #!/usr/bin/env python3
import sys
import os
from pprint import pformat
from pprint import pprint
sys.path.append(os.path.join(os.getcwd()))
from utils.des_bench import DesignBenchFunctionWrapper
import logging
import torch
import math
import argparse
import pickle as pkl
import numpy as np
import torch.nn as nn
fr... | 11,801 | 38.471572 | 224 | py |
bonet | bonet-main/scripts/sorted_binning.py | #! /usr/bin/env python3
import sys
import os
sys.path.append(os.path.join(os.getcwd()))
from contextlib import contextmanager, redirect_stderr, redirect_stdout
import argparse
import matplotlib.pyplot as plt
import pickle as pkl
from mingpt.utils import set_seed
@contextmanager
def suppress_output():
"""
... | 8,491 | 28.901408 | 172 | py |
bonet | bonet-main/scripts/test_desbench_new.py | #!/usr/bin/env python3
import sys
import os
from pprint import pformat
from pprint import pprint
sys.path.append(os.path.join(os.getcwd()))
from utils.des_bench import DesignBenchFunctionWrapper
import logging
import torch
import math
import argparse
import pickle as pkl
import numpy as np
import torch.nn as nn
fr... | 11,749 | 38.56229 | 224 | py |
bonet | bonet-main/scripts/train_desbench.py | #!/usr/bin/env python3
import sys
import os
from pprint import pformat
from contextlib import contextmanager, redirect_stderr, redirect_stdout
sys.path.append(os.path.join(os.getcwd()))
from utils.des_bench import DesignBenchFunctionWrapper
@contextmanager
def suppress_output():
"""
A context manager tha... | 13,351 | 39.583587 | 254 | py |
bonet | bonet-main/scripts/train_desbench_new.py | #!/usr/bin/env python3
import sys
import os
from pprint import pformat
from contextlib import contextmanager, redirect_stderr, redirect_stdout
sys.path.append(os.path.join(os.getcwd()))
from utils.des_bench import DesignBenchFunctionWrapper
@contextmanager
def suppress_output():
"""
A context manager tha... | 13,171 | 39.404908 | 254 | py |
bonet | bonet-main/scripts/plot/plot_branin_2d.py | import torch
import sys
import os
from pprint import pformat
from pprint import pprint
import numpy as np
import pickle as pkl
import matplotlib.pyplot as plt
import seaborn as sns
sys.path.append(os.path.join(os.getcwd()))
from utils.functions import neg_branin
from matplotlib.colors import LogNorm, PowerNorm, Nor... | 3,087 | 32.565217 | 154 | py |
bonet | bonet-main/utils/functions.py | import torch
from botorch.test_functions.synthetic import Branin
def quadratic(bias):
return lambda x : -(x - bias) ** 2
def neg_branin(x):
return -Branin().evaluate_true(torch.Tensor(x))
def scaled_shifted_neg_branin(x, scale, shift):
assert scale > 0
branin = Branin()
x = torch.tensor(x)
s... | 400 | 21.277778 | 51 | py |
bonet | bonet-main/utils/loss.py | import math
import torch
import gpytorch
def compute_gram_matrix(x_1, x_2, length_scale=1.):
kernel = gpytorch.kernels.RBFKernel(length_scale=length_scale)
return kernel(x_1, x_2)
def ucb_loss(preds, target_x, target_y, b=0.1, length_scale=1.):
"""
preds: (batch, block_size, dim)
target_x: (batch... | 1,514 | 29.918367 | 105 | py |
bonet | bonet-main/utils/utils.py | import logging
import torch
import os
import pickle as pkl
import numpy as np
from attrdict import AttrDict
# from .plot import plot_simple_regret
def cumargmin(array):
assert len(array.shape) == 1
ret = []
m = float('inf')
m_idx = -1
for i in range(array.shape[0]):
if array[i] < m:
... | 3,319 | 25.99187 | 97 | py |
bonet | bonet-main/utils/des_bench.py | import sys
import os
from contextlib import contextmanager, redirect_stderr, redirect_stdout
@contextmanager
def suppress_output():
"""
A context manager that redirects stdout and stderr to devnull
https://stackoverflow.com/a/52442331
"""
with open(os.devnull, 'w') as fnull:
with re... | 5,242 | 35.664336 | 124 | py |
bonet | bonet-main/utils/plot.py | from matplotlib import pyplot as plt
import numpy as np
import torch
from utils.utils import cumargmin
def plot_simple_regret(**kwargs):
"""
Takes a sequence of pointwise regrets as input
regrets --> k x n array or n array, k is number of runs
"""
f, ax = plt.subplots(1, 1, figsize=(6, 4))
f... | 2,080 | 32.031746 | 112 | py |
bonet | bonet-main/utils/gp_fit.py | import torch
import gpytorch
import botorch
import pickle as pkl
from gpytorch.mlls import ExactMarginalLogLikelihood
from botorch.models import SingleTaskGP
from botorch.fit import fit_gpytorch_model
def fit_gp_model(x, y, device='cpu'):
"""
Fit GP model to data (x, y) and return the surrogate GP model
"... | 1,299 | 28.545455 | 87 | py |
bonet | bonet-main/utils/forward.py | import sys
import os
import argparse
from tqdm import tqdm
from contextlib import contextmanager, redirect_stderr, redirect_stdout
@contextmanager
def suppress_output():
"""
A context manager that redirects stdout and stderr to devnull
https://stackoverflow.com/a/52442331
"""
with open(os.... | 6,759 | 35.149733 | 119 | py |
CEDual | CEDual-main/train.py | import os
from tensorboardX import SummaryWriter
from copy import deepcopy
from torch.nn.init import xavier_uniform_
import numpy as np
import random
from utils.data_loader import prepare_data_seq
from utils.common import *
torch.manual_seed(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark =... | 4,001 | 38.235294 | 132 | py |
CEDual | CEDual-main/Model/CEDual.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from Model.common_layer import EncoderLayer, DecoderLayer, MultiHeadAttention, Conv, PositionwiseFeedForward, LayerNorm , _gen_bias_mask ,_gen_timing_signal, share_embedding, LabelSmoothing, NoamOpt, _get_attn_subsequent_mask
import numpy as np
import m... | 17,443 | 46.018868 | 225 | py |
CEDual | CEDual-main/Model/common_layer.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.nn.init as I
import numpy as np
import math
import os
from utils import config
import pdb
# import pprint
from tqdm import tqdm
# pp = pprint.PrettyPrinter(indent=1)
import numpy as np
torch.manual_se... | 23,286 | 38.536503 | 115 | py |
CEDual | CEDual-main/utils/data_reader.py | import torch
import torch.utils.data as data
import random
import math
import os
import sys
import codecs
import csv
sys.path.append('/apdcephfs/share_916081/qtli/install/ft_local/EmpDG')
print(sys.path)
# import logging
from utils import config
import pickle
from tqdm import tqdm
import numpy as np
# import pprint
# p... | 15,417 | 43.17765 | 198 | py |
CEDual | CEDual-main/utils/data_loader.py | import torch
import torch.utils.data as data
import random
import math
import os
# import logging
from utils import config
import pickle
from tqdm import tqdm
# import pprint
import pdb
# pp = pprint.PrettyPrinter(indent=1)
import re
import ast
#from utils.nlp import normalize
import time
from collections import defau... | 12,602 | 43.850534 | 140 | py |
CEDual | CEDual-main/utils/config.py | import os
# import logging
import argparse
import torch
UNK_idx = 0
PAD_idx = 1
EOS_idx = 2
SOS_idx = 3
USR_idx = 4 # speak state
SYS_idx = 5 # listener state
CLS_idx = 6
LAB_idx = 7 # emotional state
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if (os.cpu_count() > 8):
USE_CUDA = Tru... | 5,568 | 32.957317 | 146 | py |
CEDual | CEDual-main/utils/common.py | from utils import config
import numpy as np
import pickle
import re
import json
import math
import pdb
import torch
import torch.nn as nn
from tqdm import tqdm
import nltk
import torch.nn.functional as F
# from nltk.translate.bleu_score import sentence_bleu
from nltk.translate.bleu_score import SmoothingFunction
from u... | 27,339 | 39.146843 | 190 | py |
cytoset | cytoset-main/test.py | import os
import sys
import math
import time
import shutil
import pickle
import argparse
from tqdm import tqdm
import numpy as np
import torch
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from sklearn.utils import shuffle
from sklearn.metrics import roc_auc_score
... | 2,752 | 27.381443 | 114 | py |
cytoset | cytoset-main/utils.py | import os
import gc
import psutil
import numpy as np
import pandas as pd
import torch
import flowio
from sklearn.model_selection import StratifiedKFold
from sklearn.utils import shuffle
class EarlyStopping(object):
"""
Early stops the training if validation loss
doesn't improve after a given patience
... | 6,445 | 30.753695 | 94 | py |
cytoset | cytoset-main/model.py | import copy
import json
import yaml
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
logger = logging.getLogger(__name__)
## config class
class Config(object):
def __init__(self):
pass
@classmethod
def from_dict(cls, json_object):
"""Construct the config... | 5,749 | 29.42328 | 106 | py |
cytoset | cytoset-main/logger.py | # The source code for logger
import os
import sys
import json
import torch
import logging
from datetime import datetime
from typing import (
Optional, Dict, TextIO, List
)
from collections import OrderedDict
from numbers import Number
logger = logging.getLogger(__name__)
def make_dir(dirname):
if not os.pat... | 8,164 | 28.908425 | 84 | py |
cytoset | cytoset-main/data.py | from typing import List, Optional
import os
import argparse
import numpy as np
import pandas as pd
from sklearn.utils import shuffle
from sklearn.model_selection import StratifiedKFold
from torch.utils.data import Dataset
from utils import (
generate_subsets, combine_samples, loadFCS, ftrans
)
class CytoDatasetF... | 3,743 | 35.705882 | 118 | py |
cytoset | cytoset-main/train.py | import os
import sys
import gc
import math
import time
import shutil
import argparse
from tqdm import tqdm
import numpy as np
import pickle
import torch
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from sklearn.utils import shuffle
from sklearn.metrics import roc_... | 14,822 | 37.401554 | 135 | py |
TaskRes | TaskRes-main/train.py | import argparse
import torch
from dassl.utils import setup_logger, set_random_seed, collect_env_info
from dassl.config import get_cfg_default
from dassl.engine import build_trainer
# custom
import datasets.oxford_pets
import datasets.oxford_flowers
import datasets.fgvc_aircraft
import datasets.dtd
import datasets.eur... | 6,063 | 27.469484 | 99 | py |
TaskRes | TaskRes-main/clip/clip.py | import hashlib
import os
import urllib
import warnings
from typing import Union, List
import torch
from PIL import Image
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
from tqdm import tqdm
from .model import build_model
from .simple_tokenizer import SimpleTokenizer as _Tokenizer
... | 8,256 | 36.193694 | 142 | py |
TaskRes | TaskRes-main/clip/model.py | from collections import OrderedDict
from typing import Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1):
super().__init__()
# all conv layers have strid... | 19,815 | 39.606557 | 178 | py |
TaskRes | TaskRes-main/lpclip/feat_extractor.py | import os, argparse
import numpy as np
import torch
import sys
sys.path.append(os.path.abspath(".."))
from datasets.oxford_pets import OxfordPets
from datasets.oxford_flowers import OxfordFlowers
from datasets.fgvc_aircraft import FGVCAircraft
from datasets.dtd import DescribableTextures
from datasets.eurosat import ... | 6,080 | 31.005263 | 119 | py |
TaskRes | TaskRes-main/trainers/zsclip.py | from re import template
import torch
import torch.nn as nn
from dassl.engine import TRAINER_REGISTRY, TrainerX
from dassl.optim import build_optimizer, build_lr_scheduler
from clip import clip
from clip.model import convert_weights
from .taskres import load_clip_to_cpu
from .imagenet_templates import IMAGENET_TEMPLA... | 3,829 | 34.794393 | 95 | py |
TaskRes | TaskRes-main/trainers/taskres.py | '''
Task Residual Tuning
by Tao Yu (yutao666@mail.ustc.edu.cn)
Oct 4, 2022
'''
import os
import os.path as osp
from re import template
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.cuda.amp import GradScaler, autocast
from dassl.engine import TRAINER_REGISTRY, TrainerX
from dassl.... | 13,416 | 37.665706 | 118 | py |
TaskRes | TaskRes-main/trainers/imagenet_a_r_indexes_v2.py | import os
def find_imagenet_r_indexes():
imageneta_folders = ['goldfish', 'great white shark', 'hammerhead shark', 'stingray', 'hen', 'ostrich', 'goldfinch', 'junco', 'bald eagle', 'vulture', 'smooth newt', 'axolotl', 'tree frog', 'green iguana', 'chameleon', 'Indian cobra', 'scorpion', 'tarantula', 'centipede', '... | 35,368 | 1,963.944444 | 14,837 | py |
CAT-Net | CAT-Net-main/tools/infer.py | """
Created by Myung-Joon Kwon
mjkwon2021@gmail.com
June 7, 2021
"""
import sys, os
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')
if path not in sys.path:
sys.path.insert(0, path)
import argparse
import pprint
import shutil
import logging
import time
import timeit
from pathlib import P... | 5,641 | 35.166667 | 206 | py |
CAT-Net | CAT-Net-main/tools/train.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
"""
Modified by Myung-Joon Kwon
mjkwon2021@gmail.com
J... | 9,019 | 37.547009 | 203 | py |
CAT-Net | CAT-Net-main/Splicing/data/dataset_CASIA.py | """
Created by Myung-Joon Kwon
mjkwon2021@gmail.com
July 14, 2020
"""
import project_config
from Splicing.data.AbstractDataset import AbstractDataset
import os
import numpy as np
import random
from PIL import Image, ImageChops, ImageFilter
import torch
from pathlib import Path
class CASIA(AbstractDataset):
"""
... | 5,644 | 40.20438 | 119 | py |
CAT-Net | CAT-Net-main/Splicing/data/dataset_IMD2020.py | """
Created by Myung-Joon Kwon
mjkwon2021@gmail.com
July 12, 2020
"""
import project_config
from Splicing.data.AbstractDataset import AbstractDataset
import os
import numpy as np
import random
from PIL import Image
import torch
class IMD2020(AbstractDataset):
def __init__(self, crop_size, grid_crop, blocks: list... | 3,358 | 40.469136 | 170 | py |
CAT-Net | CAT-Net-main/Splicing/data/dataset_arbitrary.py | """
Created by Myung-Joon Kwon
mjkwon2021@gmail.com
Sep 10, 2020
"""
import project_config
from Splicing.data.AbstractDataset import AbstractDataset
import os
import numpy as np
import random
from PIL import Image
from pathlib import Path
import torch
from tqdm import tqdm
import glob
class arbitrary(AbstractDataset)... | 1,398 | 32.309524 | 116 | py |
CAT-Net | CAT-Net-main/Splicing/data/dataset_FantasticReality.py | """
Created by Myung-Joon Kwon
mjkwon2021@gmail.com
July 7, 2020
"""
import project_config
from Splicing.data.AbstractDataset import AbstractDataset
import os
import numpy as np
import random
from PIL import Image
import torch
import cv2
class FantasticReality(AbstractDataset):
def __init__(self, crop_size, grid... | 3,809 | 39.531915 | 174 | py |
CAT-Net | CAT-Net-main/Splicing/data/dataset_tampCOCO.py | """
Created by Myung-Joon Kwon
mjkwon2021@gmail.com
27 Jan 2021
Note: 'tampCOCO' includes four different custom datasets: cm_COCO, bcm_COCO, bcmc_COCO, sp_COCO
'bcm_COCO' is an alias of 'CM RAISE' in the paper.
'bcmc_COCO' is an alias of 'CM-JPEG RAISE' in the paper.
"""
import project_config
from Splicing.data.Abstra... | 1,942 | 33.696429 | 95 | py |
CAT-Net | CAT-Net-main/Splicing/data/AbstractDataset.py | """
Created by Myung-Joon Kwon
mjkwon2021@gmail.com
July 7, 2020
"""
from abc import ABC, abstractmethod
from PIL import Image, JpegImagePlugin
import numpy as np
import math
import jpegio # See https://github.com/dwgoon/jpegio/blob/master/examples/jpegio_tutorial.ipynb
import torch_dct as dct
import torch
import rand... | 9,281 | 41 | 125 | py |
CAT-Net | CAT-Net-main/Splicing/data/data_core.py | """
Created by Myung-Joon Kwon
mjkwon2021@gmail.com
July 8, 2020
"""
import torch
from torch.utils.data import Dataset
import random
from Splicing.data.dataset_FantasticReality import FantasticReality
from Splicing.data.dataset_IMD2020 import IMD2020
from Splicing.data.dataset_CASIA import CASIA
# from Splicing.data... | 6,440 | 51.365854 | 185 | py |
CAT-Net | CAT-Net-main/lib/core/function.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
"""
Modified by Myung-Joon Kwon
mjkwon2021@gmail.com
J... | 5,882 | 34.439759 | 123 | py |
CAT-Net | CAT-Net-main/lib/core/criterion.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
import torch
import torch.nn as nn
from torch.nn impo... | 2,385 | 40.137931 | 80 | py |
CAT-Net | CAT-Net-main/lib/models/network_CAT.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
"""
Modified by Myung-Joon Kwon
mjkwon2021@gmail.com
A... | 23,160 | 38.255932 | 112 | py |
CAT-Net | CAT-Net-main/lib/models/network_DCT_cls.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
"""
Mo... | 19,466 | 37.170588 | 131 | py |
CAT-Net | CAT-Net-main/lib/models/network_DCT.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
"""
Modified by Myung-Joon Kwon
mjkwon2021@gmail.com
A... | 18,273 | 37.390756 | 112 | py |
CAT-Net | CAT-Net-main/lib/models/sync_bn/inplace_abn/functions.py | from os import path
import torch.autograd as autograd
import torch.cuda.comm as comm
from torch.autograd.function import once_differentiable
from torch.utils.cpp_extension import load
_src_path = path.join(path.dirname(path.abspath(__file__)), "src")
_backend = load(name="inplace_abn",
extra_cflags=["... | 8,605 | 32.486381 | 104 | py |
CAT-Net | CAT-Net-main/lib/models/sync_bn/inplace_abn/bn.py | import os, sys
import torch
import torch.nn as nn
import torch.nn.functional as functional
try:
from queue import Queue
except ImportError:
from Queue import Queue
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, '../src'))
from functions i... | 6,947 | 37.815642 | 112 | py |
CAT-Net | CAT-Net-main/lib/utils/utils.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __future_... | 4,600 | 29.269737 | 80 | py |
CAT-Net | CAT-Net-main/lib/utils/modelsummary.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
from ... | 4,817 | 34.688889 | 120 | py |
CAT-Net | CAT-Net-main/lib/utils/metric.py | # Originally written by wkentaro
# https://github.com/wkentaro/pytorch-fcn/blob/master/torchfcn/utils.py
import numpy as np
import torch
def _fast_hist(label_true, label_pred, n_class):
mask = (label_true >= 0) & (label_true < n_class)
hist = np.bincount(
n_class * label_true[mask].astype(int) + labe... | 4,023 | 34.610619 | 90 | py |
deep-intake-detection | deep-intake-detection-master/oreba_cnn_lstm.py | """CNN-LSTM Model"""
import tensorflow as tf
import oreba_building_blocks
SCOPE = "oreba_cnn_lstm"
DEFAULT_DTYPE = tf.float32
CASTABLE_TYPES = (tf.float16,)
ALLOWED_TYPES = (DEFAULT_DTYPE,) + CASTABLE_TYPES
class Model(object):
"""Base class for building ConvLSTM network."""
def __init__(self, params):
... | 2,904 | 36.24359 | 89 | py |
deep-intake-detection | deep-intake-detection-master/resnet_slowfast.py | """ResNet-SlowFast Model
Based on github.com/tensorflow/models/blob/master/official/resnet
Adapted into SlowFast network as described by:
SlowFast Networks for Video Recognition
https://arxiv.org/pdf/1812.03982.pdf
by Christoph Feichtenhofer, Haoqi Fan, Jitendra Malik, Kaiming He
Adapted for frame sequences... | 8,131 | 50.468354 | 135 | py |
deep-intake-detection | deep-intake-detection-master/oreba_3d_cnn.py | """3D CNN Model"""
import tensorflow as tf
import oreba_building_blocks
SCOPE = "oreba_3d_cnn"
DEFAULT_DTYPE = tf.float32
CASTABLE_TYPES = (tf.float16,)
ALLOWED_TYPES = (DEFAULT_DTYPE,) + CASTABLE_TYPES
class Model(object):
"""Base class for building 3d convolutional network."""
def __init__(self, params)... | 2,288 | 33.681818 | 89 | py |
deep-intake-detection | deep-intake-detection-master/resnet_two_stream.py | """ResNet Two-Stream Model
Based on github.com/tensorflow/models/blob/master/official/resnet
"""
import tensorflow as tf
import resnet_building_blocks
SCOPE = "resnet_two_stream"
IMAGENET_SIZE = 224
DEFAULT_DTYPE = tf.float32
CASTABLE_TYPES = (tf.float16,)
ALLOWED_TYPES = (DEFAULT_DTYPE,) + CASTABLE_TYPES
class Mod... | 7,648 | 44.529762 | 100 | py |
deep-intake-detection | deep-intake-detection-master/resnet_cnn_lstm.py | """ResNet CNN-LSTM Model
Based on github.com/tensorflow/models/blob/master/official/resnet
"""
import tensorflow as tf
import resnet_building_blocks
SCOPE = "resnet_cnn_lstm"
IMAGENET_SIZE = 224
DEFAULT_DTYPE = tf.float32
CASTABLE_TYPES = (tf.float16,)
ALLOWED_TYPES = (DEFAULT_DTYPE,) + CASTABLE_TYPES
class Model(o... | 5,266 | 39.829457 | 89 | py |
deep-intake-detection | deep-intake-detection-master/resnet_2d_cnn.py | """ResNet 2D CNN Model"""
import tensorflow as tf
import resnet_building_blocks
SCOPE = "resnet_2d_cnn"
IMAGENET_SIZE = 224
DEFAULT_DTYPE = tf.float32
CASTABLE_TYPES = (tf.float16,)
ALLOWED_TYPES = (DEFAULT_DTYPE,) + CASTABLE_TYPES
class Model(object):
"""Base class for ResNet 2D CNN model."""
def __init_... | 4,267 | 40.038462 | 89 | py |
deep-intake-detection | deep-intake-detection-master/oreba_slowfast.py | """Small SlowFast Model"""
import tensorflow as tf
import oreba_building_blocks
SCOPE = "oreba_slowfast"
DEFAULT_DTYPE = tf.float32
CASTABLE_TYPES = (tf.float16,)
ALLOWED_TYPES = (DEFAULT_DTYPE,) + CASTABLE_TYPES
class Model(object):
"""Base class for building small slowfast network."""
def __init__(self,... | 6,879 | 43.387097 | 104 | py |
deep-intake-detection | deep-intake-detection-master/oreba_two_stream.py | """TwoStream Model"""
import tensorflow as tf
import oreba_building_blocks
SCOPE = "oreba_two_stream"
DEFAULT_DTYPE = tf.float32
CASTABLE_TYPES = (tf.float16,)
ALLOWED_TYPES = (DEFAULT_DTYPE,) + CASTABLE_TYPES
class Model(object):
"""Base class for building TwoStream network."""
def __init__(self, params)... | 4,198 | 40.574257 | 100 | py |
deep-intake-detection | deep-intake-detection-master/oreba_2d_cnn.py | """2D CNN Model"""
import tensorflow as tf
import oreba_building_blocks
SCOPE = "oreba_2d_cnn"
DEFAULT_DTYPE = tf.float32
CASTABLE_TYPES = (tf.float16,)
ALLOWED_TYPES = (DEFAULT_DTYPE,) + CASTABLE_TYPES
class Model(object):
"""Base class for building 2d convolutional network."""
def __init__(self, params)... | 2,312 | 33.522388 | 89 | py |
deep-intake-detection | deep-intake-detection-master/resnet_3d_cnn.py | """ResNet 3D CNN Model
Based on github.com/tensorflow/models/blob/master/official/resnet
Adapted for frame sequences of shape [16, 128, 128, 3]
"""
import tensorflow as tf
import resnet_building_blocks
SCOPE = "resnet_3d_cnn"
DEFAULT_DTYPE = tf.float32
CASTABLE_TYPES = (tf.float16,)
ALLOWED_TYPES = (DEFAULT_DTYPE,) +... | 3,845 | 40.804348 | 130 | py |
deep-intake-detection | deep-intake-detection-master/oreba_building_blocks.py | """Building blocks for oreba models."""
import tensorflow as tf
def channels_axis(inputs, params):
"""Return the axis index which houses the channels."""
if params.data_format == 'channels_first':
axis = 1
else:
axis = len(inputs.get_shape()) - 1
return axis
def batch_norm(inputs, p... | 5,427 | 32.300613 | 76 | py |
deep-intake-detection | deep-intake-detection-master/resnet_building_blocks.py | """Building blocks for resnet models.
Based on github.com/tensorflow/models/blob/master/official/resnet"""
import tensorflow as tf
BATCH_NORM_DECAY = 0.997
BATCH_NORM_EPSILON = 1e-5
def channels_axis(inputs, data_format):
"""Return the axis index which houses the channels."""
if data_format == 'channels_fir... | 11,633 | 40.402135 | 96 | py |
deep-intake-detection | deep-intake-detection-master/oreba_main.py | """Runs a model on the OREBA dataset."""
import os
import math
import json
import tensorflow as tf
from tensorflow.python.platform import gfile
from absl import app
from absl import flags
from absl import logging
import run_loop
import oreba_2d_cnn
import resnet_2d_cnn
import oreba_3d_cnn
import resnet_3d_cnn
import o... | 24,351 | 39.927731 | 106 | py |
SparK | SparK-main/pretrain/main.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import datetime
import math
import sys
import time
from functools import partial
from typing import List
import torch
fro... | 8,766 | 44.661458 | 190 | py |
SparK | SparK-main/pretrain/sampler.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import random
import numpy as np
import torch
from torch.utils.data.sampler import Sampler
def worker_init_fn(worker_id... | 2,630 | 34.08 | 138 | py |
SparK | SparK-main/pretrain/encoder.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
from timm.models.layers import DropPath
_cur_active: torch.Tensor = None #... | 9,533 | 44.617225 | 182 | py |
SparK | SparK-main/pretrain/spark.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from pprint import pformat
from typing import List
import sys
import torch
import torch.nn as nn
from timm.models.layers ... | 9,049 | 47.395722 | 177 | py |
SparK | SparK-main/pretrain/decoder.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import math
from typing import List
import torch
import torch.nn as nn
from timm.models.layers import trunc_normal_
from... | 2,932 | 38.106667 | 158 | py |
SparK | SparK-main/pretrain/dist.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
from typing import List
from typing import Union
import sys
import torch
import torch.distributed as tdist
impo... | 3,041 | 24.563025 | 142 | py |
SparK | SparK-main/pretrain/models/custom.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
from typing import List
from timm.models.registry import register_model
class YourCon... | 3,472 | 37.588889 | 155 | py |
SparK | SparK-main/pretrain/models/resnet.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
import torch
import torch.nn.functional as F
from timm.models.resnet import ResNet
# hack: injec... | 2,597 | 29.564706 | 90 | py |
SparK | SparK-main/pretrain/models/__init__.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from timm import create_model
from timm.loss import SoftTargetCrossEntropy
from timm.models.layers import dro... | 2,010 | 31.967213 | 99 | py |
SparK | SparK-main/pretrain/models/convnext.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
# This file is basically a copy of: https://github.com/facebookresearch/ConvNeXt/blob/06f7b05f922e21914916406141f50f82b4a... | 4,994 | 38.642857 | 145 | py |
SparK | SparK-main/pretrain/utils/misc.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import datetime
import functools
import os
import subprocess
import sys
import time
from collections import defaultdict, d... | 12,052 | 33.83526 | 133 | py |
SparK | SparK-main/pretrain/utils/imagenet.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
from typing import Any, Callable, Optional, Tuple
import PIL.Image as PImage
from timm.data import IMAGENET_DEF... | 3,222 | 35.625 | 111 | py |
SparK | SparK-main/pretrain/utils/lamb.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
# This file is basically a copy to: https://github.com/rwightman/pytorch-image-models/blob/v0.5.4/timm/optim/lamb.py
# **... | 7,977 | 48.246914 | 129 | py |
SparK | SparK-main/downstream_mmdet/mmcv_custom/customized_text.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import datetime
from collections import OrderedDict
import torch
import mmcv
from mmcv.runner import HOOKS
from mmcv.r... | 4,939 | 36.709924 | 85 | py |
SparK | SparK-main/downstream_mmdet/mmcv_custom/runner/checkpoint.py | # Copyright (c) Open-MMLab. All rights reserved.
import os.path as osp
import time
from tempfile import TemporaryDirectory
import torch
from torch.optim import Optimizer
import mmcv
from mmcv.parallel import is_module_wrapper
from mmcv.runner.checkpoint import weights_to_cpu, get_state_dict
try:
import apex
exce... | 2,885 | 32.55814 | 77 | py |
SparK | SparK-main/downstream_mmdet/mmdet/models/backbones/convnext.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models.layers... | 7,434 | 40.077348 | 112 | py |
SparK | SparK-main/downstream_d2/lr_decay.py | from typing import List, Dict, Set, Optional, Callable, Any
import torch
import copy
from detectron2.solver.build import reduce_param_groups
def lr_factor_func(para_name: str, is_resnet50, dec: float, debug=False) -> float:
if dec == 0:
dec = 1.
N = 5 if is_resnet50 else 11
if '.stem.' in pa... | 5,554 | 40.766917 | 110 | py |
SparK | SparK-main/downstream_d2/convert-timm-to-d2.py | #!/usr/bin/python3
# Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import pickle as pkl
import torch
# we use `timm.models.ResNet` in pre-training, so keys are timm-s... | 1,680 | 37.204545 | 128 | py |
SparK | SparK-main/downstream_d2/train_net.py | #!/usr/bin/python3
# Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import datetime
import json
import logging
import os
import time
from collections import OrderedDict, ... | 12,832 | 38.73065 | 150 | py |
SparK | SparK-main/downstream_imagenet/main.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import datetime
import time
import torch
import torch.distributed as tdist
from timm.utils import ModelEmaV2
from torch.u... | 9,150 | 47.163158 | 187 | py |
SparK | SparK-main/downstream_imagenet/data.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
import random
import time
import PIL.Image as PImage
import numpy as np
import torch
import torchvision
from ti... | 6,223 | 39.947368 | 167 | py |
SparK | SparK-main/downstream_imagenet/mixup.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# This file is a modified version of timm.data.Mixup
# Fixed error of "Batch size should be even when using this"
""" Mix... | 7,502 | 43.39645 | 120 | py |
SparK | SparK-main/downstream_imagenet/util.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import datetime
import os
import sys
from functools import partial
from typing import List, Tuple, Callable
import pytz
i... | 6,223 | 46.151515 | 236 | py |
SparK | SparK-main/downstream_imagenet/models/__init__.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch
from timm.data import Mixup
from timm.loss import BinaryCrossEntropy, SoftTargetCrossEntropy
fro... | 3,455 | 31.914286 | 109 | py |
SparK | SparK-main/downstream_imagenet/models/convnext_official.py | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
# This file is exactly the same as: https://github.com/facebookresearch/ConvNeXt/blob/06f7b05f922e21914916406141f50f82b4a... | 9,511 | 46.089109 | 145 | py |
TransferLearningClassification | TransferLearningClassification-master/database/dataset_reader.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import glob
def num_per_epoche(mode, dataset):
if dataset == 'indoors67':
if mode == 'train':
return 5360
else:
return 1340
elif dataset... | 11,026 | 44.008163 | 115 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.