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
FewRel
FewRel-master/models/metanet.py
import sys sys.path.append('..') import fewshot_re_kit from fewshot_re_kit.network.embedding import Embedding from fewshot_re_kit.network.encoder import Encoder import torch from torch import autograd, optim, nn from torch.autograd import Variable from torch.nn import functional as F import numpy as np def log_and_sig...
8,016
37.729469
187
py
meta-demodulator
meta-demodulator-master/main_offline.py
from __future__ import print_function import torch import numpy from nets.deeper_linear import deeper_linear_net from nets.deeper_linear import deeper_linear_net_prime from data_gen.data_set import generating_training_set from data_gen.data_set import generating_test_set from training.train import meta_train from train...
64,128
58.105069
329
py
meta-demodulator
meta-demodulator-master/main_online.py
from __future__ import print_function import torch import numpy from nets.deeper_linear import deeper_linear_net from nets.deeper_linear import deeper_linear_net_prime from data_gen.data_set import generating_online_training_set from data_gen.data_set import generating_test_set from training.train import meta_train_onl...
59,507
58.448551
308
py
meta-demodulator
meta-demodulator-master/nets/meta_net.py
from __future__ import print_function import torch.nn as nn from torch.nn import functional as F class meta_Net(nn.Module): def __init__(self, if_relu): # it only gets paramters from other network's parameters super(meta_Net, self).__init__() self.vars = nn.ParameterList() self.softmax = nn...
1,484
32
89
py
meta-demodulator
meta-demodulator-master/nets/deeper_linear.py
from __future__ import print_function import torch.nn as nn class deeper_Net(nn.Module): def __init__(self, args, m_ary, num_neurons_first, num_neurons_second, num_neurons_third, if_bias, if_relu): if m_ary == 5: m_ary = 4 super(deeper_Net, self).__init__() self.layer_list = [] ...
1,932
36.173077
112
py
meta-demodulator
meta-demodulator-master/training/train.py
from __future__ import print_function import torch import numpy from loss.cross_entropy_loss import cross_entropy_loss from loss.cross_entropy_loss import cross_entropy_loss_test from nets.meta_net import meta_net import math import os from numpy.linalg import inv import scipy.io as sio from data_gen.data_set import iq...
101,937
53.164718
427
py
meta-demodulator
meta-demodulator-master/loss/cross_entropy_loss.py
from __future__ import print_function import torch def cross_entropy_loss(loss, error_rate, M, s, out): ## loss function K, _= s.size() success = 0 loss = 0 for i in range(K): if M == 2: if s[i, 0] == -1: loss = loss - out[i][0] if torch.argmax...
10,797
37.841727
75
py
meta-demodulator
meta-demodulator-master/data_gen/data_set.py
from __future__ import print_function import torch def generating_symbol(M, device_for_data): device = device_for_data Bern = torch.distributions.bernoulli.Bernoulli(torch.tensor([0.5])) # equal prob. if M == 2: # BPSK symb = Bern.sample() symb = symb.to(device) if symb == 0: ...
38,518
50.912399
146
py
BiGI
BiGI-main/BiGI_src/train_rec.py
import os import sys from datetime import datetime import time import numpy as np import random import argparse from shutil import copyfile import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from model.trainer import DGITrainer from utils.loader import DataLoader from uti...
12,721
43.020761
171
py
BiGI
BiGI-main/BiGI_src/train_lp.py
import os import sys from datetime import datetime import time import numpy as np import random import argparse from shutil import copyfile import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from model.trainer import DGITrainer from utils.loader import DataLoader,wikiData...
11,728
42.280443
170
py
BiGI
BiGI-main/BiGI_src/utils/torch_utils.py
""" Utility functions for torch. """ import torch from torch import nn, optim from torch.optim.optimizer import Optimizer ### class class MyAdagrad(Optimizer): """My modification of the Adagrad optimizer that allows to specify an initial accumulater value. This mimics the behavior of the default Adagrad imple...
5,703
32.751479
106
py
BiGI
BiGI-main/BiGI_src/utils/loader.py
""" Data loader for TACRED json files. """ import json import random import torch import numpy as np class DataLoader(object): """ Load data from json files, preprocess and prepare batches. """ def __init__(self, filename, batch_size, opt, user_real_dict, user_fake_dict, item_real_dict, item_fake_dic...
12,021
43.03663
373
py
BiGI
BiGI-main/BiGI_src/utils/GraphMaker.py
import numpy as np import random import scipy.sparse as sp import torch import codecs import json import copy def normalize(mx): """Row-normalize sparse matrix""" rowsum = np.array(mx.sum(1)) r_inv = np.power(rowsum, -1).flatten() r_inv[np.isinf(r_inv)] = 0. r_mat_inv = sp.diags(r_inv) mx = r_m...
6,173
37.5875
200
py
BiGI
BiGI-main/BiGI_src/model/myDGI.py
import torch import torch.nn as nn import torch.nn.functional as F import math from model.GAT import GAT class AvgReadout(nn.Module): def __init__(self): super(AvgReadout, self).__init__() def forward(self, seq, msk=None): if msk is None: return torch.mean(seq, 0) else: ...
3,453
38.25
180
py
BiGI
BiGI-main/BiGI_src/model/GCN.py
import torch.nn as nn import torch.nn.functional as F import math import torch import torch.nn as nn from torch.nn.modules.module import Module class GCN(nn.Module): def __init__(self, nfeat, nhid, dropout, alpha): super(GCN, self).__init__() self.gc1 = GraphConvolution(nfeat, nhid) self.d...
1,586
29.519231
80
py
BiGI
BiGI-main/BiGI_src/model/AttDGI.py
import torch import torch.nn as nn import torch.nn.functional as F import math class AvgReadout(nn.Module): def __init__(self): super(AvgReadout, self).__init__() def forward(self, seq, msk=None): if msk is None: return torch.mean(seq, 0) else: msk = torch.unsqu...
4,036
36.036697
182
py
BiGI
BiGI-main/BiGI_src/model/GNN.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import math from model.GCN import GCN from torch.autograd import Variable class GNN(nn.Module): """ GNN Module layer """ def __init__(self, opt): super(GNN, self).__init__() self.opt=opt se...
2,670
32.3875
96
py
BiGI
BiGI-main/BiGI_src/model/GNN2.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import math from model.GCN import GCN from torch.autograd import Variable class GNN2(nn.Module): """ DGCN Module layer """ def __init__(self, opt): super(GNN2, self).__init__() self.opt=opt ...
3,755
31.66087
118
py
BiGI
BiGI-main/BiGI_src/model/BiGI.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from model.GNN import GNN from model.GNN2 import GNN2 from model.AttDGI import AttDGI from model.myDGI import myDGI class BiGI(nn.Module): def __init__(self, opt): super(BiGI, self).__init__() self.opt=opt ...
1,702
36.844444
84
py
BiGI
BiGI-main/BiGI_src/model/GAT.py
import torch.nn as nn import torch.nn.functional as F import math import torch import torch.nn as nn from torch.nn.modules.module import Module class GAT(nn.Module): def __init__(self, opt): super(GAT, self).__init__() self.att = Attention(opt) self.dropout = opt["dropout"] self.le...
1,907
30.8
81
py
BiGI
BiGI-main/BiGI_src/model/trainer.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from utils import torch_utils from model.BiGI import BiGI class Trainer(object): def __init__(self, opt): raise NotImplementedError def update(self, batch): raise NotImplementedError def...
9,418
44.066986
290
py
ATN
ATN-main/custom_transforms.py
# Basic library of transforms not included in torch.torchvision # By Ashkan Pakzad (ashkanpakzad.github.io) 2022 import torch import torchvision.transforms.functional as TF import numpy as np import numbers from typing import Tuple, List, Optional from collections.abc import Sequence class GaussianNoise(object): ...
10,751
31.581818
114
py
ATN
ATN-main/engine.py
# By Ashkan Pakzad (ashkanpakzad.github.io) 2022 import matplotlib import matplotlib.pyplot as plt import torch import enum from tqdm import tqdm import numpy as np import util from sklearn import metrics from dataset import prepare_cnr_batch from pathlib import Path import wandb class Action(enum.Enum): TRAIN =...
13,015
27.4814
100
py
ATN
ATN-main/simgan.py
# By Ashkan Pakzad (ashkanpakzad.github.io) 2022 import os import wandb from tqdm import tqdm import util from imagehistorybuffer import ImageHistoryBuffer from engine import setmodel, ModelAction, prer_train, pred_train, adv_train from model import getmodels from loss import VGGPerceptualLoss from dataset import Decla...
15,039
31.982456
101
py
ATN
ATN-main/imagehistorybuffer.py
# Adapted from https://github.com/mjdietzx/SimGAN/, under MIT license import numpy as np import torch class ImageHistoryBuffer(object): def __init__(self, shape, max_size, batch_size, device): """ Initialize the class's state. :param shape: Shape of the data to be stored in the image histo...
2,520
42.465517
119
py
ATN
ATN-main/loss.py
# By Ashkan Pakzad (ashkanpakzad.github.io) 2022 # Adapted from https://gist.github.com/alper111/8233cdb0414b4cb5853f2f730ab95a49 import torch import torchvision from torchvision.models import vgg16, VGG16_Weights class VGGPerceptualLoss(torch.nn.Module): def __init__( self, resize=True, feature_layers=[...
3,829
34.462963
80
py
ATN
ATN-main/model.py
# By Ashkan Pakzad (ashkanpakzad.github.io) 2022 from torch import nn import util def parsemode(mode): if mode == 'ellipse': outn = 8 elif mode == 'circle': outn = 2 else: raise(ValueError, 'argument mode invalid') return outn ##==========================CNR=================...
4,838
29.055901
76
py
ATN
ATN-main/dataset.py
# By Ashkan Pakzad (ashkanpakzad.github.io) 2022 import torch from pathlib import Path import tifffile import numpy as np from torchvision import transforms import custom_transforms import pandas as pd import copy from math import pi class DeclareTransforms: def __init__(self, inputsize): self.inputsize ...
6,518
29.895735
112
py
ATN
ATN-main/cnr.py
# By Ashkan Pakzad (ashkanpakzad.github.io) 2022 import wandb import os from pathlib import Path import torch from torch.utils.data import DataLoader, Subset import random import argparse import engine import dataset import model import util torch.backends.cudnn.benchmark = True os.environ["KMP_DUPLICATE_LIB_OK"] =...
7,070
27.39759
101
py
ATN
ATN-main/util.py
# By Ashkan Pakzad (ashkanpakzad.github.io) 2022 import torch import json import matplotlib.pyplot as plt from matplotlib.patches import Circle, Ellipse import numpy as np from dataset import da_vector_2_angle def calc_acc(output, type): assert type in [0, 1] # TARGET 0 FOR REAL AND 1 FOR REFINED target ...
4,803
27.258824
99
py
ATN
ATN-main/atn.py
# By Ashkan Pakzad (ashkanpakzad.github.io) 2022 import os from pathlib import Path import wandb import torch import torch.nn as nn import torchvision from torch.utils.data import DataLoader, Subset import random import argparse from dataset import DeclareTransforms, prepare_batch, ImageData from loss import VGGPercept...
9,601
29.579618
88
py
ATN
ATN-main/AQ_CNR.py
import torch from torch.utils.data import DataLoader from dataset import DeclareTransforms, ImageData from model import getmodels, getCNRmodel import util import numpy as np from pathlib import Path def outputellipse(vals): ''' Convert output of model variables to interpretable ellipse parameters. input v...
2,062
28.898551
94
py
ATN
ATN-main/MakeDatasetHead.py
# By Ashkan Pakzad (ashkanpakzad.github.io) 2022 from pathlib import Path import torch from torch.utils.data import DataLoader import custom_transforms import argparse from dataset import ImageData import json from tqdm import tqdm def args_parser(): parser = argparse.ArgumentParser('Explore', add_help=False) ...
3,029
31.234043
116
py
terngrad
terngrad-master/terngrad/inception/data/build_imagenet_data.py
# Copyright 2016 Google Inc. 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 # # Unless required by applicable law or a...
26,828
36.314325
87
py
terngrad
terngrad-master/terngrad/inception/slim/models.py
# Copyright 2016 Google Inc. 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 # # Unless required by applicable law or agree...
28,545
50.434234
131
py
terngrad
terngrad-master/slim/nets/resnet_utils.py
# Copyright 2016 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 # # Unless required by applicable ...
10,613
40.623529
80
py
swat-seq2seq
swat-seq2seq-master/test_dataset.py
import torch from torch.utils.data import DataLoader import conf from swat_dataset import SWaTDataset def test_parsed_dataset(): BATCH_SIZE = 5 N_SAMPLES = 20 for datatype in ['normal', 'attack']: for pidx in range(conf.N_PROCESS): dataset = SWaTDataset('dat/{}-P{}.dat'.format(datatyp...
1,131
39.428571
119
py
swat-seq2seq
swat-seq2seq-master/network.py
import torch from torch import nn, optim from torch.utils.data import DataLoader import conf import model from db import InfluxDB, swat_time_to_nanosec DB = InfluxDB('swat') class Network: def __init__(self, pidx: int, gidx: int, n_features: int, n_hiddens: int): self.n_features = n_features sel...
3,787
36.88
102
py
swat-seq2seq
swat-seq2seq-master/validate.py
import argparse import sys from datetime import datetime import torch from torch.utils.data import ConcatDataset import conf from db import InfluxDB, datetime_to_nanosec from network import Network from swat_dataset import SWaTDataset N_DUPLICATE_RUNS = 2 BATCH_SIZE = 1024 # larger validation batch is possible, bu...
1,512
28.666667
115
py
swat-seq2seq
swat-seq2seq-master/model.py
import torch import torch.nn.parallel from torch import nn import conf class Encoder(nn.Module): def __init__(self, n_inputs, n_hiddens): super().__init__() self.n_hiddens = n_hiddens self.lstm1 = nn.LSTMCell(input_size=n_inputs, hidden_size=n_hiddens) self.lstm2 = nn.LSTMCell(inp...
3,679
41.298851
113
py
swat-seq2seq
swat-seq2seq-master/swat_dataset.py
import pickle import torch from torch.utils.data import Dataset import conf class SWaTDataset(Dataset): def __init__(self, pickle_jar: str): with open(pickle_jar, 'rb') as f: self.picks = pickle.load(f) def __len__(self): return len(self.picks) def __getitem__(self, idx): ...
717
26.615385
69
py
swat-seq2seq
swat-seq2seq-master/train.py
import argparse import configparser import sys from datetime import datetime import torch import conf from db import InfluxDB, datetime_to_nanosec from network import Network from swat_dataset import SWaTDataset assert torch.cuda.device_count() >= 6 BATCH_SIZE = 4096 DB = InfluxDB('swat') parser = argparse.Argumen...
2,203
29.611111
100
py
resalloc
resalloc-main/setup.py
import codecs import os.path from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() def read(rel_path): here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, rel_path), "r") as fp: return fp.read() def get_ve...
1,214
24.851064
62
py
resalloc
resalloc-main/resalloc/optim.py
import logging import sys import time import torch from resalloc.lbfgs import LBFGS LOGGER = logging.getLogger("__doubly_projected__") LOGGER.propagate = False LOGGER.setLevel(logging.INFO) _stream_handler = logging.StreamHandler(sys.stdout) _stream_handler.setLevel(logging.INFO) _formatter = logging.Formatter( ...
9,382
27.69419
83
py
resalloc
resalloc-main/resalloc/lbfgs.py
""" L-BFGS, but with constraints. Based on the official PyTorch implementation. """ import numpy as np import torch from functools import reduce #from pymde.util import SolverError def _cubic_interpolate(x1, f1, g1, x2, f2, g2, bounds=None): # ported from https://github.com/torch/optim/blob/master/polyinterp...
19,742
34.255357
79
py
resalloc
resalloc-main/resalloc/latexify.py
import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np import torch def latexify(figsize_inches=None, font_size=12): """Set up matplotlib's RC params for LaTeX plotting. This function only needs to be called once per Python session. ...
2,202
26.5375
79
py
resalloc
resalloc-main/resalloc/constraints.py
import abc import torch class Constraint(abc.ABC): """A generic constraint. To create a custom constraint, create a subclass of this class, and implement its abstract methods. """ @abc.abstractmethod def name(self) -> str: """The name of the constraint.""" raise NotImplement...
3,194
26.307692
79
py
resalloc
resalloc-main/resalloc/fungible/fungible.py
import time import numpy as np import torch import resalloc.constraints as constraints import resalloc.optim as optim import resalloc.fungible.utilities as utilities class _Allocator(torch.autograd.Function): @staticmethod def forward(ctx, prices, allocator_object): value, gradient = allocator_object...
11,073
30.460227
84
py
resalloc
resalloc-main/resalloc/fungible/utilities.py
import torch def _initial_prices(utility, alloc_problem): x = alloc_problem.resource_limits[1:] / alloc_problem.n_jobs if x.sum() > 1: x = x / x.sum() t = alloc_problem.A[:, 1:] @ x u_prime_t = utility._derivative(t) prices = (u_prime_t[:, None] * alloc_problem.A[:, 1:]).sum( axis=...
4,629
28.119497
80
py
resalloc
resalloc-main/notebooks/latexify.py
import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np import torch def latexify(figsize_inches=None, font_size=12): """Set up matplotlib's RC params for LaTeX plotting. This function only needs to be called once per Python session. ...
2,202
26.5375
79
py
pypop
pypop-main/pypop7/optimizers/cem/dcem.py
import numpy as np import torch from lml import LML from pypop7.optimizers.cem.scem import SCEM class DCEM(SCEM): """Differentiable Cross-Entropy Method (DCEM). .. note:: Since the underlying `lml` library may be not successfully installed via `pip`, please run the following two commands before invok...
5,686
45.235772
119
py
pypop
pypop-main/pypop7/optimizers/cem/_repeat_dcem.py
"""Repeat the following paper for `DCEM`: Amos, B. and Yarats, D., 2020, November. The differentiable cross-entropy method. In International Conference on Machine Learning (pp. 291-302). PMLR. http://proceedings.mlr.press/v119/amos20a.html Luckily our Python code could repeat the data generated by ...
2,140
34.683333
101
py
pypop
pypop-main/pypop7/optimizers/cc/cosyne.py
import numpy as np from pypop7.optimizers.cc.cc import CC class COSYNE(CC): """CoOperative SYnapse NEuroevolution (COSYNE). .. note:: This is a wrapper of `COSYNE`, which has been implemented in the Python library `EvoTorch <https://docs.evotorch.ai/v0.3.0/reference/evotorch/algorithms/ga/#evotorch.a...
7,527
49.864865
119
py
pypop
pypop-main/pypop7/optimizers/cc/_repeat_cosyne.py
"""Repeat the following paper for `COSYNE`: Gomez, F., Schmidhuber, J. and Miikkulainen, R., 2008. Accelerated neural evolution through cooperatively coevolved synapses. Journal of Machine Learning Research, 9(31), pp.937-965. https://jmlr.org/papers/v9/gomez08a.html We notice that the EvoTorch lib...
2,420
39.35
112
py
affective_bias_in_plm
affective_bias_in_plm-main/LargePLMs based Emotion Detection/GPT2_semeval_finetuning.py
#!/usr/bin/env python # coding: utf-8 import numpy as np import pandas as pd import seaborn as sns import nltk nltk.download('punkt') nltk.download('stopwords') from nltk.corpus import stopwords from nltk.tokenize import word_tokenize, RegexpTokenizer from nltk.corpus import wordnet from nltk.stem import WordNetLemma...
8,660
31.438202
128
py
affective_bias_in_plm
affective_bias_in_plm-main/LargePLMs based Emotion Detection/XLNet_semeval_finetuning.py
#!/usr/bin/env python # coding: utf-8 import numpy as np import pandas as pd import tensorflow as tf import seaborn as sns import transformers import keras import nltk nltk.download('punkt') nltk.download('stopwords') from nltk.corpus import stopwords from nltk.tokenize import word_tokenize, RegexpTokenizer from nlt...
9,406
35.746094
127
py
affective_bias_in_plm
affective_bias_in_plm-main/LargePLMs based Emotion Detection/BERT_semeval_finetuning.py
#!/usr/bin/env python # coding: utf-8 import numpy as np import pandas as pd import seaborn as sns import nltk nltk.download('punkt') nltk.download('stopwords') from nltk.corpus import stopwords from nltk.tokenize import word_tokenize, RegexpTokenizer from nltk.corpus import wordnet from nltk.stem import WordNetLemm...
9,331
29.900662
200
py
affective_bias_in_plm
affective_bias_in_plm-main/LargePLMs based Emotion Detection/T5_semeval_finetuning.py
#!/usr/bin/env python # coding: utf-8 import numpy as np import pandas as pd import seaborn as sns import nltk nltk.download('punkt') nltk.download('stopwords') from nltk.corpus import stopwords from nltk.tokenize import word_tokenize, RegexpTokenizer from nltk.corpus import wordnet from nltk.stem import WordNetLemma...
8,935
33.501931
128
py
MutexMatch4SSL
MutexMatch4SSL-master/utils.py
import os import time from torch.utils.tensorboard import SummaryWriter import logging import torchvision.models as models_torch from models.nets.net import * def setattr_cls_from_kwargs(cls, kwargs): #if default values are in the cls, #overlap the value by kwargs for key in kwargs.keys(): if hasatt...
2,834
32.75
122
py
MutexMatch4SSL
MutexMatch4SSL-master/train_mutex.py
#import needed library import os import logging import random import warnings import numpy as np import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.multiprocessing as mp from utils import net_builder, get_logger, count_paramet...
16,721
43.951613
173
py
MutexMatch4SSL
MutexMatch4SSL-master/train_utils.py
import torch from torch.utils.tensorboard import SummaryWriter from torch.optim.lr_scheduler import LambdaLR import torch.nn.functional as F import math import time import os class TBLog: """ Construc tensorboard writer (self.writer). The tensorboard is saved at os.path.join(tb_dir, file_name). """ ...
5,272
31.549383
128
py
MutexMatch4SSL
MutexMatch4SSL-master/eval_mutex.py
from __future__ import print_function, division import os from models.nets.net import * import torch import torch.nn as nn import numpy as np from utils import net_builder from datasets.ssl_dataset import SSL_Dataset from datasets.data_utils import get_data_loader class TotalNet(nn.Module): def __init__(self, net...
4,096
38.394231
131
py
MutexMatch4SSL
MutexMatch4SSL-master/datasets_mini/miniimage.py
from PIL import Image, ImageFilter import os, sys import random import numpy as np import pandas as pd import os.path as osp import torch import torchvision from torch.utils.data import Dataset from torchvision import transforms # from torchvision.transforms import InterpolationMode from datasets_mini.randaugment im...
11,699
36.620579
230
py
MutexMatch4SSL
MutexMatch4SSL-master/datasets_mini/randaugment.py
# copyright: https://github.com/ildoonet/pytorch-randaugment # code in this file is adpated from rpmcruz/autoaugment # https://github.com/rpmcruz/autoaugment/blob/master/transformations.py # This code is modified version of one of ildoonet, for randaugmentation of fixmatch. import random import PIL, PIL.ImageOps, PIL...
4,485
23.248649
85
py
MutexMatch4SSL
MutexMatch4SSL-master/models/nets/resnet18.py
import torch.nn as nn class ReverseCLS(nn.Module): def __init__(self, in_dim, out_dim): super(ReverseCLS, self).__init__() self.fc = nn.Linear(in_dim, out_dim) self.main = nn.Sequential(self.fc, nn.Softmax(dim=-1)) def forward(self, x): out = [x] for module in self.mai...
1,212
28.585366
79
py
MutexMatch4SSL
MutexMatch4SSL-master/models/nets/net.py
import torch.nn as nn class ReverseCLS(nn.Module): def __init__(self, in_dim, out_dim): super(ReverseCLS, self).__init__() self.fc = nn.Linear(in_dim, out_dim) self.main = nn.Sequential(self.fc, nn.Softmax(dim=-1)) def forward(self, x): out = [x] for module in self.mai...
408
20.526316
62
py
MutexMatch4SSL
MutexMatch4SSL-master/models/nets/cnn13.py
## CNN-13 import torch.nn as nn import torch.nn.functional as F from torch.nn.utils import weight_norm class CNN13(nn.Module): def __init__(self, num_classes=10, dropout=0.5): super(CNN13, self).__init__() #self.gn = GaussianNoise(0.15) self.activation = nn.LeakyReLU(0.1) s...
3,601
29.786325
70
py
MutexMatch4SSL
MutexMatch4SSL-master/models/nets/wrn.py
import math import torch import torch.nn as nn import torch.nn.functional as F momentum=0.001 class BasicBlock(nn.Module): def __init__(self, in_planes, out_planes, stride, bn_momentum=0.1, leaky_slope=0.0, dropRate=0.0): super(BasicBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes, mome...
5,545
41.335878
140
py
MutexMatch4SSL
MutexMatch4SSL-master/models/mutexmatch/mutexmatch.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import os import contextlib from models.nets.net import * from torch.cuda.amp import autocast, GradScaler from .mutexmatch_utils import consistency_loss, Get_Scalar from train_utils import ce_loss class TotalNet(...
14,992
41.59375
172
py
MutexMatch4SSL
MutexMatch4SSL-master/models/mutexmatch/mutexmatch_utils.py
import torch import torch.nn as nn import torch.nn.functional as F from train_utils import ce_loss class Get_Scalar: def __init__(self, value): self.value = value def get_value(self, iter): return self.value def __call__(self, iter): return self.value def consistency_...
2,113
36.087719
146
py
MutexMatch4SSL
MutexMatch4SSL-master/datasets/tinyimage.py
from torch.utils.data import Dataset, DataLoader from torchvision import models, utils, datasets, transforms import numpy as np import sys import os from PIL import Image from .augmentation.randaugment import RandAugment class TinyImageNet(Dataset): def __init__(self, root, train=True): self.Train = trai...
4,844
37.149606
106
py
MutexMatch4SSL
MutexMatch4SSL-master/datasets/ssl_dataset.py
import numpy as np import torch from torch.utils.data import Dataset, DataLoader from torch.utils.data.sampler import BatchSampler from .augmentation.randaugment import RandAugment from .data_utils import get_sampler_by_name, get_data_loader, get_onehot, split_ssl_data from .dataset import BasicDataset import torchv...
10,287
44.321586
167
py
MutexMatch4SSL
MutexMatch4SSL-master/datasets/data_utils.py
import torch import torchvision from torchvision import datasets from torch.utils.data import sampler, DataLoader from torch.utils.data.sampler import BatchSampler import torch.distributed as dist import numpy as np import math from datasets.DistributedProxySampler import DistributedProxySampler def split_ssl_da...
4,979
34.070423
103
py
MutexMatch4SSL
MutexMatch4SSL-master/datasets/dataset.py
from torchvision import datasets, transforms from torch.utils.data import Dataset from .data_utils import get_onehot from .augmentation.randaugment import RandAugment from PIL import Image import numpy as np import copy class BasicDataset(Dataset): """ BasicDataset returns a pair of image and labels (targets...
2,980
33.264368
106
py
MutexMatch4SSL
MutexMatch4SSL-master/datasets/DistributedProxySampler.py
# copyright: https://github.com/pytorch/pytorch/issues/23430#issuecomment-562350407 import math import torch from torch.utils.data.distributed import DistributedSampler class DistributedProxySampler(DistributedSampler): """Sampler that restricts data loading to a subset of input sampler indices. It is espec...
1,748
37.866667
115
py
MutexMatch4SSL
MutexMatch4SSL-master/datasets/augmentation/randaugment.py
# copyright: https://github.com/ildoonet/pytorch-randaugment # code in this file is adpated from rpmcruz/autoaugment # https://github.com/rpmcruz/autoaugment/blob/master/transformations.py # This code is modified version of one of ildoonet, for randaugmentation of fixmatch. import random import PIL, PIL.ImageOps, PIL...
4,485
23.248649
85
py
BTAI_3MF
BTAI_3MF-master/main_BTAI_3MF.py
import time from agent.inference.TemporalSliceBuilder import TemporalSliceBuilder from env.dSpritesEnv import dSpritesEnv from env.wrapper.dSpritesPreProcessingWrapper import dSpritesPreProcessingWrapper from agent.BTAI_3MF import BTAI_3MF import torch # ---------------------------------------------------------------...
4,873
47.257426
107
py
BTAI_3MF
BTAI_3MF-master/analysis/widgets/NavBar.py
import tkinter as tk from tkinter import messagebox import torch # # Class representing the main navigation bar. # class NavBar(tk.Menu): def __init__(self, gui): """ Construct the main navigation bar. :param gui: the graphical user interface. """ # Call super class contru...
1,114
26.195122
81
py
BTAI_3MF
BTAI_3MF-master/analysis/frames/VisualisationFrame.py
import tkinter as tk from PIL import Image, ImageTk import numpy as np class VisualisationFrame(tk.Frame): """ Class representing the frame used to visualise the agent's planning and action selection scheme. """ def __init__(self, parent, gui): """ Construct the visulisation frame...
12,279
36.553517
99
py
BTAI_3MF
BTAI_3MF-master/env/dSpritesEnv.py
import random import torch from env.viewer.DefaultViewer import DefaultViewer from data.dSpritesDataset import DataSet import numpy as np class dSpritesEnv: """ A class implementing the dSprites environment. """ def __init__(self, granularity=4, repeat=8, dataset_file="./data/dsprites.npz"): ...
6,643
32.22
110
py
BTAI_3MF
BTAI_3MF-master/env/wrapper/dSpritesPreProcessingWrapper.py
import torch from torch.nn.functional import one_hot class dSpritesPreProcessingWrapper: """ Class preforming the pre-processing of the observation coming out of the dSprites environment. """ def __init__(self, env, obs_names=None): """ Construct the pre-processor of the dSprites ...
7,148
36.626316
120
py
BTAI_3MF
BTAI_3MF-master/agent/graph/VariableNode.py
import torch from agent.graph.Node import Node class VariableNode(Node): """ Class representing a variable node in the factor graph. """ def __init__(self, name): """ Construct a node of the factor graph. :param name: the node name. """ super().__init__(name, {...
793
26.37931
71
py
BTAI_3MF
BTAI_3MF-master/agent/inference/TemporalSlice.py
import math import queue import torch from torch.nn.functional import one_hot from agent.inference.Operators import Operators class TemporalSlice: """ A class representing a temporal slice that can contain several states, actions and observations. """ def __init__( self, fg, n_actions...
10,702
38.936567
114
py
BTAI_3MF
BTAI_3MF-master/agent/inference/Operators.py
import torch class Operators: @staticmethod def expansion(x1, n, dim): """ Expand the input tensor along a dimension by repating its content n times. :param x1: the input tensor. :param n: the number of times the content needs to be repeated. :param dim: the dimension ...
2,831
33.962963
95
py
fvcore
fvcore-main/tests/test_focal_loss.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import typing import unittest import numpy as np import torch from fvcore.nn import ( sigmoid_focal_loss, sigmoid_focal_loss_jit, sigmoid_focal_loss_star, sigmoid_focal_loss_star_jit, ) from torch.nn import functional as F def l...
18,603
38.752137
88
py
fvcore
fvcore-main/tests/test_checkpoint.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import copy import os import random import string import typing import unittest from collections import OrderedDict from tempfile import TemporaryDirectory from typing import Tuple from unittest.mock import MagicMock import torch from fvcore.comm...
13,541
37.362606
88
py
fvcore
fvcore-main/tests/test_transform.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import itertools import unittest from typing import Any, Tuple import numpy as np import torch from fvcore.transforms import transform as T from fvcore.transforms.transform_util import to_float_tensor, to_numpy # pyre-ignore-all-errors class Te...
40,628
36.138026
96
py
fvcore
fvcore-main/tests/bm_focal_loss.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from fvcore.common.benchmark import benchmark from test_focal_loss import TestFocalLoss, TestFocalLossStar def bm_focal_loss() -> None: if not torch.cuda.is_available(): print("Skipped: CUDA unavailable") return ...
1,377
23.175439
85
py
fvcore
fvcore-main/tests/test_flop_count.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # pyre-ignore-all-errors[2,3,14,53] import typing import unittest from collections import Counter, defaultdict from typing import Any, Dict, Tuple import torch import torch.nn as nn from fvcore.nn.flop_count import _DEFAULT_SUPPORTED_OPS, flop_cou...
28,987
30.069668
88
py
fvcore
fvcore-main/tests/test_activation_count.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # pyre-ignore-all-errors[2] import typing import unittest from collections import Counter, defaultdict from typing import Any, Dict, List, Tuple import torch import torch.nn as nn from fvcore.nn.activation_count import activation_count, Activatio...
5,215
31.397516
87
py
fvcore
fvcore-main/tests/test_smooth_l1_loss.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import unittest import numpy as np import torch from fvcore.nn import smooth_l1_loss class TestSmoothL1Loss(unittest.TestCase): def setUp(self) -> None: super().setUp() np.random.seed(42) def test_smooth_l1_loss(self) -...
1,209
34.588235
86
py
fvcore
fvcore-main/tests/test_weight_init.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import itertools import math import unittest import torch import torch.nn as nn from fvcore.nn.weight_init import c2_msra_fill, c2_xavier_fill class TestWeightInit(unittest.TestCase): """ Test creation of WeightInit. """ def se...
5,795
38.162162
80
py
fvcore
fvcore-main/tests/test_layers_squeeze_excitation.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import itertools import unittest from typing import Iterable import torch from fvcore.nn.squeeze_excitation import ( ChannelSpatialSqueezeExcitation, SpatialSqueezeExcitation, SqueezeExcitation, ) class TestSqueezeExcitation(unittest...
3,784
29.772358
81
py
fvcore
fvcore-main/tests/test_precise_bn.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # -*- coding: utf-8 -*- import itertools import unittest from typing import List, Tuple import numpy as np import torch from fvcore.nn import update_bn_stats from torch import nn class TestPreciseBN(unittest.TestCase): def setUp(self) -> No...
3,345
36.595506
86
py
fvcore
fvcore-main/tests/test_param_count.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import unittest from fvcore.nn.parameter_count import parameter_count, parameter_count_table from torch import nn class NetWithReuse(nn.Module): def __init__(self, reuse: bool = False) -> None: super().__init__() self.conv1...
1,398
29.413043
76
py
fvcore
fvcore-main/tests/test_jit_model_analysis.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # pyre-ignore-all-errors[2,56] import logging import typing import unittest import warnings from collections import Counter from typing import Any, Dict, List import torch import torch.nn as nn from fvcore.nn.flop_count import FlopCountAnalysis fr...
28,372
33.308343
92
py
fvcore
fvcore-main/tests/test_print_model_statistics.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import unittest from typing import Dict import torch import torch.nn as nn from fvcore.nn import ActivationCountAnalysis, FlopCountAnalysis from fvcore.nn.print_model_statistics import ( _fill_missing_statistics, _group_by_module, _ind...
19,540
34.723949
87
py
fvcore
fvcore-main/tests/test_giou_loss.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import unittest import numpy as np import torch from fvcore.nn import giou_loss class TestGIoULoss(unittest.TestCase): def setUp(self) -> None: super().setUp() np.random.seed(42) def test_giou_loss(self) -> None: ...
2,057
33.3
72
py
fvcore
fvcore-main/fvcore/nn/activation_count.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # pyre-ignore-all-errors[2,33] from collections import defaultdict from typing import Any, Counter, DefaultDict, Dict, Optional, Tuple, Union import torch.nn as nn from torch import Tensor from .jit_analysis import JitModelAnalysis from .jit_han...
4,577
35.919355
87
py
fvcore
fvcore-main/fvcore/nn/giou_loss.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch def giou_loss( boxes1: torch.Tensor, boxes2: torch.Tensor, reduction: str = "none", eps: float = 1e-7, ) -> torch.Tensor: """ Generalized Intersection over Union Loss (Hamid Rezatofighi et. al) https://ar...
2,042
30.921875
84
py