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 |
|---|---|---|---|---|---|---|
Weighted-Soft-Label-Distillation | Weighted-Soft-Label-Distillation-master/knowledge_distiller.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 2,946 | 33.267442 | 189 | py |
Weighted-Soft-Label-Distillation | Weighted-Soft-Label-Distillation-master/train_with_distillation.py | import gc
import os
import shutil
import time
import warnings
import torch
import torch.backends.cudnn as cudnn
import models.MobileNet as Mov
import models.ResNet as ResNet
from imagenet_train_cfg import cfg as config
from dataset import imagenet_data
from dataset.prefetch_data import data_prefetcher
from tools impo... | 8,304 | 30.819923 | 132 | py |
Weighted-Soft-Label-Distillation | Weighted-Soft-Label-Distillation-master/tools/utils.py | import numpy as np
import torch
import torch.nn as nn
def set_seed(seed):
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
def cross_entropy_with_label_smoothing(pred, target, label_smoothing=0.):
"""
Label smoothing implementation.
This function is taken from https:/... | 790 | 30.64 | 110 | py |
Weighted-Soft-Label-Distillation | Weighted-Soft-Label-Distillation-master/dataset/lmdb_dataset.py | import os
import cv2
import msgpack
import numpy as np
import torch.utils.data as data
from PIL import Image
from imagenet_train_cfg import cfg as config
import lmdb
class Datum(object):
def __init__(self, shape=None, image=None, label=None):
self.shape = shape
self.image = image
self.labe... | 4,877 | 35.954545 | 119 | py |
Weighted-Soft-Label-Distillation | Weighted-Soft-Label-Distillation-master/dataset/prefetch_data.py | import torch
import numpy as np
class data_prefetcher():
def __init__(self, loader, mean=None, std=None, is_cutout=False, cutout_length=16, is_sample=False):
self.is_sample = is_sample
self.loader = iter(loader)
self.stream = torch.cuda.Stream()
if mean is None:
self.mea... | 4,722 | 40.069565 | 110 | py |
Weighted-Soft-Label-Distillation | Weighted-Soft-Label-Distillation-master/dataset/imagenet_data.py | import os
import torch
import torchvision
import torchvision.transforms as transforms
from . import lmdb_dataset
from . import torchvision_extension as transforms_extension
from .prefetch_data import fast_collate
from imagenet_train_cfg import cfg as config
class ImageNet12(object):
def __init__(self, trainFolde... | 5,166 | 43.162393 | 118 | py |
Weighted-Soft-Label-Distillation | Weighted-Soft-Label-Distillation-master/dataset/torchvision_extension.py | import random
import torch
from torchvision.transforms import functional as F
# In this file some more transformations (apart from the ones defined in torchvision.transform)
# are added. Particularly helpful to train imagenet, and in the style of the transforms
# used by fb.resnet https://github.com/facebook/fb.resnet... | 1,753 | 34.08 | 97 | py |
Weighted-Soft-Label-Distillation | Weighted-Soft-Label-Distillation-master/models/ResNet.py | import torch
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch... | 8,577 | 29.635714 | 92 | py |
Weighted-Soft-Label-Distillation | Weighted-Soft-Label-Distillation-master/models/MobileNet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class MobileNet(nn.Module):
def __init__(self):
super(MobileNet, self).__init__()
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.Ba... | 2,518 | 27.625 | 74 | py |
weighted-removal | weighted-removal-main/wr_train.py | # encoding:utf-8
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader,random_split
from torch.optim import Adam
from torch.autograd import Variable
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from collectio... | 5,322 | 32.062112 | 140 | py |
weighted-removal | weighted-removal-main/evaluate.py | # encoding:utf-8
import argparse
import torch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
from transformers import AutoTokenizer, AutoModelWithLMHead
from transformers import *
from config_file import config
import sys
sys.path.append("..")
import tools.mod... | 8,824 | 39.113636 | 140 | py |
weighted-removal | weighted-removal-main/tools/loaddatasets.py | import pandas as pd
import torch
def load_datasets(bert_tokenizer, embedding, word_simi_train_file, word_simi_test_file, analogy_test_file, text_simi_test_file):
# word_simi
word_simi_train = pd.read_csv(word_simi_train_file)
word_simi_test = pd.read_csv(word_simi_test_file)
#save tensor in dataframe... | 4,483 | 34.872 | 128 | py |
weighted-removal | weighted-removal-main/tools/dataloaders.py | import torch
from torch.utils.data import Dataset, DataLoader,random_split
#dataloader
class Dataset_id2hot(Dataset):
def __init__(self, id1, id2, simi_label, E):
#dataloading
self.id1 = id1
self.id2 = id2
self.label = simi_label
self.E = E
def __getitem__(self... | 4,000 | 26.40411 | 96 | py |
weighted-removal | weighted-removal-main/tools/models.py | import torch
import torch.nn as nn
class BaseModel(nn.Module):
def __init__(self,emb_dimension,component_num):
super(BaseModel, self).__init__()
self.emb_dimension = emb_dimension
self.component_num = component_num
def __get_cosine_similar__(self, e1, e2):
#注意输入输出都需要是二维的,即必... | 1,667 | 37.790698 | 110 | py |
PVCGN | PVCGN-master/ggnn_evaluation_sh_top72_peak.py | import argparse
import yaml
import numpy as np
import torch
import pandas as pd
from lib import utils
from lib import metrics
from ggnn.multigraph import Net
from ggnn_train import _get_log_dir
from lib.utils import collate_wrapper
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Lo... | 9,220 | 28.366242 | 79 | py |
PVCGN | PVCGN-master/ggnn_utils.py | import torch
from torch_geometric.data import Batch, Data
class SimpleBatch(list):
def to(self, device):
for ele in self:
ele.to(device)
return self
def collate_wrapper(x, y, edge_index, edge_attr, device, return_y=True):
x = torch.tensor(x, dtype=torch.float, device=device)
... | 1,425 | 29.340426 | 91 | py |
PVCGN | PVCGN-master/ggnn_train.py | import random
import argparse
import time
import yaml
import numpy as np
import torch
import os
from torch import nn
from torch.nn.utils import clip_grad_norm_
from torch import optim
from torch.optim.lr_scheduler import MultiStepLR
from torch.nn.init import xavier_uniform_
from lib import utils
from lib import metric... | 13,265 | 33.367876 | 79 | py |
PVCGN | PVCGN-master/ggnn_evaluation.py | import argparse
import yaml
import numpy as np
import torch
from ggnn.multigraph import Net
from ggnn_train import evaluate
from lib import utils
from lib.utils import collate_wrapper
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
def read_cfg_file(filename):
with ope... | 3,391 | 29.836364 | 79 | py |
PVCGN | PVCGN-master/ggnn_evaluation_hz_top20_peak.py | import argparse
import yaml
import numpy as np
import torch
import pandas as pd
from lib import utils
from lib import metrics
from ggnn.multigraph import Net
from ggnn_train import _get_log_dir
from lib.utils import collate_wrapper
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Lo... | 8,804 | 32.60687 | 79 | py |
PVCGN | PVCGN-master/ggnn/rgcn.py | import torch
from torch.nn import Parameter as Param
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.inits import uniform
from torch.nn.init import xavier_normal_, calculate_gain
class RGCNConv(MessagePassing):
r"""The relational graph convolutional operator from the `"Modeling
Rel... | 3,796 | 36.97 | 79 | py |
PVCGN | PVCGN-master/ggnn/multigraph.py | from torch_geometric import nn as gnn
from torch import nn
from torch.nn import functional as F
from torch.nn import init, Parameter
import torch
import random
import math
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
from ggnn.rgcn import RGCNConv
class GCNSequential(nn.Sequential):
"""docstrin... | 16,330 | 36.629032 | 78 | py |
PVCGN | PVCGN-master/lib/utils.py | # part of this code are copied from DCRNN
import logging
import os
import pickle
import sys
import numpy as np
import torch
from torch_geometric.data import Batch, Data
class DataLoader(object):
def __init__(self,
xs,
ys,
xtime,
ytime,
... | 10,548 | 34.880952 | 112 | py |
BottleNetPlusPlus | BottleNetPlusPlus-master/BottleNet++_VGG16.py | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import transforms
from torchvision.utils import save_image
from compression_module import *
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import StratifiedShuffleSplit
impor... | 7,266 | 37.449735 | 271 | py |
BottleNetPlusPlus | BottleNetPlusPlus-master/BottleNet++_ResNet50.py | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import transforms
from torchvision.utils import save_image
from compression_module import *
import numpy as np
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-channel', type=str, ... | 8,914 | 38.100877 | 310 | py |
BottleNetPlusPlus | BottleNetPlusPlus-master/compression_module.py | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import transforms
from torchvision.utils import save_image
import numpy as np
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class BEC(torch.autograd.Function)... | 3,736 | 29.137097 | 98 | py |
BottleNetPlusPlus | BottleNetPlusPlus-master/models/resnet.py | import torch
import torch.nn as nn
class BasicBlock(nn.Module):
"""Basic Block for resnet
"""
expansion = 1
def __init__(self, in_channels, out_channels, stride=1):
super().__init__()
#residual function
self.residual_function = nn.Sequential(
nn.Conv2d(in_channe... | 5,207 | 33.490066 | 118 | py |
BottleNetPlusPlus | BottleNetPlusPlus-master/models/vgg.py | import torch
import torch.nn as nn
cfg = {
'A' : [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'B' : [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'D' : [64, 64, 'M', 128, 128, 'M', 256, 25... | 1,849 | 27.030303 | 114 | py |
mori-ran | mori-ran-main/src/main.py | import argparse
import torch
from experiments import CONAN
from models import MORIRAN
from config import get_cfg
from trainer import Trainer
from datatool import load_dataset
dataset = {
0: "Caltech101-20",
1: "Scene-15",
2: "LandUse-21",
3: "NoisyMNIST",
}
def parse_args():
parser = argparse.A... | 1,588 | 30.156863 | 130 | py |
mori-ran | mori-ran-main/src/losses.py | import torch
from torch import nn
class BarlowTwinsModule(nn.Module):
"""
References to: FAIR's barlowtwins.
"""
def __init__(self, args) -> None:
super().__init__()
self.args = args
# according to original paper 2048 -> 8192
self.projector_dim = args.hidden_dim * ... | 5,050 | 32.230263 | 88 | py |
mori-ran | mori-ran-main/src/utils.py | import sys
import numpy as np
import torch
from scipy.optimize import linear_sum_assignment
from sklearn import metrics
from sklearn.cluster import KMeans
from munkres import Munkres
def normalize(x):
"""Normalize"""
x = (x - np.min(x)) / (np.max(x) - np.min(x))
return x
def seed_everything(seed):
n... | 6,181 | 33.344444 | 95 | py |
mori-ran | mori-ran-main/src/networks.py | """
Network building tools.
------
Author: Guanzhou Ke.
Email: guanzhouk@gmail.com
Date: 2022/08/14
"""
import torch
from torch import nn
def build_mlp(layers, activation='relu', norm='batch'):
"""Build multiple linear perceptron
Args:
layers (list): The list of input and output dimension.
a... | 1,928 | 27.791045 | 89 | py |
mori-ran | mori-ran-main/src/vis_result.py | """
Visualization result.
------
Author: Guanzhou Ke.
Email: guanzhouk@gmail.com
Date: 2022/08/14
"""
import torch
import numpy as np
def calc_stats(history_path, task):
his = torch.load(history_path)
if task == 'clustering':
acc = []
nmi = []
ari = []
p = []
... | 1,868 | 33.611111 | 217 | py |
mori-ran | mori-ran-main/src/models.py | """
Model.
------
Author: Guanzhou Ke.
Email: guanzhouk@gmail.com
Date: 2022/08/14
"""
import math
import torch
from torch import nn
from torch.nn import init
from networks import build_mlp
from losses import BarlowTwinsModule, CategoryContrastiveModule
class MORIRAN(nn.Module):
"""MORIRAN
"""
def... | 6,404 | 31.025 | 118 | py |
mori-ran | mori-ran-main/src/datatool.py | """
Data preprocessing tools
------
Author: Guanzhou Ke.
Email: guanzhouk@gmail.com
Date: 2022/08/14
"""
import os
import random
import scipy.io as sio
from scipy import sparse
import numpy as np
import torch
from torch.utils.data import Dataset
import utils
DEFAULT_DATA_ROOT = './data'
PROCESSED_DATA_ROOT = os.p... | 8,428 | 33.125506 | 151 | py |
mori-ran | mori-ran-main/src/trainer.py | """
Model trainer.
------
Author: Guanzhou Ke.
Email: guanzhouk@gmail.com
Date: 2022/08/14
"""
import torch
from tqdm import tqdm
import numpy as np
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
from apex import amp
from utils import clustering_by_representation, seed_every... | 7,424 | 44.833333 | 130 | py |
mori-ran | mori-ran-main/src/optimizer.py | """
Optimizer.
------
Author: Guanzhou Ke.
Email: guanzhouk@gmail.com
Date: 2022/08/14
"""
import torch
class Optimizer:
def __init__(self, params, lr=1e-3, type='adam', schedule=True):
self.params = params
self.schedule = schedule
if type == 'sgd':
self._opt = torch.optim.SG... | 1,259 | 26.391304 | 100 | py |
mori-ran | mori-ran-main/src/experiments/conan.py | import math
from typing import Optional
from abc import ABC
import torch
from torch import nn
from torch.nn import init
from torch.nn import Parameter
from torch.nn import functional as F
from networks import build_mlp
class CONAN(nn.Module):
def __init__(self, args, device='cpu'):
super(CONAN, self).__... | 20,889 | 34.16835 | 114 | py |
solo | solo-master/solo/solo.py | #!/usr/bin/env python
import json
import os
import umap
import sys
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import pkg_resources
import numpy as np
from sklearn.metrics import *
from scipy.special import softmax
from scanpy import read_10x_mtx
import torch
from pytorch_lightning.callbacks.ea... | 16,739 | 32.017751 | 89 | py |
quimb | quimb-main/tests/test_tensor/test_tensor_2d_tebd.py | import itertools
import importlib
import pytest
import quimb as qu
import quimb.tensor as qtn
found_torch = importlib.util.find_spec('torch') is not None
pytorch_case = pytest.param(
'torch', marks=pytest.mark.skipif(
not found_torch, reason='pytorch not installed'))
class TestLocalHam2DConstruct:
... | 4,129 | 28.71223 | 77 | py |
quimb | quimb-main/tests/test_tensor/test_optimizers.py | import functools
import importlib
import pytest
import numpy as np
from numpy.testing import assert_allclose
from autoray import real
import opt_einsum as oe
import quimb as qu
import quimb.tensor as qtn
from quimb.tensor.optimize import Vectorizer, parse_network_to_backend
found_torch = importlib.util.find_spec('t... | 12,308 | 30.241117 | 78 | py |
quimb | quimb-main/quimb/tensor/decomp.py | """Functions for decomposing and projecting matrices.
"""
import functools
import operator
import numpy as np
import scipy.sparse.linalg as spla
import scipy.linalg.interpolative as sli
from autoray import (
astype,
backend_like,
compose,
dag,
do,
get_dtype_name,
get_lib_fn,
infer_back... | 32,610 | 26.730442 | 79 | py |
quimb | quimb-main/quimb/tensor/circuit.py | """Tools for quantum circuit simulation using tensor networks.
"""
import re
import math
import numbers
import operator
import functools
import itertools
import numpy as np
from autoray import do, reshape, backend_like
import quimb as qu
from ..utils import progbar as _progbar
from ..utils import oset, partitionby, ... | 99,042 | 32.918836 | 79 | py |
quimb | quimb-main/quimb/tensor/optimize.py | """Support for optimizing tensor networks using automatic differentiation to
automatically derive gradients for input to scipy optimizers.
"""
import re
import warnings
import functools
import importlib
from collections.abc import Iterable
import tqdm
import numpy as np
from autoray import to_numpy, astype, get_dtype_... | 53,854 | 29.582056 | 81 | py |
quimb | quimb-main/quimb/tensor/tensor_arbgeom_tebd.py | """Tools for performing TEBD like algorithms on arbitrary lattices.
"""
import random
import itertools
import collections
from autoray import do, to_numpy, dag
from ..core import eye, kron, qarray
from ..utils import ensure_dict
from ..utils import progbar as Progbar, default_to_neutral_style
from .tensor_core impor... | 22,973 | 30.214674 | 82 | py |
quimb | quimb-main/quimb/tensor/__init__.py | """Tensor and tensor network functionality.
"""
from .contraction import (
contract_backend,
contract_strategy,
get_contract_backend,
get_contract_strategy,
get_tensor_linop_backend,
set_contract_backend,
set_contract_path_cache,
set_contract_strategy,
set_tensor_linop_backend,
... | 7,938 | 20.341398 | 50 | py |
quimb | quimb-main/quimb/tensor/interface.py | """Tools for interfacing the tensor and tensor network objects with other
libraries.
"""
import functools
from ..utils import tree_map
from .tensor_core import Tensor, TensorNetwork
class Placeholder:
__slots__ = ("shape",)
def __init__(self, x):
self.shape = getattr(x, "shape", None)
def __r... | 2,659 | 23.859813 | 79 | py |
quimb | quimb-main/quimb/tensor/tensor_core.py | """Core tensor network tools.
"""
import os
import copy
import uuid
import math
import string
import weakref
import operator
import functools
import itertools
import contextlib
import collections
from numbers import Integral
import numpy as np
import opt_einsum as oe
import scipy.sparse.linalg as spla
from autoray imp... | 350,898 | 32.87383 | 79 | py |
quimb | quimb-main/quimb/experimental/tn_marginals.py | """Helper functions for computing marginals of classical partition functions /
SAT problems.
"""
def compute_all_marginals_via_slicing(
tn,
output_inds,
optimize="auto-hq",
**contract_kwargs,
):
tree0 = tn.contraction_tree(output_inds=(), optimize=optimize)
arrays = tn.arrays
w = {}
... | 3,496 | 25.694656 | 78 | py |
quimb | quimb-main/quimb/experimental/autojittn.py | """Decorator for automatically just in time compiling tensor network functions.
TODO::
- [ ] go via an intermediate pytree / array function, that could be shared
e.g. with the TNOptimizer class.
"""
import functools
import autoray as ar
class AutojittedTN:
"""Class to hold the ``autojit_tn`` de... | 4,098 | 30.530769 | 79 | py |
quimb | quimb-main/quimb/experimental/tnvmc.py | """Tools for generic VMC optimization of tensor networks.
"""
import array
import random
import numpy as np
import autoray as ar
from quimb import format_number_with_error
# --------------------------------------------------------------------------- #
def sample_bitstring_from_prob_ndarray(p, rng):
flat_idx ... | 41,266 | 28.37153 | 94 | py |
Sarcasm-Detection-using-NN | Sarcasm-Detection-using-NN-master/train_CUE_CNN.py | import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvi... | 16,093 | 37.780723 | 125 | py |
Sarcasm-Detection-using-NN | Sarcasm-Detection-using-NN-master/param_sweep.py | import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
from torch.optim.lr_scheduler import ReduceLROnPlateau
import torch.utils.data
import torch.utils.data.distributed
imp... | 20,059 | 44.384615 | 161 | py |
Sarcasm-Detection-using-NN | Sarcasm-Detection-using-NN-master/Headlines_RNN.py | import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvi... | 19,074 | 38.329897 | 176 | py |
Sarcasm-Detection-using-NN | Sarcasm-Detection-using-NN-master/twitter_data_set.py | import ast
import csv
import sys
import numpy as np
from torch.utils.data.dataset import Dataset
from collections import defaultdict
from pdb import set_trace as brk
import torch
class TwitterDataset(Dataset):
"""Twitter dataset."""
def __init__(self, csv_file, folds_file, word_embedding_file, user_embedding_... | 6,178 | 37.141975 | 128 | py |
Sarcasm-Detection-using-NN | Sarcasm-Detection-using-NN-master/param_sweep_Headlines_RNN.py | import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvi... | 23,539 | 45.799205 | 259 | py |
Sarcasm-Detection-using-NN | Sarcasm-Detection-using-NN-master/SemEval_CUE_CNN.py | import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvi... | 17,985 | 38.356674 | 155 | py |
Sarcasm-Detection-using-NN | Sarcasm-Detection-using-NN-master/SemEval_data_set.py | import ast
import csv
import sys
import numpy as np
from torch.utils.data.dataset import Dataset
from collections import defaultdict
from pdb import set_trace as brk
import torch
import pandas as pd
class SemEvalDataset(Dataset):
"""SemEval dataset."""
def __init__(self, csv_file, word_embedding_file, pad, ma... | 3,525 | 36.115789 | 100 | py |
Sarcasm-Detection-using-NN | Sarcasm-Detection-using-NN-master/Headlines_CNN.py | import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvi... | 18,053 | 38.419214 | 155 | py |
Sarcasm-Detection-using-NN | Sarcasm-Detection-using-NN-master/headline_data_set.py | import ast
import csv
import sys
import numpy as np
from torch.utils.data.dataset import Dataset
from collections import defaultdict
from pdb import set_trace as brk
import torch
import pandas as pd
class HeadlineDataset(Dataset):
"""SemEval dataset."""
def __init__(self, csv_file, word_embedding_file, pad, w... | 4,939 | 38.52 | 141 | py |
HAL | HAL-main/run.py | import warnings # Keep output clean
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=DeprecationWarning)
import torch
import os
import signal
import argparse
import wandb
import cProfile
import pstats
from io import S... | 32,614 | 42.602941 | 103 | py |
HAL | HAL-main/algorithms/network/network_heads.py | # Modified from https://github.com/ShangtongZhang/DeepRL
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from ..utils.torch_utils import tensor
from ..utils.config import Config
from .network_utils import BaseNet, layer_init, NoisyLinear
class DuelingNet(nn.Module, BaseNet):
"""Supports ... | 10,346 | 37.180812 | 88 | py |
HAL | HAL-main/algorithms/network/network_utils.py | # Almost unchanged from https://github.com/ShangtongZhang/DeepRL
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from ..utils import *
class BaseNet:
def __init__(self):
pass
def reset_noise(self):
pass
def layer_init(layer, w_scale=1.0):
nn.init.orthogon... | 2,812 | 34.607595 | 102 | py |
HAL | HAL-main/algorithms/network/network_bodies.py | # Modified from https://github.com/ShangtongZhang/DeepRL
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from .network_utils import layer_init, NoisyLinear
from ..utils.config import Config
class GridBody(nn.Module):
def __init__(self, in_channels=4, vec_dim=10, noisy_linear=False,
... | 2,945 | 31.733333 | 76 | py |
HAL | HAL-main/algorithms/utils/normalizer.py | # Modified from https://github.com/ShangtongZhang/DeepRL
import numpy as np
import torch
class BaseNormalizer:
def __init__(self, read_only=False):
self.read_only = read_only
def set_read_only(self):
self.read_only = True
def unset_read_only(self):
self.read_only = False
def... | 1,435 | 24.192982 | 79 | py |
HAL | HAL-main/algorithms/utils/logger.py | # Modified from https://github.com/ShangtongZhang/DeepRL
from torch.utils.tensorboard import SummaryWriter
import numpy as np
import torch
import wandb
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s: %(message)s')
from .misc import *
def get_logger(wb=False, tag='default', log_lev... | 3,380 | 31.825243 | 102 | py |
HAL | HAL-main/algorithms/utils/config.py | # Modified from https://github.com/ShangtongZhang/DeepRL
from .normalizer import RescaleNormalizer, GridRLNormalizer, LogNormalizer
import argparse
import torch
class Config:
DEVICE = torch.device('cpu')
NOISY_LAYER_STD = 0.1
DEFAULT_REPLAY = 'replay'
PRIORITIZED_REPLAY = 'prioritized_replay'
WAND... | 3,899 | 31.773109 | 74 | py |
HAL | HAL-main/algorithms/utils/torch_utils.py | # Modified from https://github.com/ShangtongZhang/DeepRL
from .config import Config
import numpy as np
import torch as th
import random
import os
def select_device(gpu_id):
# if th.cuda.is_available() and gpu_id >= 0:
if gpu_id >= 0:
Config.DEVICE = th.device('cuda:%d' % (gpu_id))
else:
Co... | 11,859 | 31.582418 | 80 | py |
HAL | HAL-main/algorithms/utils/__init__.py | from .config import *
from .normalizer import *
from .misc import *
from .logger import *
from .schedule import *
from .torch_utils import *
from .sum_tree import *
| 165 | 19.75 | 26 | py |
HAL | HAL-main/algorithms/agent/HDQN_agent.py | from ..utils import to_np, epsilon_greedy, tensor, \
epsilon_greedy_plus, double_epsilon_greedy
from ..utils.torch_utils import range_tensor
from ..component.envs import LazyFrames
from ..utils.config import Config
from ..utils.misc import close_obj
from .BaseAgent import BaseAgent, BaseActor
impor... | 79,873 | 40.818848 | 111 | py |
HAL | HAL-main/algorithms/agent/BaseAgent.py | # Almost unchanged from https://github.com/ShangtongZhang/DeepRL
import torch
import numpy as np
import pickle
from ..utils import *
import torch.multiprocessing as mp
from collections import deque
from skimage.io import imsave
class BaseAgent:
def __init__(self, config):
self.config = config
self... | 7,446 | 33.317972 | 103 | py |
HAL | HAL-main/algorithms/agent/DQN_agent.py | # Modified from https://github.com/ShangtongZhang/DeepRL
from ..utils import to_np, epsilon_greedy, close_obj, tensor
from ..component.envs import LazyFrames
from ..utils.config import Config
from ..utils.torch_utils import range_tensor
from .BaseAgent import BaseAgent, BaseActor
import torch
import torch.nn as nn
imp... | 10,658 | 37.480144 | 89 | py |
HAL | HAL-main/algorithms/component/replay.py | # Modified from https://github.com/ShangtongZhang/DeepRL
import torch
import numpy as np
import random
from collections import namedtuple, defaultdict
import torch.multiprocessing as mp
from ..utils import SumTree
from ..utils.torch_utils import tensor
# Legacy
Transition = namedtuple('Transition', ['state', 'action'... | 52,246 | 37.416912 | 88 | py |
MSDNet-PyTorch | MSDNet-PyTorch-master/main.py | #!/usr/bin/env python3
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
import sys
import math
import time
import shutil
from dataloader import get_dataloaders
from args import arg_parser
from adaptive_inference import dynamic_evaluate
import mode... | 11,148 | 30.673295 | 106 | py |
MSDNet-PyTorch | MSDNet-PyTorch-master/adaptive_inference.py | from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
import os
import math
def dynamic_evaluate(model, test_loader, val_loader, args):
tester = Tester(model, args)
if os.path.exis... | 5,692 | 36.701987 | 120 | py |
MSDNet-PyTorch | MSDNet-PyTorch-master/dataloader.py | import torch
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import os
def get_dataloaders(args):
train_loader, val_loader, test_loader = None, None, None
if args.data == 'cifar10':
normalize = transforms.Normalize(mean=[0.4914, 0... | 4,774 | 45.813725 | 78 | py |
MSDNet-PyTorch | MSDNet-PyTorch-master/op_counter.py | from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
from torch.autograd import Variable
from functools import reduce
import operator
'''
Calculate the FLOPS of each exit without lazy... | 4,420 | 30.578571 | 88 | py |
MSDNet-PyTorch | MSDNet-PyTorch-master/models/msdnet.py | import torch.nn as nn
import torch
import math
import pdb
class ConvBasic(nn.Module):
def __init__(self, nIn, nOut, kernel=3, stride=1,
padding=1):
super(ConvBasic, self).__init__()
self.net = nn.Sequential(
nn.Conv2d(nIn, nOut, kernel_size=kernel, stride=stride,
... | 12,602 | 35.850877 | 146 | py |
dfd_benchmark | dfd_benchmark-master/detect_img.py | import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
import torch.nn as nn
import argparse
from PIL import Image
import torchvision.transforms as transforms
import glob
import torch
# from pytorch_model.train import *
# from tf_model.train import *
def parse_args():
parser = argparse.ArgumentP... | 7,629 | 46.6875 | 138 | py |
dfd_benchmark | dfd_benchmark-master/eval.py | import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
#import os, logging
#os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
#import tensorflow as tf
#tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
import argparse
import torch.nn as nn
# from pytorch_model.train import *
# from tf_model.t... | 14,525 | 54.442748 | 138 | py |
dfd_benchmark | dfd_benchmark-master/train.py | import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
import torch.nn as nn
import argparse
# from pytorch_model.train import *
# from tf_model.train import *
def parse_args():
parser = argparse.ArgumentParser(description="Deepfake detection")
parser.add_argument('--train_set', default="da... | 23,000 | 62.016438 | 159 | py |
dfd_benchmark | dfd_benchmark-master/tf_model/residual_attention_keras.py | import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0"
import tensorflow.keras.backend as K
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.per_... | 11,137 | 35.28013 | 212 | py |
dfd_benchmark | dfd_benchmark-master/tf_model/train_tf.py | # from collections import Counter
import numpy as np
from sklearn.utils import class_weight
from keras.preprocessing.image import ImageDataGenerator
import keras
import os
from keras.optimizers import Adam
from PIL import ImageEnhance,Image
import matplotlib.pyplot as plt
from PIL import ImageFile
ImageFile.LOAD_TRUNC... | 7,415 | 47.470588 | 209 | py |
dfd_benchmark | dfd_benchmark-master/tf_model/eval_tf.py | # from collections import Counter
import numpy as np
from sklearn.utils import class_weight
from keras.preprocessing.image import ImageDataGenerator
import torchtoolbox.transform as transforms
import cv2
import keras
import os
from PIL import ImageEnhance,Image
import tensorflow as tf
from albumentations.augmentations.... | 4,943 | 32.632653 | 144 | py |
dfd_benchmark | dfd_benchmark-master/tf_model/focal_loss.py |
"""TensorFlow Keras focal loss implementation."""
# ____ __ ___ __ __ __ __ ____ ____
# ( __)/ \ / __) / _\ ( ) ( ) / \ / ___)/ ___)
# ) _)( O )( (__ / \/ (_/\ / (_/\( O )\___ \\___ \
# (__) \__/ \___)\_/\_/\____/ \____/ \__/ (____/(____/
from functools import partial
import ... | 10,391 | 37.776119 | 80 | py |
dfd_benchmark | dfd_benchmark-master/tf_model/siamese.py | # import os
#
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
# os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.allow_grow... | 6,727 | 38.576471 | 123 | py |
dfd_benchmark | dfd_benchmark-master/tf_model/model_cnn_keras.py | import keras.backend as K
import tensorflow as tf
import keras
from tf_model.focal_loss import BinaryFocalLoss
def xception(image_size=256):
model = keras.models.Sequential([
keras.applications.Xception(include_top=False, weights="imagenet", input_shape=(image_size, image_size, 3)),
keras.layers.Fl... | 1,214 | 40.896552 | 116 | py |
dfd_benchmark | dfd_benchmark-master/tf_model/mesonet/model.py |
from keras.models import Model as KerasModel
from keras.layers import Input, Dense, Flatten, Conv2D, MaxPooling2D, BatchNormalization, Dropout, Reshape, Concatenate, LeakyReLU
# IMGWIDTH = 256
class Meso1():
"""
Feature extraction + Classification
"""
def __init__(self,image_size=256, learning_rate... | 6,992 | 35.233161 | 130 | py |
dfd_benchmark | dfd_benchmark-master/tf_model/gan_fingerprint/misc.py | # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain ... | 16,804 | 35.934066 | 177 | py |
dfd_benchmark | dfd_benchmark-master/preprocess_data/extract_face.py | # import os
import argparse
# import random
from os.path import isfile, join
# import json
from tqdm import tqdm
import cv2
import numpy as np
# import pickle
from facenet_pytorch import MTCNN
# from operator import itemgetter
import glob
import matplotlib.pyplot as plt
import torch
torch.multiprocessing.set_start_meth... | 4,194 | 33.958333 | 110 | py |
dfd_benchmark | dfd_benchmark-master/preprocess_data/extract_frame.py | # import os
import argparse
# import random
from os.path import isfile, join
# import json
from tqdm import tqdm
import cv2
import numpy as np
# import pickle
from facenet_pytorch import MTCNN
# from operator import itemgetter
import glob
import matplotlib.pyplot as plt
import torch
# from pytorch_model.train import *... | 2,413 | 30.350649 | 110 | py |
dfd_benchmark | dfd_benchmark-master/preprocess_data/test_adj.py | import torchvision
from PIL import Image
img_path = "../../../extract_raw_img/real/aabqyygbaa.mp4_0.jpg"
im = Image.open(img_path)
im_adj = torchvision.transforms.functional.adjust_contrast(im,4)
im_adj.show() | 209 | 34 | 64 | py |
dfd_benchmark | dfd_benchmark-master/preprocess_data/extract_face_kaggle.py | import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0"
import random
from os import listdir
from os.path import isfile, join
import numpy as np
import json
import matplotlib.pyplot as plt
import cv2
margin = 0.2
from tqdm import tqdm
# from mtcnn import MTCN... | 6,862 | 37.994318 | 283 | py |
dfd_benchmark | dfd_benchmark-master/cnn_visualization/generate_class_specific_samples.py | """
Created on Thu Oct 26 14:19:44 2017
@author: Utku Ozbulak - github.com/utkuozbulak
"""
import os
import numpy as np
import torch
from torch.optim import SGD
from cnn_visualization.misc_functions import preprocess_image, recreate_image, save_image
import argparse
import torch.nn as nn
class ClassSpecificImageGe... | 8,238 | 43.058824 | 138 | py |
dfd_benchmark | dfd_benchmark-master/cnn_visualization/integrated_gradients.py | """
Created on Wed Jun 19 17:06:48 2019
@author: Utku Ozbulak - github.com/utkuozbulak
"""
import torch
import numpy as np
from cnn_visualization.misc_functions import get_example_params, convert_to_grayscale, save_gradient_images
class IntegratedGradients():
"""
Produces gradients generated with integr... | 3,700 | 37.552083 | 119 | py |
dfd_benchmark | dfd_benchmark-master/cnn_visualization/guided_backprop.py | """
Created on Thu Oct 26 11:23:47 2017
@author: Utku Ozbulak - github.com/utkuozbulak
"""
import torch
from torch.nn import ReLU
from cnn_visualization.misc_functions import (get_example_params,
convert_to_grayscale,
save_gradient_images,
... | 4,781 | 39.871795 | 119 | py |
dfd_benchmark | dfd_benchmark-master/cnn_visualization/generate_regularized_class_specific_samples.py | """
Created on Tues Mar 10 08:13:15 2020
@author: Alex Stoken - https://github.com/alexstoken
Last tested with torchvision 0.5.0 with image and model on cpu
"""
import os
import numpy as np
from PIL import Image, ImageFilter
import torch
from torch.optim import SGD
from torch.autograd import Variable
from torchvision... | 12,378 | 41.539519 | 138 | py |
dfd_benchmark | dfd_benchmark-master/cnn_visualization/misc_functions.py | """
Created on Thu Oct 21 11:09:09 2017
@author: Utku Ozbulak - github.com/utkuozbulak
"""
import os
import copy
import numpy as np
from PIL import Image, ImageFilter
import matplotlib.cm as mpl_color_map
import torch
from torch.autograd import Variable
from torchvision import models
def convert_to_grayscale(im_as_... | 9,350 | 34.286792 | 91 | py |
dfd_benchmark | dfd_benchmark-master/pytorch_model/local_nn.py |
import torch.nn.functional as F
from torch.nn import init
import torch
import torch.nn as nn
class NLBlockND(nn.Module):
def __init__(self, in_channels, inter_channels=None, mode='embedded',
dimension=3, bn_layer=True):
"""Implementation of Non-Local Block with 4 different pairwise functi... | 9,186 | 37.60084 | 140 | py |
dfd_benchmark | dfd_benchmark-master/pytorch_model/train_torch.py | import torch
import random
import os
# import torchvision.transforms as transforms
from torch.optim import Adam
# import torchvision.datasets as datasets
import torch.backends.cudnn as cudnn
from sklearn import metrics
import numpy as np
from torch.autograd import Variable
from pytorch_model.capsule_pytorch.model impor... | 38,005 | 48.87664 | 163 | py |
dfd_benchmark | dfd_benchmark-master/pytorch_model/self_attention.py | import torch
import torch.nn as nn
from torch.nn import Parameter
def l2normalize(v, eps=1e-12):
return v / (v.norm() + eps)
class SpectralNorm(nn.Module):
def __init__(self, module, name='weight', power_iterations=1):
super(SpectralNorm, self).__init__()
self.module = module
self.na... | 5,436 | 33.194969 | 107 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.