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 |
|---|---|---|---|---|---|---|
E-Att | E-Att-main/E-ATT.py | import torch
from torch import nn
from torch.nn.functional import softmax
from model.layer_norm import Identity, LayerNorm, UnlearnableLayerNorm
snn_threshold = 0.0
class MultiHeadSelfAttention(nn.Module):
def __init__(self,
emb_size: int, num_of_heads: int,
attention_dropout_p... | 14,029 | 46.239057 | 137 | py |
CRPropa3 | CRPropa3-master/doc/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | 6,401 | 28.232877 | 79 | py |
CurveNet | CurveNet-main/core/main_partseg.py | """
@Author: An Tao
@Contact: ta19@mails.tsinghua.edu.cn
@File: main_partseg.py
@Time: 2019/12/31 11:17 AM
Modified by
@Author: Tiange Xiang
@Contact: txia7609@uni.sydney.edu.au
@Time: 2021/01/21 3:10 PM
"""
from __future__ import print_function
import os
import argparse
import torch
import torch.nn as nn
import to... | 15,928 | 44.511429 | 128 | py |
CurveNet | CurveNet-main/core/main_cls.py | """
@Author: Yue Wang
@Contact: yuewangx@mit.edu
@File: main_cls.py
@Time: 2018/10/13 10:39 PM
Modified by
@Author: Tiange Xiang
@Contact: txia7609@uni.sydney.edu.au
@Time: 2021/01/21 3:10 PM
"""
from __future__ import print_function
import os
import argparse
import torch
import torch.nn as nn
import torch.nn.functi... | 9,057 | 37.544681 | 119 | py |
CurveNet | CurveNet-main/core/data.py | """
@Author: Yue Wang
@Contact: yuewangx@mit.edu
@File: data.py
@Time: 2018/10/13 6:21 PM
Modified by
@Author: Tiange Xiang
@Contact: txia7609@uni.sydney.edu.au
@Time: 2021/1/21 3:10 PM
"""
import os
import sys
import glob
import h5py
import numpy as np
import torch
from torch.utils.data import Dataset
# change t... | 7,145 | 35.459184 | 113 | py |
CurveNet | CurveNet-main/core/util.py | """
@Author: Yue Wang
@Contact: yuewangx@mit.edu
@File: util
@Time: 4/5/19 3:47 PM
"""
import numpy as np
import torch
import torch.nn.functional as F
def cal_loss(pred, gold, smoothing=True):
''' Calculate cross entropy loss, apply label smoothing if needed. '''
gold = gold.contiguous().view(-1)
if s... | 949 | 20.111111 | 75 | py |
CurveNet | CurveNet-main/core/main_normal.py | """
@Author: Tiange Xiang
@Contact: txia7609@uni.sydney.edu.au
@File: main_normal.py
@Time: 2021/01/21 3:10 PM
"""
from __future__ import print_function
import os
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import CosineA... | 8,255 | 37.943396 | 119 | py |
CurveNet | CurveNet-main/core/models/curvenet_seg.py | """
@Author: Tiange Xiang
@Contact: txia7609@uni.sydney.edu.au
@File: curvenet_seg.py
@Time: 2021/01/21 3:10 PM
"""
import torch.nn as nn
import torch.nn.functional as F
from .curvenet_util import *
curve_config = {
'default': [[100, 5], [100, 5], None, None, None]
}
class CurveNet(nn.Module):
def _... | 6,239 | 46.272727 | 165 | py |
CurveNet | CurveNet-main/core/models/curvenet_cls.py | """
@Author: Tiange Xiang
@Contact: txia7609@uni.sydney.edu.au
@File: curvenet_cls.py
@Time: 2021/01/21 3:10 PM
"""
import torch.nn as nn
import torch.nn.functional as F
from .curvenet_util import *
curve_config = {
'default': [[100, 5], [100, 5], None, None],
'long': [[10, 30], None, None, None]
... | 3,178 | 42.547945 | 177 | py |
CurveNet | CurveNet-main/core/models/curvenet_normal.py | """
@Author: Tiange Xiang
@Contact: txia7609@uni.sydney.edu.au
@File: curvenet_normal.py
@Time: 2021/01/21 3:10 PM
"""
import torch.nn as nn
import torch.nn.functional as F
from .curvenet_util import *
curve_config = {
'default': [[100, 5], [100, 5], None, None]
}
class CurveNet(nn.Module):
def __in... | 4,635 | 51.089888 | 174 | py |
CurveNet | CurveNet-main/core/models/curvenet_util.py | """
@Author: Yue Wang
@Contact: yuewangx@mit.edu
@File: pointnet_util.py
@Time: 2018/10/13 10:39 PM
Modified by
@Author: Tiange Xiang
@Contact: txia7609@uni.sydney.edu.au
@Time: 2021/01/21 3:10 PM
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from time import time
import numpy as np
from .w... | 16,637 | 33.02454 | 122 | py |
CurveNet | CurveNet-main/core/models/walk.py | """
@Author: Tiange Xiang
@Contact: txia7609@uni.sydney.edu.au
@File: walk.py
@Time: 2021/01/21 3:10 PM
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def batched_index_select(input, dim, index):
views = [input.shape[0]] + \
[1 if i != dim else -1 for i in range(1, len(i... | 5,859 | 36.324841 | 122 | py |
Counterfactuals-for-Sentiment-Analysis | Counterfactuals-for-Sentiment-Analysis-master/cfsa.py | import sys
import argparse
import logging
import os
from datetime import datetime
from pathlib import Path
import pandas as pd
import numpy as np
import torch
from transformers import *
from cfsa.constants import TRAIN_SET_URL, DICT_PATH, OUTPUT_PATH, models_dict
from cfsa.loader import dataset_loader, dict_loader... | 5,573 | 43.238095 | 188 | py |
Counterfactuals-for-Sentiment-Analysis | Counterfactuals-for-Sentiment-Analysis-master/cfsa/cfsa.py | import torch
import numpy as np
import pandas as pd
from pathlib import Path
from typing import Callable
from tqdm import tqdm
from cfsa.constants import delimeters, lc_delimeters, punctuation
from copy import deepcopy
import regex as re
class Cfsa:
def __init__(self, texts, labels, neg_proun, finetuned_model, ... | 3,324 | 36.784091 | 127 | py |
Counterfactuals-for-Sentiment-Analysis | Counterfactuals-for-Sentiment-Analysis-master/cfsa/cfsarm.py | import logging
import torch
import math
import numpy as np
import pandas as pd
from pathlib import Path
from typing import Callable
from tqdm import tqdm
from cfsa.cfsa import Cfsa
from cfsa.constants import masker_sets, delimeters, lc_delimeters
from copy import deepcopy
import regex as re
class Cfsarm(Cfsa):
... | 7,001 | 45.370861 | 110 | py |
Counterfactuals-for-Sentiment-Analysis | Counterfactuals-for-Sentiment-Analysis-master/cfsa/cfsarep.py | import logging
import torch
import numpy as np
import pandas as pd
from pathlib import Path
from typing import Callable
from tqdm import tqdm
from cfsa.cfsa import Cfsa
from cfsa.constants import masker_sets, delimeters, lc_delimeters, punctuation
from copy import deepcopy
import regex as re
class Cfsarep(Cfsa):
... | 10,636 | 51.142157 | 197 | py |
CondGauss | CondGauss-master/main.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from stochnet.network import GhostNet, StochNet
from stochnet.datasets import MNISTData, CIFAR10Data
import stochnet.tools as tools
from stochnet.tools import Print
import os, sys
from time import strftime
outpath = f'./StochNet_{strftime("%Y%m%d-%H... | 3,091 | 30.876289 | 209 | py |
CondGauss | CondGauss-master/stochnet/network.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
import dill, math, os
from time import strftime
from stochnet.tools import Print, inv_KL, invkl, gauss_ccdf, _mk_perm, save_lists, buf_to_par, par_to_buf, __OUT_DIR__, __EPS__, __SN_version__, __SN_comp_version... | 38,823 | 40.612004 | 316 | py |
CondGauss | CondGauss-master/stochnet/tools.py | import torch, os, dill
from math import sqrt
from scipy.special import xlogy
from torch.nn.parameter import Parameter
__SN_comp_version__ = [3.1, 'GH_1.0']
__SN_version__ = 'GH_1.0'
__EPS__ = torch.finfo(torch.float32).eps
__out_file__ = None
__term__ = True
__out_dir__ = './'
__OUT_DIR__ = lambda: __out_dir__
__OU... | 3,789 | 24.266667 | 133 | py |
CondGauss | CondGauss-master/stochnet/datasets.py | import torch
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST, CIFAR10
torch.manual_seed(0)
class MyData():
def make_loaders(self):
self.TrainLoader = DataLoader(self.TrainData, batch_size=self.train_batch_size, shuffle=True)
self.T... | 5,512 | 42.409449 | 193 | py |
waveglow | waveglow-master/inference.py | # *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions... | 3,995 | 46.011765 | 80 | py |
waveglow | waveglow-master/convert_model.py | import sys
import copy
import torch
def _check_model_old_version(model):
if hasattr(model.WN[0], 'res_layers') or hasattr(model.WN[0], 'cond_layers'):
return True
else:
return False
def _update_model_res_skip(old_model, new_model):
for idx in range(0, len(new_model.WN)):
wavenet =... | 3,228 | 41.486842 | 108 | py |
waveglow | waveglow-master/mel2samp.py | # *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions... | 5,861 | 39.993007 | 109 | py |
waveglow | waveglow-master/glow_old.py | import copy
import torch
from glow import Invertible1x1Conv, remove
@torch.jit.script
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
n_channels_int = n_channels[0]
in_act = input_a+input_b
t_act = torch.tanh(in_act[:, :n_channels_int, :])
s_act = torch.sigmoid(in_act[:, n_channels_... | 9,144 | 38.081197 | 90 | py |
waveglow | waveglow-master/glow.py | # *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions... | 12,653 | 39.557692 | 105 | py |
waveglow | waveglow-master/distributed.py | # *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions... | 7,429 | 39.162162 | 110 | py |
waveglow | waveglow-master/train.py | # *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions... | 8,049 | 41.592593 | 95 | py |
waveglow | waveglow-master/denoiser.py | import sys
sys.path.append('tacotron2')
import torch
from layers import STFT
class Denoiser(torch.nn.Module):
""" Removes model bias from audio produced with waveglow """
def __init__(self, waveglow, filter_length=1024, n_overlap=4,
win_length=1024, mode='zeros'):
super(Denoiser, sel... | 1,605 | 38.170732 | 77 | py |
SupContrast | SupContrast-master/losses.py | """
Author: Yonglong Tian (yonglong@mit.edu)
Date: May 07, 2020
"""
from __future__ import print_function
import torch
import torch.nn as nn
class SupConLoss(nn.Module):
"""Supervised Contrastive Learning: https://arxiv.org/pdf/2004.11362.pdf.
It also supports the unsupervised contrastive loss in SimCLR"""
... | 3,758 | 36.969697 | 80 | py |
SupContrast | SupContrast-master/main_ce.py | from __future__ import print_function
import os
import sys
import argparse
import time
import math
import tensorboard_logger as tb_logger
import torch
import torch.backends.cudnn as cudnn
from torchvision import transforms, datasets
from util import AverageMeter
from util import adjust_learning_rate, warmup_learning... | 11,274 | 32.757485 | 86 | py |
SupContrast | SupContrast-master/main_linear.py | from __future__ import print_function
import sys
import argparse
import time
import math
import torch
import torch.backends.cudnn as cudnn
from main_ce import set_loader
from util import AverageMeter
from util import adjust_learning_rate, warmup_learning_rate, accuracy
from util import set_optimizer
from networks.re... | 8,429 | 31.175573 | 79 | py |
SupContrast | SupContrast-master/util.py | from __future__ import print_function
import math
import numpy as np
import torch
import torch.optim as optim
class TwoCropTransform:
"""Create two crops of the same image"""
def __init__(self, transform):
self.transform = transform
def __call__(self, x):
return [self.transform(x), self.... | 2,681 | 26.9375 | 88 | py |
SupContrast | SupContrast-master/main_supcon.py | from __future__ import print_function
import os
import sys
import argparse
import time
import math
import tensorboard_logger as tb_logger
import torch
import torch.backends.cudnn as cudnn
from torchvision import transforms, datasets
from util import TwoCropTransform, AverageMeter
from util import adjust_learning_rat... | 10,525 | 34.441077 | 96 | py |
SupContrast | SupContrast-master/networks/resnet_big.py | """ResNet in PyTorch.
ImageNet-Style ResNet
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
Adapted from: https://github.com/bearpaw/pytorch-classification
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(n... | 7,218 | 33.37619 | 104 | py |
qDWI-Morph | qDWI-Morph-main/main.py | import os
import pandas as pd
# import voxelmorph with pytorch backend
os.environ['VXM_BACKEND'] = 'pytorch'
import voxelmorph as vxm # nopep8
import torch.nn as nn
import torchio as tio
import json
from config import config
from ExpFitGA_ADC import ADC_GA_corr
from plots import *
from torch.utils.tensorboard import ... | 13,299 | 34 | 120 | py |
qDWI-Morph | qDWI-Morph-main/plots.py | import os.path
import matplotlib.pyplot as plt
import torch
import numpy as np
def plotSlice(vol, slice, case, config, seg_vol=None, name=None, path=None):
fig, axes = plt.subplots(nrows=2, ncols=3, gridspec_kw={'wspace': 0, 'hspace': 0})
for ax, (i, bval) in zip(axes.flat, enumerate(config['b_vector'])):
... | 9,257 | 37.575 | 118 | py |
qDWI-Morph | qDWI-Morph-main/config.py | import os
os.environ['VXM_BACKEND'] = 'pytorch'
import voxelmorph as vxm
import torch
import ModelFitLoss
def config():
config = dict()
# general:
config['seed'] = 37
config['device'] = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
config['b_vector'] = torch.tensor([0, 50, 100, 200,... | 2,121 | 34.966102 | 106 | py |
qDWI-Morph | qDWI-Morph-main/ModelFitLoss.py | class ModelFit:
def loss(self, y, y_model, fit_mask):
y = y * fit_mask
y_model = y_model * fit_mask
eps = 1e-4
SS_res = (y_model - y).square().sum()
SS_tot = (y - y.mean()).square().sum()
N = fit_mask.sum((1, 2, 3))[0].item()
return (1 / (N + eps)) * (SS_res ... | 524 | 29.882353 | 58 | py |
LGR | LGR-main/semi_supervised/infomax.py | import torch
import math
import torch.nn.functional as F
# from cortex_DIM.functions.gan_losses import get_positive_expectation, get_negative_expectation
def log_sum_exp(x, axis=None):
"""Log sum exp function
Args:
x: Input.
axis: Axis over which to perform sum.
Returns:
torch.T... | 4,579 | 26.100592 | 96 | py |
LGR | LGR-main/semi_supervised/mean_teacher.py | from torch.nn import Sequential, Linear, ReLU, GRU
from torch_geometric.data import DataLoader
from torch_geometric.datasets import QM9
from torch_geometric.nn import NNConv, Set2Set
from torch_geometric.utils import remove_self_loops
import numpy as np
import os
import os.path as osp
import random
import sys
import to... | 7,059 | 34.656566 | 124 | py |
LGR | LGR-main/semi_supervised/model.py | import os.path as osp
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.nn import Sequential, Linear, ReLU, GRU, Conv2d
import torch_geometric.transforms as T
from torch_geometric.datasets import QM9
from torch_geometric.nn import NNCon... | 11,494 | 41.416974 | 124 | py |
LGR | LGR-main/semi_supervised/run.py | from torch.nn import Sequential, Linear, ReLU, GRU
from torch_geometric.data import DataLoader
from torch_geometric.datasets import QM9
from torch_geometric.nn import NNConv, Set2Set
from torch_geometric.utils import remove_self_loops
import numpy as np
import os
import os.path as osp
import random
import sys
import to... | 7,112 | 32.394366 | 124 | py |
LGR | LGR-main/unsupervised/base_neg_model.py | from torch.nn import Sequential, Linear, ReLU
from torch_geometric.data import DataLoader
from torch_geometric.datasets import TUDataset
from torch_geometric.nn import GINConv, global_add_pool, SAGPooling, GCNConv
from tqdm import tqdm
import numpy as np
import os.path as osp
import sys
import torch
import torch.nn.fun... | 10,856 | 43.863636 | 120 | py |
LGR | LGR-main/unsupervised/base_model.py | from torch.nn import Sequential, Linear, ReLU
from torch_geometric.data import DataLoader
from torch_geometric.datasets import TUDataset
from torch_geometric.nn import GINConv, global_add_pool, SAGPooling, GCNConv
from tqdm import tqdm
import numpy as np
import os.path as osp
import sys
import torch
import torch.nn.fun... | 10,740 | 43.020492 | 120 | py |
LGR | LGR-main/unsupervised/losses.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from cortex_DIM.functions.gan_losses import get_positive_expectation, get_negative_expectation
import numpy as np
import math, random
def global_global_loss_(pos_graph, sub_graph, neg_graph, measure='JSD'):
num_graphs = pos_graph.shape[0]
# nu... | 2,695 | 29.988506 | 96 | py |
LGR | LGR-main/unsupervised/test.py | import torch
import numpy as np
# from run import compute
import os
# from run import *
from tqdm import tqdm
from info_nce import InfoNCE
nce_loss = InfoNCE()
a = torch.tensor([0, 0, 0, 1, 1, 2, 2])
b = torch.rand(7, 10)
c = torch.rand(3, 10)
d = torch.rand(10, 10)
all_loss = 0
for i in range(a[-1] + 1):
all_loss... | 472 | 21.52381 | 61 | py |
LGR | LGR-main/unsupervised/utils.py | import torch
import torch.nn.functional as F
import numpy as np
import random
from torch_geometric.utils import degree, remove_self_loops
def move_to(data, device=None):
batch = data.batch.to(device)
edge_idx = data.edge_index.to(device)
if data.x is None:
node_attr = degree(edge_idx[0], batch.sha... | 1,364 | 32.292683 | 86 | py |
LGR | LGR-main/unsupervised/model.py | from torch.nn import Sequential, Linear, ReLU
from torch_geometric.data import DataLoader
from torch_geometric.datasets import TUDataset
from torch_geometric.nn import GINConv, global_add_pool, SAGPooling, GCNConv
from tqdm import tqdm
import numpy as np
import os.path as osp
import sys
import torch
import torch.nn.fun... | 10,820 | 42.633065 | 117 | py |
LGR | LGR-main/unsupervised/run.py | from torch import optim
from torch.autograd import Variable
from torch_geometric.data import DataLoader
from torch_geometric.datasets import TUDataset
import json, os
import numpy as np
import os.path as osp
import sys
import torch
from tqdm import tqdm
import torch.nn as nn
import torch.nn.functional as F
from argumen... | 6,998 | 40.170588 | 114 | py |
LGR | LGR-main/unsupervised/evaluate_embedding.py | from sklearn import preprocessing
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.manifold import TSNE
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV, KFo... | 7,012 | 34.598985 | 108 | py |
LGR | LGR-main/unsupervised/cortex_DIM/functions/gan_losses.py | """
"""
import math
import torch
import torch.nn.functional as F
from cortex_DIM.functions.misc import log_sum_exp
def raise_measure_error(measure):
supported_measures = ['GAN', 'JSD', 'X2', 'KL', 'RKL', 'DV', 'H2', 'W1']
raise NotImplementedError(
'Measure `{}` not supported. Supported: {}'.forma... | 2,359 | 23.842105 | 79 | py |
LGR | LGR-main/unsupervised/cortex_DIM/functions/dim_losses.py | '''cortex_DIM losses.
'''
import math
import torch
import torch.nn.functional as F
from cortex_DIM.functions.gan_losses import get_positive_expectation, get_negative_expectation
def fenchel_dual_loss(l, g, measure=None):
'''Computes the f-divergence distance between positive and negative joint distributions.
... | 5,584 | 23.933036 | 100 | py |
LGR | LGR-main/unsupervised/cortex_DIM/functions/misc.py | """Miscilaneous functions.
"""
import torch
def log_sum_exp(x, axis=None):
"""Log sum exp function
Args:
x: Input.
axis: Axis over which to perform sum.
Returns:
torch.Tensor: log sum exp
"""
x_max = torch.max(x, axis)[0]
y = torch.log((torch.exp(x - x_max)).sum(ax... | 690 | 16.275 | 59 | py |
LGR | LGR-main/unsupervised/cortex_DIM/nn_modules/resnet.py | '''Module for making resnet encoders.
'''
import torch
import torch.nn as nn
from cortex_DIM.nn_modules.convnet import Convnet
from cortex_DIM.nn_modules.misc import Fold, Unfold, View
_nonlin_idx = 6
class ResBlock(Convnet):
'''Residual block for ResNet
'''
def create_layers(self, shape, conv_args... | 9,013 | 29.248322 | 112 | py |
LGR | LGR-main/unsupervised/cortex_DIM/nn_modules/misc.py | '''Various miscellaneous modules
'''
import torch
class View(torch.nn.Module):
"""Basic reshape module.
"""
def __init__(self, *shape):
"""
Args:
*shape: Input shape.
"""
super().__init__()
self.shape = shape
def forward(self, input):
""... | 2,943 | 21.473282 | 101 | py |
LGR | LGR-main/unsupervised/cortex_DIM/nn_modules/encoder.py | '''Basic cortex_DIM encoder.
'''
import torch
from cortex_DIM.nn_modules.convnet import Convnet, FoldedConvnet
from cortex_DIM.nn_modules.resnet import ResNet, FoldedResNet
def create_encoder(Module):
class Encoder(Module):
'''Encoder used for cortex_DIM.
'''
def __init__(self, *args,... | 2,663 | 26.463918 | 104 | py |
LGR | LGR-main/unsupervised/cortex_DIM/nn_modules/convnet.py | '''Convnet encoder module.
'''
import torch
import torch.nn as nn
#from cortex.built_ins.networks.utils import get_nonlinearity
from cortex_DIM.nn_modules.misc import Fold, Unfold, View
def infer_conv_size(w, k, s, p):
'''Infers the next size after convolution.
Args:
w: Input size.
k: Ker... | 10,432 | 28.555241 | 107 | py |
LGR | LGR-main/unsupervised/cortex_DIM/nn_modules/mi_networks.py | """Module for networks used for computing MI.
"""
import numpy as np
import torch
import torch.nn as nn
from cortex_DIM.nn_modules.misc import Permute
class MIFCNet(nn.Module):
"""Simple custom network for computing MI.
"""
def __init__(self, n_input, n_units):
"""
Args:
n... | 2,829 | 25.448598 | 88 | py |
auto-discern | auto-discern-master/setup.py | from setuptools import setup
setup(name='autodiscern',
version='0.0.2',
description='',
url='https://github.com/CMI-UZH/auto-discern',
packages=['autodiscern', 'autodiscern.experiments', 'autodiscern.predictors'],
package_data={'autodiscern': ['package_data/*']},
python_requires='>3... | 857 | 27.6 | 84 | py |
auto-discern | auto-discern-master/neural/neural_discern_run_script.py | #!/usr/bin/env python
# coding: utf-8
# % load_ext autoreload
# % autoreload 2
import torch.multiprocessing as mp
import argparse
import os
import datetime
import pandas as pd
import torch
from pytorch_pretrained_bert import BertModel, BertForPreTraining, BertConfig
from neural.data_processor import DataDictProcess... | 17,558 | 47.775 | 120 | py |
auto-discern | auto-discern-master/neural/model.py | import os
from .utilities import get_device, ReaderWriter
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence
class Attention(nn.Module):
def __init__(self, attn_method, input_dim, nonlinear_func=torch.tanh, config={}, to_gpu=True, gpu_index=0):
'''
Args:
... | 24,409 | 42.511586 | 119 | py |
auto-discern | auto-discern-master/neural/data_processor.py | from copy import deepcopy
import numpy as np
import torch
from torch.nn.utils.rnn import pad_sequence
from .dataset import DocDataTensor
class DataDictProcessor(object):
def __init__(self, config):
'''
Args
config: dict, specifying options
- torch_device: instance of to... | 9,132 | 44.665 | 120 | py |
auto-discern | auto-discern-master/neural/dataset.py | import os
import numpy as np
import torch
from .utilities import ModelScore
from torch.utils.data import Dataset, DataLoader
from sklearn.model_selection import StratifiedKFold, StratifiedShuffleSplit
from sklearn.utils.class_weight import compute_class_weight
class DocDataTensor(Dataset):
def __init__(self, doc... | 12,713 | 44.898917 | 119 | py |
auto-discern | auto-discern-master/neural/predict_with_neural.py | import numpy as np
import os
import pkg_resources
import pandas as pd
from pytorch_pretrained_bert import BertTokenizer
import requests
import torch
import autodiscern.transformations as adt
from neural.data_processor import DataDictProcessor
from neural.dataset import generate_docpartition_per_question
from neural.mo... | 14,261 | 41.195266 | 120 | py |
auto-discern | auto-discern-master/neural/utilities.py | import os
import shutil
import pickle
import torch
import numpy as np
from sklearn.metrics import classification_report, f1_score, roc_curve, precision_recall_curve, accuracy_score
from matplotlib import pyplot as plt
class ModelScore:
def __init__(self, best_epoch_indx, micro_f1, macro_f1, accuracy, auc):
... | 7,849 | 33.581498 | 114 | py |
auto-discern | auto-discern-master/neural/run_workflow.py | import os
import itertools
from .utilities import get_device, create_directory, ReaderWriter, perfmetric_report, plot_loss
from .model import Attention, SentenceEncoder, DocEncoder, DocEncoder_MeanPooling, DocCategScorer, BertEmbedder,\
restrict_grad_
from .dataset import construct_load_dataloaders
import numpy as ... | 43,763 | 48.845103 | 119 | py |
ceecnet | ceecnet-master/nn/pooling/psp_pooling.py | from mxnet import gluon
from mxnet.gluon import HybridBlock
from ceecnet.nn.layers.conv2Dnormed import *
class PSP_Pooling(gluon.HybridBlock):
def __init__(self, nfilters, depth=4, _norm_type = 'BatchNorm', norm_groups=None, mob=False, **kwards):
gluon.HybridBlock.__init__(self,**kwards)
... | 3,055 | 31.510638 | 139 | py |
ceecnet | ceecnet-master/nn/layers/conv2Dnormed.py | import mxnet as mx
from mxnet import gluon
from mxnet.gluon import HybridBlock
from ceecnet.utils.get_norm import *
class Conv2DNormed(HybridBlock):
"""
Convenience wrapper layer for 2D convolution followed by a normalization layer
All other keywords are the same as gluon.nn.Conv2D
"""
... | 1,442 | 36.973684 | 132 | py |
ceecnet | ceecnet-master/nn/layers/scale.py | from mxnet import gluon
from mxnet.gluon import HybridBlock
from ceecnet.nn.layers.conv2Dnormed import *
from ceecnet.utils.get_norm import *
class DownSample(HybridBlock):
def __init__(self, nfilters, factor=2, _norm_type='BatchNorm', norm_groups=None, **kwargs):
super().__init__(**kwargs)
... | 1,732 | 29.946429 | 97 | py |
ceecnet | ceecnet-master/nn/layers/combine.py | from mxnet import gluon
from mxnet.gluon import HybridBlock
from ceecnet.nn.layers.scale import *
from ceecnet.nn.layers.conv2Dnormed import *
"""
For combining layers with Fusion (i.e. relative attention), see ../units/ceecnet.py
"""
class combine_layers(HybridBlock):
def __init__(self,_nfilters, _norm_type ... | 1,206 | 27.738095 | 92 | py |
ceecnet | ceecnet-master/nn/layers/ftnmt.py | from mxnet.gluon import HybridBlock
class FTanimoto(HybridBlock):
"""
This is the average fractal Tanimoto set similarity with complement.
"""
def __init__(self, depth=5, smooth=1.0e-5, axis=[2,3],**kwards):
super().__init__(**kwards)
assert depth >= 0, "Expecting depth >= 0,... | 1,413 | 24.709091 | 92 | py |
ceecnet | ceecnet-master/nn/layers/attention.py | from mxnet import gluon
from mxnet.gluon import HybridBlock
from ceecnet.nn.layers.conv2Dnormed import *
from ceecnet.nn.layers.ftnmt import *
class RelFTAttention2D(HybridBlock):
def __init__(self, nkeys, kernel_size=3, padding=1,nheads=1, norm = 'BatchNorm', norm_groups=None,ftdepth=5,**kwards):
... | 2,279 | 34.076923 | 173 | py |
ceecnet | ceecnet-master/nn/units/ceecnet.py | from mxnet import gluon
from mxnet.gluon import HybridBlock
from ceecnet.nn.layers.conv2Dnormed import *
from ceecnet.utils.get_norm import *
from ceecnet.nn.layers.attention import *
class ResizeLayer(HybridBlock):
"""
Applies bilinear up/down sampling in spatial dims and changes number of filters as well
... | 16,072 | 44.661932 | 186 | py |
ceecnet | ceecnet-master/nn/units/fractal_resnet.py | from mxnet import gluon
from mxnet.gluon import HybridBlock
from ceecnet.nn.layers.conv2Dnormed import *
from ceecnet.utils.get_norm import *
from ceecnet.nn.layers.attention import *
class ResNet_v2_block(HybridBlock):
"""
ResNet v2 building block. It is built upon the assumption of ODD kernel
"""
de... | 2,481 | 37.184615 | 157 | py |
ceecnet | ceecnet-master/nn/loss/ftnmt_loss.py | """
Fractal Tanimoto (with dual) loss
"""
from mxnet.gluon.loss import Loss
class ftnmt_loss(Loss):
"""
This function calculates the average fractal tanimoto similarity for d ... | 1,989 | 31.622951 | 168 | py |
ceecnet | ceecnet-master/nn/activations/sigmoid_crisp.py | from mxnet.gluon import HybridBlock
import mxnet as mx
class SigmoidCrisp(HybridBlock):
def __init__(self, smooth=1.e-2,**kwards):
super().__init__(**kwards)
self.smooth = smooth
with self.name_scope():
self.gamma = self.params.get('gamma', shape=(1,), init=mx.init.One())
... | 558 | 21.36 | 82 | py |
ceecnet | ceecnet-master/src/LVRCDDataset.py | """
DataSet reader for the LEVIRCD dataset.
"""
import numpy as np
import glob
from mxnet.gluon.data import dataset
import cv2
import mxnet as mx
import pickle
class LVRCDDataset(dataset.Dataset):
def __init__(self, root=r'/Location/Of/Your/LEVIRCD/Files/', mode='train', mtsk = True, transform=None, norm=None... | 4,793 | 34.776119 | 181 | py |
ceecnet | ceecnet-master/models/semanticsegmentation/x_unet/x_dn_features.py | from mxnet import gluon
from mxnet.gluon import HybridBlock
from ceecnet.nn.layers.conv2Dnormed import *
from ceecnet.nn.layers.attention import *
from ceecnet.nn.pooling.psp_pooling import *
from ceecnet.nn.layers.scale import *
from ceecnet.nn.layers.combine import *
# CEEC units
from ceecnet.nn.units.ceecnet i... | 5,929 | 44.615385 | 196 | py |
ceecnet | ceecnet-master/models/changedetection/mantis/mantis_dn_features.py | from mxnet import gluon
from mxnet.gluon import HybridBlock
from ceecnet.nn.layers.conv2Dnormed import *
from ceecnet.nn.layers.attention import *
from ceecnet.nn.pooling.psp_pooling import *
from ceecnet.nn.layers.scale import *
from ceecnet.nn.layers.combine import *
# CEEC units
from ceecnet.nn.units.ceecnet i... | 6,432 | 44.624113 | 196 | py |
ceecnet | ceecnet-master/models/heads/head_cmtsk.py | from mxnet import gluon
from mxnet.gluon import HybridBlock
from ceecnet.nn.activations.sigmoid_crisp import *
from ceecnet.nn.pooling.psp_pooling import *
from ceecnet.nn.layers.conv2Dnormed import *
# Helper classification head, for a single layer output
class HeadSingle(HybridBlock):
def __init__(self, nfil... | 3,982 | 35.209091 | 148 | py |
ceecnet | ceecnet-master/chopchop/chopchop2rec.py | # ============================== Helper Functions ==================================
# Helper functions to create boundary and distance transform
# ground trouth label in 1hot format
import cv2
import glob
import numpy as np
def get_boundary(labels, _kernel_size = (3,3)):
label = labels.copy()
for channel ... | 7,609 | 34.7277 | 147 | py |
ceecnet | ceecnet-master/utils/get_norm.py | import mxnet as mx
from mxnet import gluon
def get_norm(name, axis=1, norm_groups=None):
if (name == 'BatchNorm'):
return gluon.nn.BatchNorm(axis=axis)
elif (name == 'InstanceNorm'):
return gluon.nn.InstanceNorm(axis=axis)
elif (n... | 613 | 39.933333 | 86 | py |
RMDL | RMDL-master/setup.py | import io
import os
import numpy
from setuptools import Extension
from setuptools import setup, find_packages
from os import path
__author__ = 'Kamran Kowsari'
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
def readfile(file):
with open(path.join(here, file)) as f... | 1,688 | 27.627119 | 85 | py |
RMDL | RMDL-master/RMDL/BuildModel.py | """""""""""""""""""""""""""""""""""""""""""""""""""""""""""
RMDL: Random Multimodel Deep Learning for Classification
* Copyright (C) 2018 Kamran Kowsari <kk7nc@virginia.edu>
* Last Update: Oct 26, 2018
* This file is part of RMDL project, University of Virginia.
* Free to use, change, share and distribute source cod... | 17,723 | 39.651376 | 126 | py |
RMDL | RMDL-master/RMDL/RMDL_Image.py | """""""""""""""""""""""""""""""""""""""""""""""""""""""""""
RMDL: Random Multimodel Deep Learning for Classification
* Copyright (C) 2018 Kamran Kowsari <kk7nc@virginia.edu>
* Last Update: Oct 26, 2018
* This file is part of RMDL project, University of Virginia.
* Free to use, change, share and distribute source cod... | 15,997 | 49.466877 | 238 | py |
RMDL | RMDL-master/RMDL/text_feature_extraction.py | """""""""""""""""""""""""""""""""""""""""""""""""""""""""""
RMDL: Random Multimodel Deep Learning for Classification
* Copyright (C) 2018 Kamran Kowsari <kk7nc@virginia.edu>
* Last Update: Oct 26, 2018
* This file is part of RMDL project, University of Virginia.
* Free to use, change, share and distribute source cod... | 5,209 | 36.214286 | 104 | py |
RMDL | RMDL-master/RMDL/RMDL_Text.py | """""""""""""""""""""""""""""""""""""""""""""""""""""""""""
RMDL: Random Multimodel Deep Learning for Classification
* Copyright (C) 2018 Kamran Kowsari <kk7nc@virginia.edu>
* Last Update: Oct 26, 2018
* This file is part of RMDL project, University of Virginia.
* Free to use, change, share and distribute source cod... | 20,094 | 45.301843 | 234 | py |
RMDL | RMDL-master/Examples/Text_classification_demo.py | """""""""""""""""""""""""""""""""""""""""""""""""""""""""""
RMDL: Random Multimodel Deep Learning for Classification
* Copyright (C) 2018 Kamran Kowsari <kk7nc@virginia.edu>
* Last Update: Oct 26, 2018
* This file is part of RMDL project, University of Virginia.
* Free to use, change, share and distribute source cod... | 3,773 | 41.886364 | 1,095 | py |
RMDL | RMDL-master/Examples/CIFAR.py | '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
RMDL: Random Multimodel Deep Learning for Classification
* Copyright (C) 2018 Kamran Kowsari <kk7nc@virginia.edu>
* Last Update: May 3rd, 2018
* This file is part of RMDL project, University of Virginia.
* Free to use, change, share and distribute... | 1,310 | 36.457143 | 103 | py |
RMDL | RMDL-master/Examples/IMDB.py | """""""""""""""""""""""""""""""""""""""""""""""""""""""""""
RMDL: Random Multimodel Deep Learning for Classification
* Copyright (C) 2018 Kamran Kowsari <kk7nc@virginia.edu>
* Last Update: Oct 26, 2018
* This file is part of RMDL project, University of Virginia.
* Free to use, change, share and distribute source cod... | 1,962 | 39.895833 | 102 | py |
RMDL | RMDL-master/Examples/MNIST.py | """""""""""""""""""""""""""""""""""""""""""""""""""""""""""
RMDL: Random Multimodel Deep Learning for Classification
* Copyright (C) 2018 Kamran Kowsari <kk7nc@virginia.edu>
* Last Update: Oct 26, 2018
* This file is part of RMDL project, University of Virginia.
* Free to use, change, share and distribute source cod... | 1,643 | 40.1 | 102 | py |
healthy-data-diet | healthy-data-diet-main/main.py | # Main script for gathering args.
from model.metrics import assess_performance_and_bias
from argparse import ArgumentParser
from analysis import analyze_results
import numpy as np
import zipfile
from transformers import TrainingArguments, Trainer
from transformers import EarlyStoppingCallback
from pathlib import Path
i... | 15,504 | 30.772541 | 274 | py |
healthy-data-diet | healthy-data-diet-main/load_model.py | from model.metrics import assess_performance_and_bias
from main import parse_args
import torch
import numpy as np
from model.data_loader import data_loader
from transformers import BertForSequenceClassification, RobertaForSequenceClassification
from analysis import analyze_results
from pathlib import Path
import wandb
... | 4,470 | 30.265734 | 88 | py |
healthy-data-diet | healthy-data-diet-main/utils.py | import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from transformers import BertForSequenceClassification, RobertaForSequenceClassification
import torch
import numpy as np
import... | 15,683 | 36.792771 | 288 | py |
healthy-data-diet | healthy-data-diet-main/importance_scores.py | from transformers import BertForSequenceClassification, RobertaForSequenceClassification
import torch
import numpy as np
import os
from torch.optim import Adam
import torch.nn as nn
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
softmax = torch.nn.Softmax(dim=1).to(device)
def compute_GraNd(
... | 17,376 | 38.225734 | 153 | py |
healthy-data-diet | healthy-data-diet-main/analysis.py | from utils import compute_confidence_and_variability
import pandas as pd
from transformers import BertForSequenceClassification, RobertaForSequenceClassification
from transformers import BertTokenizer, RobertaTokenizer
import torch
import re
import numpy as np
from pathlib import Path
from model.data_loader import data... | 16,481 | 38.149644 | 166 | py |
healthy-data-diet | healthy-data-diet-main/model/data_loader.py | import pandas as pd
import random
from transformers import BertTokenizer, RobertaTokenizer
import torch
import numpy as np
# Create torch dataset
class Dataset(torch.utils.data.Dataset):
def __init__(
self,
encodings,
encodings_gender_swap=None,
encodings_gender_blind=None,
... | 22,450 | 39.091071 | 213 | py |
healthy-data-diet | healthy-data-diet-main/model/classifier.py | from transformers import TrainingArguments, Trainer
from transformers import BertForSequenceClassification, RobertaForSequenceClassification
from transformers import EarlyStoppingCallback
from model.data_loader import data_loader
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def... | 4,074 | 35.061947 | 130 | py |
healthy-data-diet | healthy-data-diet-main/model/metrics.py | from transformers import BertForSequenceClassification, RobertaForSequenceClassification
from model.data_loader import data_loader
from sklearn.metrics import roc_auc_score
from pathlib import Path
import torch
import json
import numpy as np
import torch.nn.functional as F
import pandas as pd
import wandb
import re
de... | 31,186 | 38.228931 | 171 | py |
USID | USID-master/docs/source/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | 14,703 | 32.042697 | 101 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.