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
StreamingTransformer
StreamingTransformer-master/espnet/utils/dataset.py
#!/usr/bin/env python # Copyright 2017 Johns Hopkins University (Shinji Watanabe) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """pytorch dataset and dataloader implementation for chainer training.""" import torch import torch.utils.data class TransformDataset(torch.utils.data.Dataset): """Transf...
2,561
26.548387
80
py
StreamingTransformer
StreamingTransformer-master/espnet/utils/fill_missing_args.py
# -*- coding: utf-8 -*- # Copyright 2018 Nagoya University (Tomoki Hayashi) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import argparse import logging def fill_missing_args(args, add_arguments): """Fill missing arguments in args. Args: args (Namespace or None): Namesapce containing ...
1,426
29.361702
84
py
StreamingTransformer
StreamingTransformer-master/espnet/utils/deterministic_utils.py
import logging import torch def set_deterministic_pytorch(args): """Ensures pytorch produces deterministic results depending on the program arguments :param Namespace args: The program arguments """ # seed setting torch.manual_seed(args.seed) # debug mode setting # 0 would be fastest, bu...
869
30.071429
88
py
StreamingTransformer
StreamingTransformer-master/espnet/transform/spec_augment.py
"""Spec Augment module for preprocessing i.e., data augmentation""" import random import numpy from PIL import Image from PIL.Image import BICUBIC from espnet.transform.functional import FuncTrans def time_warp(x, max_time_warp=80, inplace=False, mode="PIL"): """time warp for spec augment move random cent...
5,924
28.187192
88
py
StreamingTransformer
StreamingTransformer-master/utils/average_checkpoints.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import json import os import numpy as np def main(): if args.log is not None: with open(args.log) as f: logs = json.load(f) val_scores = [] for log in logs: if "validation/main/acc" in log.keys(): ...
2,516
30.074074
81
py
combo
combo-master/examples/classifier_multiple_libs_example.py
# -*- coding: utf-8 -*- """Example of combining the models from different ML libraries. The example shows the combination of scikit-learn, xgboost, and LightGBM models. """ # Author: Yue Zhao <zhaoy@cmu.edu> # License: BSD 2 clause import os import sys # temporary solution for relative imports in case combo is not ...
2,531
35.695652
76
py
CodeGen
CodeGen-main/codegen2/sample.py
from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("checkpoints/codegen2-6B") model = CodeGenForCausalLM.from_pretrained("checkpoints/codegen2-6B", torch_dtype=torch.float16, revision="sharded") inputs = tokenizer("# this function prints hello world", return_tensors=...
466
57.375
116
py
CodeGen
CodeGen-main/codegen1/jaxformer/hf/sample.py
# Copyright (c) 2022, salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause import os import re import time import random import argparse import torch from transformers import ...
6,949
26.254902
224
py
CodeGen
CodeGen-main/codegen1/jaxformer/hf/train_deepspeed.py
# Minimal example of training the 16B checkpoint on GPU with CPU offloading using deepspeed. ''' apt install python3.8 python3.8-venv python3.8-dev python3.8 -m venv .venv source .venv/bin/activate pip install --upgrade pip setuptools pip install torch --extra-index-url https://download.pytorch.org/whl/cu113 pip inst...
5,560
26.666667
452
py
CodeGen
CodeGen-main/codegen1/jaxformer/hf/codegen/modeling_codegen.py
# coding=utf-8 # Copyright 2021 The EleutherAI and HuggingFace Teams. 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 #...
27,568
38.955072
160
py
CodeGen
CodeGen-main/codegen1/benchmark/mtpb_sample.py
# Copyright (c) 2022, salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ python3.9 -m venv .venv source .venv/bin/activate pip3 install --upgrade pip pip3 install --upgrad...
11,246
28.912234
209
py
HTRbyMatching
HTRbyMatching-main/htr_utils.py
import torch from tqdm import tqdm from torchvision.transforms import functional as Fsupp import os import numpy as np from configs import getOptions from PIL import Image, ImageFont, ImageDraw, ImageEnhance import editdistance import random options = getOptions().parse() alphabet_path = options.alphabet resizing = ...
8,610
28.489726
146
py
HTRbyMatching
HTRbyMatching-main/test.py
import torch import torchvision from src.faster_rcnn import FastRCNNPredictor ,TwoMLPHead import torchvision from src.faster_rcnn import FasterRCNN from src.rpn import AnchorGenerator import torchvision import src.transforms as T import cv2 import os import random import numpy as np from configs import getOptions ...
4,237
28.227586
113
py
HTRbyMatching
HTRbyMatching-main/train_progressive.py
import os import random import numpy as np import PIL import torch from PIL import Image import pickle from torch import nn import torchvision from src.faster_rcnn import FastRCNNPredictor ,TwoMLPHead import torchvision from src.faster_rcnn import FasterRCNN from src.rpn import AnchorGenerator from torchvision.tra...
26,067
29.77686
200
py
HTRbyMatching
HTRbyMatching-main/utils.py
from __future__ import print_function from collections import defaultdict, deque import datetime import pickle import time import torch import torch.distributed as dist import errno import os class SmoothedValue(object): """Track a series of values and provide access to smoothed values over a window or the...
9,162
28.36859
94
py
HTRbyMatching
HTRbyMatching-main/load_data.py
from PIL import Image import os import torch import sys import cv2 import transforms as T import torchvision.transforms as torchT import torchvision.transforms.functional as TF import utils from configs import getOptions import random options = getOptions().parse() cipher = options.cipher #"synthetic"# alphabet = o...
6,895
37.311111
167
py
HTRbyMatching
HTRbyMatching-main/train.py
import torch import torchvision from src.faster_rcnn import FastRCNNPredictor ,TwoMLPHead import torchvision from src.faster_rcnn import FasterRCNN from src.rpn import AnchorGenerator import torchvision from src.engine import train_one_epoch import os from load_data import load_data from configs import getOptions imp...
4,100
25.62987
90
py
HTRbyMatching
HTRbyMatching-main/transforms.py
import random import torch from torchvision.transforms import functional as F def _flip_coco_person_keypoints(kps, width): flip_inds = [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15] flipped_data = kps[:, flip_inds] flipped_data[..., 0] = width - flipped_data[..., 0] # Maintain COCO conven...
1,534
29.098039
74
py
HTRbyMatching
HTRbyMatching-main/src/engine.py
import math import sys import time import torch import torchvision.models.detection.mask_rcnn from .coco_utils import get_coco_api_from_dataset from src.coco_eval import CocoEvaluator import src.utils import utils def train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq): model.train() me...
3,989
34.625
97
py
HTRbyMatching
HTRbyMatching-main/src/util_fc.py
from PIL import Image, ImageFont, ImageDraw, ImageEnhance import numpy as np import os import PIL import torch def drawprobs(img1,shots,st_ch,en_ch): mat_size = 100 image_hline = Image.new('RGB', (img1.size()[2]+5+mat_size, 5), (0, 0, 255)) image1 = Image.fromarray(img1.mul(255).permute(1, 2, ...
2,944
35.358025
146
py
HTRbyMatching
HTRbyMatching-main/src/faster_rcnn.py
from collections import OrderedDict import torch from torch import nn import torch.nn.functional as F from torchvision.ops import misc as misc_nn_ops from torchvision.ops import MultiScaleRoIAlign from torchvision.models.utils import load_state_dict_from_url from .generalized_rcnn import GeneralizedRCNN from .rpn i...
16,622
44.667582
112
py
HTRbyMatching
HTRbyMatching-main/src/generalized_rcnn.py
""" Implements the Generalized R-CNN framework """ from collections import OrderedDict import torch from torch import nn class GeneralizedRCNN(nn.Module): """ Main class for Generalized R-CNN. Arguments: backbone (nn.Module): rpn (nn.Module): heads (nn.Module): takes the features...
2,562
31.858974
134
py
HTRbyMatching
HTRbyMatching-main/src/utils.py
from __future__ import print_function from collections import defaultdict, deque import datetime import pickle import time import torch import torch.distributed as dist import errno import os class SmoothedValue(object): """Track a series of values and provide access to smoothed values over a window or the...
9,161
28.459807
94
py
HTRbyMatching
HTRbyMatching-main/src/rpn.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from torch.nn import functional as F from torch import nn from torchvision.ops import boxes as box_ops from torchvision.models.detection import _utils as det_utils class AnchorGenerator(nn.Module): """ Module that generates...
17,453
39.21659
111
py
HTRbyMatching
HTRbyMatching-main/src/roi_heads.py
import torch import torch.nn.functional as F from torch import nn from torchvision.ops import boxes as box_ops from torchvision.ops import misc as misc_nn_ops from torchvision.ops import roi_align from torchvision.models.detection import _utils as det_utils def contrastive_loss_torch(y_pred, y_gt): ...
24,437
35.150888
165
py
HTRbyMatching
HTRbyMatching-main/src/coco_utils.py
import copy import os from PIL import Image import torch import torch.utils.data import torchvision from pycocotools import mask as coco_mask from pycocotools.coco import COCO import src.transforms as T class FilterAndRemapCocoCategories(object): def __init__(self, categories, remap=True): self.categor...
8,736
33.670635
102
py
HTRbyMatching
HTRbyMatching-main/src/coco_eval.py
import json import tempfile import numpy as np import copy import time import torch import torch._six from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from collections import defaultdict import src.utils class CocoEvaluator(object): def __init__(...
11,988
33.254286
107
py
HTRbyMatching
HTRbyMatching-main/src/transforms.py
import random import torch from torchvision.transforms import functional as F def _flip_coco_person_keypoints(kps, width): flip_inds = [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15] flipped_data = kps[:, flip_inds] flipped_data[..., 0] = width - flipped_data[..., 0] # Maintain COCO conven...
1,534
29.098039
74
py
personalized-breath
personalized-breath-master/src/main.py
import os import argparse import pickle import torch import numpy as np import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from torch.optim.lr_scheduler import StepLR from matplotlib import pyplot as plt from training.trainer import train, test, EarlyStopping from utils.process_d...
9,351
48.481481
227
py
personalized-breath
personalized-breath-master/src/evaluation/verification_one_vs_all.py
import numpy as np from scipy.optimize import brentq from scipy.interpolate import interp1d from sklearn.metrics import roc_curve from scipy.spatial import distance from sklearn.mixture import GaussianMixture import torch import torch.nn as nn def get_predicted_set(loader, models): Y_true, Y_out=[],[] for batc...
2,206
37.051724
82
py
personalized-breath
personalized-breath-master/src/evaluation/verification.py
import numpy as np from scipy.optimize import brentq from scipy.interpolate import interp1d from sklearn.metrics import roc_curve from scipy.spatial import distance from sklearn.mixture import GaussianMixture import torch def get_embedded_set(loader,model): X_out, Y_out=[],[] for batch_idx, (types, samples,lab...
3,076
35.630952
71
py
personalized-breath
personalized-breath-master/src/evaluation/plot_tsne.py
import os import numpy as np import pickle import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from torch.utils.data import Dataset, DataLoader from matplotlib import pyplot as plt import random from scipy.optimize import brentq from scipy.interpolate import interp1d from ...
2,836
40.720588
139
py
personalized-breath
personalized-breath-master/src/training/dataloader.py
import numpy as np from torch.utils.data import Dataset class Audio_Dataset(Dataset): def __init__(self,root_dir,filenamelist,old_new_name_map, object_id = None): self.filenamelist = filenamelist self.root_dir=root_dir self.old_new_name_map=old_new_name_map self.type_name = "Audio" ...
3,469
37.555556
111
py
personalized-breath
personalized-breath-master/src/training/trainer.py
import torch import numpy as np import torch.nn as nn from torch.autograd import Variable from utils.plot_grad_flow import plot_grad_flow class EarlyStopping: def __init__(self, checkpoint_name, lr_scheduler, patiences=[], delta=0): self.checkpoint_name = checkpoint_name self.lr_scheduler = lr_sche...
4,129
34.913043
77
py
personalized-breath
personalized-breath-master/src/modeling/triplet_tristou.py
import os import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import PackedSequence from torch.nn.utils.rnn import pad_packed_sequence from torch.autograd import Variable from torch.utils.data import Dataset, DataLoader from sklearn.neighbors impor...
22,819
45.288032
160
py
personalized-breath
personalized-breath-master/src/modeling/cnn_lstm.py
import numpy as np import torch import torch.nn as nn class Audio_CNN_LSTM(nn.Module): def __init__(self,no_outer,one_vs_all = False): super(Audio_CNN_LSTM, self).__init__() self.audio_layers = nn.Sequential( nn.Conv1d(in_channels=20, out_channels=32, kernel_size=8), nn.ReLU...
3,080
37.5125
76
py
personalized-breath
personalized-breath-master/src/modeling/tcn.py
import numpy as np import torch import torch.nn as nn from torch.nn.utils import weight_norm class Chomp1d(nn.Module): def __init__(self, chomp_size): super(Chomp1d, self).__init__() self.chomp_size = chomp_size def forward(self, x): return x[:, :, :-self.chomp_size].contiguous() clas...
4,753
44.27619
142
py
BachProp
BachProp-master/src/BachProp.py
import utils import numpy as np import pickle from tqdm import tqdm import os, sys from sys import stdout import keras from keras.utils import np_utils from keras.preprocessing.sequence import pad_sequences from keras.models import Model, load_model from keras.layers import Input, Masking, TimeDistributed, Dense, Con...
34,032
43.721419
183
py
Cophy-PGNN
Cophy-PGNN-master/loss_surface_vis/helper_electromagnetic.py
import numpy as np import matplotlib.pyplot as plt import torch import pandas as pd import torch.nn.functional as f import sys import os sys.path.append(os.path.abspath('../loss_surface_vis')) sys.path.append(os.path.abspath('../scripts')) from loss_functions_electromagnetic import multiply_Eg_C # Calculates | HC - E...
5,641
37.121622
122
py
Cophy-PGNN
Cophy-PGNN-master/loss_surface_vis/loss_functions.py
import torch from math import sqrt def inverse_norm(batch, scale, mean): return batch * scale + mean def phy_loss(batchPred, batchReal, batchInput, norm=False): num_data = batchPred.size(0) if batchInput.dim() == 2: H_height = int(sqrt(batchInput.size(1))) H_width = H_height elif batch...
2,025
31.15873
94
py
Cophy-PGNN
Cophy-PGNN-master/loss_surface_vis/data_loader.py
import torch import numpy as np from torch.autograd import Variable from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler import os # restore hamiltonian from nonzeros def restore_h(nonzero, nonzero_loc, dim): data_count = nonzero.shape[0] H = torch.zeros((data_count...
15,995
38.399015
108
py
Cophy-PGNN
Cophy-PGNN-master/loss_surface_vis/helper.py
import numpy as np import matplotlib.pyplot as plt import torch from scipy import interp def getFriendlyName(DNN_type): name = "NN" if DNN_type == "PGNN_OnlyDTr": name = r'\emph{CoPhy}-PGNN (only-$\mathcal{D}_{Tr}$)' elif DNN_type == "PGNN_LF": name = r'\emph{CoPhy}-PGNN (Label-free)' e...
3,283
35.488889
91
py
Cophy-PGNN
Cophy-PGNN-master/loss_surface_vis/loadModel.py
from DNN import DNN import glob import os import pandas as pd import torch import loss_landscapes import numpy as np def LoadModel(datasetLoader, model_path, DNN_type, H, Depth, device, initialModel=False): D_in = datasetLoader.x_dim D_out = datasetLoader.y_dim model_final = DNN(D_in, H, D_out, Depth).to...
2,197
42.098039
148
py
Cophy-PGNN
Cophy-PGNN-master/loss_surface_vis/lossCalculator.py
import torch import math def inverse_norm(batch, scale, mean): return batch * scale + mean def energy_loss(batchPred, batchInput): H_height = int(math.sqrt(batchInput.size(1))) H_width = H_height batchEg = batchPred[:, -1] loss_e = torch.exp(batchEg) return loss_e def phy_loss(batchPred, batc...
3,152
26.181034
115
py
Cophy-PGNN
Cophy-PGNN-master/eigensolver_comparison/util/solvers.py
# support libraries import time import torch import numpy as np # linear algebra libraries import scipy.linalg import scipy.sparse.linalg # ---------------------- Base Class -------------------------- class EigenSolver(object): def __init__(self, smallest_eigen=True): self.solvers = {} if smalle...
6,024
31.392473
140
py
Cophy-PGNN
Cophy-PGNN-master/scripts/data_loader_electromagnetic.py
import torch import numpy as np from torch.autograd import Variable from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler import os from scipy.io import loadmat import h5py def readMatFile(file_path, name): try: return loadmat(file_path)[name] except Excepti...
9,309
34.807692
78
py
Cophy-PGNN
Cophy-PGNN-master/scripts/evaluations.py
import torch import numpy as np from sklearn.metrics.pairwise import cosine_similarity def grad_cosine(grad_1, grad_2): cos = np.zeros(len(grad_1)) for i in range(len(grad_1)): cos_arr = grad_1[i] * grad_2[i] cos_arr /= np.sqrt(np.sum(grad_1[i] ** 2)) cos_arr /= np.sqrt(np.sum(...
3,111
36.493976
107
py
Cophy-PGNN
Cophy-PGNN-master/scripts/training_record_grad.py
# visualization import matplotlib.pyplot as plt import seaborn as sns # pytorch import torch from torch import optim from torch.autograd import Variable from torch.utils.data import DataLoader # sklearn from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler # scipy from scipy...
38,672
34.414835
140
py
Cophy-PGNN
Cophy-PGNN-master/scripts/loss_functions.py
import torch from math import sqrt def inverse_norm(batch, scale, mean): return batch * scale + mean def phy_loss(batchPred, batchReal, batchInput, norm=False): num_data = batchPred.size(0) if batchInput.dim() == 2: H_height = int(sqrt(batchInput.size(1))) H_width = H_height elif batch...
2,026
30.671875
94
py
Cophy-PGNN
Cophy-PGNN-master/scripts/loss_functions_electromagnetic.py
import torch from math import sqrt import numpy as np # The batch of this file is vectors of the form [Real Imaginary]. # Real takes the first half of the vector, and Imaginary takes the second half. # Last two elements are eignevalue (real, img) def inverse_norm(batch, scale, mean): return batch * scale + mean ...
2,430
32.763889
142
py
Cophy-PGNN
Cophy-PGNN-master/scripts/data_loader.py
import torch import numpy as np from torch.autograd import Variable from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler import os # restore hamiltonian from nonzeros def restore_h(nonzero, nonzero_loc, dim): data_count = nonzero.shape[0] H = torch.zeros((data_coun...
15,586
37.9675
108
py
Cophy-PGNN
Cophy-PGNN-master/scripts/training.py
# visualization import matplotlib.pyplot as plt import seaborn as sns # pytorch import torch from torch import optim from torch.autograd import Variable from torch.utils.data import DataLoader # sklearn from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler # scipy from scipy...
31,770
33.4962
140
py
Cophy-PGNN
Cophy-PGNN-master/scripts/early_stopping.py
# This implementation of early stopping is inspired by: # https://github.com/Bjarten/early-stopping-pytorch/blob/master/pytorchtools.py import numpy as np import torch class EarlyStopping: """Early stops the training if validation loss doesn't improve after a given patience.""" def __init__(self, patience=7, ...
2,020
38.627451
111
py
Cophy-PGNN
Cophy-PGNN-master/scripts/training_electromagnetic.py
# visualization import matplotlib.pyplot as plt import seaborn as sns # pytorch import torch from torch import optim from torch.autograd import Variable from torch.utils.data import DataLoader # sklearn from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler # scipy from scipy...
40,476
35.797273
181
py
Cophy-PGNN
Cophy-PGNN-master/scripts/parameters.py
import torch from torch import optim import numpy as np # ========================= The Parameter Class ========================= class Params(object): def __init__( self, nn_params={}, train_params={}, io_params={}, data_params={}, loss_params={}, name='d...
3,290
31.584158
95
py
Cophy-PGNN
Cophy-PGNN-master/scripts/gradient.py
import torch import numpy as np import os import pickle import pandas as pd import glob def load_grad(grad_path, epoch): load = lambda path: pickle.load(open(grad_path + path % epoch, 'rb')) grad_dict = { 'train_mse': load('train_mse_%d.pkl'), 'train_s_norm': load('train_train_s_norm_%d.pkl'), ...
6,168
35.076023
87
py
Cophy-PGNN
Cophy-PGNN-master/scripts/DNN.py
import torch from collections import OrderedDict # Multi-layer Perceptron class DNN(torch.nn.Module): def __init__( self, input_size, hidden_size, output_size, depth, act=torch.nn.Tanh, softmax=False ): super(DNN, self).__init__() ...
973
28.515152
76
py
mia-3dcnn
mia-3dcnn-main/train_mia_9a.py
import os import numpy as np import tensorflow as tf from tensorflow.keras import layers import tensorflow_addons as tfa import sklearn import sklearn.metrics import argparse import cv2 import imageio import imgaug as ia from imgaug import augmenters as iaa class DataGenerator(tf.keras.utils.Sequence): def __ini...
15,013
37.497436
123
py
mia-3dcnn
mia-3dcnn-main/valid_mia_9a.py
import os import numpy as np import tensorflow as tf from tensorflow.keras import layers import argparse import cv2 import pandas as pd import imageio import imgaug as ia from imgaug import augmenters as iaa class DataGenerator(tf.keras.utils.Sequence): def __init__( self, list_IDs, labels, batch_size=1...
9,905
33.395833
123
py
mia-3dcnn
mia-3dcnn-main/preprocess_images.py
import os import numpy as np from scipy import ndimage import cv2 import re from tqdm import tqdm def read_image_folder(folderpath): ct_names = os.listdir(folderpath) ct_names = [file_name.zfill(7) for file_name in ct_names] ct_names.sort() matrix = [] for filename in ct_names: filepath...
6,236
34.64
120
py
mia-3dcnn
mia-3dcnn-main/detection-task/train_mia_9a.py
import os import numpy as np import tensorflow as tf from tensorflow.keras import layers import tensorflow_addons as tfa import sklearn import sklearn.metrics import argparse import cv2 import imageio import imgaug as ia from imgaug import augmenters as iaa class DataGenerator(tf.keras.utils.Sequence): def __ini...
15,013
37.497436
123
py
mia-3dcnn
mia-3dcnn-main/detection-task/valid_mia_9a.py
import os import numpy as np import tensorflow as tf from tensorflow.keras import layers import argparse import cv2 import pandas as pd import imageio import imgaug as ia from imgaug import augmenters as iaa class DataGenerator(tf.keras.utils.Sequence): def __init__( self, list_IDs, labels, batch_size=1...
9,905
33.395833
123
py
mia-3dcnn
mia-3dcnn-main/severity-task/train_sev_6.py
import os import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras import layers import tensorflow_addons as tfa from scipy import ndimage import PIL from PIL import Image import sklearn import sklearn.metrics import argparse import cv2 import math import copy import random impo...
19,256
36.684932
123
py
mia-3dcnn
mia-3dcnn-main/severity-task/sev-inference.py
import os import numpy as np import tensorflow as tf from tensorflow.keras import layers import argparse import cv2 from collections import defaultdict import pandas as pd import imageio import imgaug as ia from imgaug import augmenters as iaa class DataGenerator(tf.keras.utils.Sequence): def __init__( s...
9,106
31.758993
123
py
blob
blob-master/simulate_abtest_with_bandit.py
from recogym import env_1_args from models.models_organic_bandit import RecoModelRTAEWithBanditTF, RecoModelRTAEWithBanditTF_Full from models.models_organic import RecoModelRTAE, RecoModelItemKNN from models.liang_multivae import MultiVAE from recogym.agents import organic_user_count_args from recogym.agents import Ra...
10,531
40.793651
217
py
blob
blob-master/models/liang_multivae.py
import seaborn as sn sn.set() from pandas.util import hash_pandas_object import tensorflow as tf from tensorflow.contrib.layers import apply_regularization, l2_regularizer from tqdm import tqdm from torch.utils.data import DataLoader from utils.utils import * # from https://github.com/dawenl/vae_cf/blob/master/VA...
13,484
37.528571
142
py
blob
blob-master/models/model_based_agents.py
from recogym.agents import Agent import torch import pandas as pd import numpy as np class ModelBasedAgent(Agent): def __init__(self, config): super(ModelBasedAgent, self).__init__(config) self.data = { 't': [], 'u': [], 'z': [], 'v': [], ...
2,732
33.594937
124
py
blob
blob-master/models/models_organic_bandit.py
import tensorflow as tf from tensorflow_probability import distributions as tfd from tensorflow.math import softplus as sp import os import sys import datetime import numpy as np import pandas as pd from pandas.util import hash_pandas_object import torch from torch import optim from torch.utils.data import DataLoade...
33,237
40.70389
173
py
blob
blob-master/models/models_bandit.py
import numpy as np from torch.autograd import Variable from torch.nn import functional as F from recogym.agents import ( AbstractFeatureProvider, Model, ModelBasedAgent, ViewsFeaturesProvider ) from recogym import Configuration pytorch_mlr_args = { 'n_epochs': 30, 'learning_rate': 0.01, 'r...
51,589
37.994709
128
py
blob
blob-master/models/models_organic.py
import os import sys import pdb import datetime import numpy as np import pandas as pd from pandas.util import hash_pandas_object import torch from torch import optim from tensorboardX import SummaryWriter from torch.utils.data import DataLoader from tqdm import tqdm from utils.utils import PandasDataset, shrink_wrap...
9,434
40.381579
190
py
blob
blob-master/utils/utils_vae.py
import torch from pylab import * # The KL def EQ_diag_standard_normal_logpdf(p_inv_Sigmaq_diag, p_muq): assert(p_inv_Sigmaq_diag.shape[0] == p_muq.shape[0]) assert(p_inv_Sigmaq_diag.shape[1] == p_muq.shape[1]) MB, K = p_inv_Sigmaq_diag.shape return -0.5 * ( (p_muq * p_muq).sum(1).reshape(MB,1,1) + (1...
2,153
43.875
314
py
blob
blob-master/utils/utils.py
import pandas as pd from pylab import * from torch.utils.data import Dataset from utils.utils_vae import block_torch_update import torch import torch.nn.functional as F import torch.nn as nn def to_categorical(y, num_classes=None, dtype='float32'): # from keras y = np.array(y.cpu(), dtype='int') input_shap...
6,992
34.140704
139
py
MeLT
MeLT-main/main.py
from modeling.encoder import MeLT from test_tube import HyperOptArgumentParser from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping import torch import torch.nn as nn import pytorch_lightning as pl import sys import os import random from pytorch_lightning import Callback import optuna from optuna.inte...
5,456
40.656489
153
py
MeLT
MeLT-main/modeling/encoder.py
""" Defines the MeLT encoder which leverages building blocks from encoder_layers.py """ import math import torch.nn as nn import torch from modeling.attn import MultiHeadedAttn from modeling.neural import PositionalFeedForward, PositionalEncoding, batch_by_usr, batch_by_usr_no_mask, metrics, calc_avg_preds from m...
13,760
45.489865
167
py
MeLT
MeLT-main/modeling/encoder_layers.py
""" Defines the individual layers to be used for a transformer encoder """ import math import torch.nn as nn import torch from modeling.attn import MultiHeadPooling, MultiHeadedAttn from modeling.neural import PositionalEncoding, PositionalFeedForward class TransformerEncoderLayer(nn.Module): """ A singl...
1,586
32.0625
79
py
MeLT
MeLT-main/modeling/attn.py
import math import torch import torch.nn as nn import sys class MultiHeadedAttn(nn.Module): """ Multi-Headed Attn Args: num_heads (int): amount of parallel heads model_dim (int): dimension of K,V,Q (must be divisible by head count) dropout (float): dropout rate """ def __i...
5,200
36.417266
116
py
MeLT
MeLT-main/modeling/data_handler.py
import logging logging.disable(logging.CRITICAL) import torch import pandas as pd from transformers import BertTokenizer from transformers import DistilBertTokenizer, DistilBertTokenizerFast, AlbertTokenizerFast, RobertaTokenizerFast from transformers import AutoTokenizer from torch.utils.data import TensorDataset, Dat...
6,353
40.25974
185
py
MeLT
MeLT-main/modeling/neural.py
import math import torch import torch.nn as nn import numpy as np from scipy.stats import pearsonr, zscore from sklearn.metrics.pairwise import cosine_similarity from collections import defaultdict import sys def metrics(loss, preds, metric_name, labels=None, other_data=None): """ Determines the values of...
13,707
37.505618
135
py
w2ot
w2ot-main/scripts/eval-conj-solver-benchmarks.py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. import argparse import functools import glob import os import yaml import time from collections import defaultdict import numpy as np import pickle as pkl import pandas as pd pd.set_option("display.precision", 2) import jax import jax.nump...
9,617
31.60339
88
py
w2ot
w2ot-main/scripts/prof-conj.py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. import argparse import jax import jax.numpy as jnp import numpy as np import pickle as pkl import os import functools from collections import defaultdict import time from w2ot import conjugate_solver, utils import matplotlib.pyplot as p...
2,942
27.028571
86
py
w2ot
w2ot-main/scripts/eval-conj-solver-lbfgs.py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. import argparse import functools import glob import os import yaml import time from collections import namedtuple import numpy as np import pickle as pkl import pandas as pd pd.set_option("display.precision", 2) import jax import jax.numpy...
4,996
31.032051
94
py
w2ot
w2ot-main/scripts/vis-2d-transport.py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. import argparse import jax import jax.numpy as jnp import numpy as np import pickle as pkl import os import shutil import functools from w2ot import conjugate_solver, utils import matplotlib.pyplot as plt from matplotlib.collections impor...
20,756
31.688189
156
py
w2ot
w2ot-main/scripts/eval-conj-solver.py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. import argparse import jax import jax.numpy as jnp import numpy as np import pickle as pkl import os import functools from w2ot import conjugate_solver, utils import sys import w2ot.run_train as train sys.modules['train'] = train # Legacy...
3,784
27.458647
88
py
w2ot
w2ot-main/scripts/vis-image-transport.py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. import argparse import jax import jax.numpy as jnp import numpy as np import pickle as pkl import os import shutil import functools from w2ot import conjugate_solver, utils import matplotlib.pyplot as plt from matplotlib.collections impor...
7,222
31.536036
97
py
w2ot
w2ot-main/scripts/vis-2d-grid-warp.py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. import argparse import jax import jax.numpy as jnp import numpy as np import pickle as pkl import os import shutil import functools from w2ot import conjugate_solver, utils import matplotlib.pyplot as plt from matplotlib.collections impor...
4,788
28.93125
95
py
w2ot
w2ot-main/w2ot/dual_trainer.py
# Copyright (c) Meta Platforms, Inc. and affiliates. import copy import functools import jax import jax.numpy as jnp from jax.lax import stop_gradient from flax import linen as nn from flax.training import train_state from dataclasses import dataclass from typing import Tuple, Sequence, Optional import optax from ...
12,679
36.076023
90
py
w2ot
w2ot-main/w2ot/utils.py
# Copyright (c) Meta Platforms, Inc. and affiliates. import jax import jax.numpy as jnp from jax import dtypes from flax import linen as nn from functools import partial batch_dot = jax.vmap(jnp.dot) class RunningAverageMeter(object): def __init__(self, momentum=0.999): self.momentum = momentum ...
2,492
27.011236
75
py
w2ot
w2ot-main/w2ot/data.py
# Copyright (c) Meta Platforms, Inc. and affiliates. import random import copy import jax import jax.numpy as jnp import sys import gc import numpy as np import numpy.random as npr import sklearn.datasets import torch from torch.utils.data import IterableDataset from torchvision import transforms from torchvision...
22,476
32.953172
139
py
w2ot
w2ot-main/w2ot/run_train.py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. import hydra import csv import time import warnings warnings.filterwarnings('ignore') from collections import defaultdict import copy import numpy as np import pickle as pkl import jax import jax.numpy as jnp import optax import os impo...
8,791
33.614173
114
py
w2ot
w2ot-main/w2ot/conjugate_solver.py
# Copyright (c) Meta Platforms, Inc. and affiliates. import functools import jax from jax import lax import jax.numpy as jnp import optax from dataclasses import dataclass, field from collections import namedtuple from typing import Optional import copy from w2ot.external.jax_lbfgs import _minimize_lbfgs from w2ot...
5,692
29.44385
105
py
w2ot
w2ot-main/w2ot/external/jaxopt_lbfgs.py
# This file is modified from: # https://github.com/google/jaxopt/blob/418bce35ff7410a86dc5edb64ee5d3716b3bc132/jaxopt/_src/lbfgs.py # and remains under the original licensing. # # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complian...
14,723
36.370558
101
py
w2ot
w2ot-main/w2ot/external/jax_lbfgs.py
# This file is modified from # https://github.com/google/jax/blob/ba557d5/jax/_src/scipy/optimize/_lbfgs.py # and remains under the original licensing. # # # Copyright 2020 The JAX Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
12,258
31.517241
103
py
w2ot
w2ot-main/w2ot/external/ott_icnn.py
# This file is modified from the following files and remains under the # original licensing. # # https://github.com/ott-jax/ott/blob/main/ott/core/icnn.py # and # https://github.com/ott-jax/ott/blob/main/ott/core/layers.py # # # Copyright 2022 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License...
3,334
27.504274
83
py
w2ot
w2ot-main/w2ot/external/jaxopt_backtracking_linesearch.py
# This file is modified from: # https://github.com/google/jaxopt/blob/418bce35ff7410a86dc5edb64ee5d3716b3bc132/jaxopt/_src/backtracking_linesearch.py # and remains under the original licensing. # # # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this fil...
7,275
35.38
119
py
w2ot
w2ot-main/w2ot/external/benchmark/distributions.py
# This file is from # https://github.com/iamalexkorotin/Wasserstein1Benchmark/commit/647a1acc85f88e207733d087cbe87987cc0dea06 # and remains under the original licensing. import torch import numpy as np from scipy.linalg import sqrtm import sklearn.datasets import random from .potentials import BasePotential def symme...
12,163
31.524064
119
py
w2ot
w2ot-main/w2ot/external/benchmark/resnet2.py
# This file is from # https://github.com/iamalexkorotin/Wasserstein1Benchmark/commit/647a1acc85f88e207733d087cbe87987cc0dea06 # and remains under the original licensing. import numpy as np import torch from torch import nn def weights_init_G(m): classname = m.__class__.__name__ if classname.find('Conv') != -1...
5,356
31.271084
105
py
w2ot
w2ot-main/w2ot/external/benchmark/inception.py
# This file is from # https://github.com/iamalexkorotin/Wasserstein1Benchmark/commit/647a1acc85f88e207733d087cbe87987cc0dea06 # and remains under the original licensing. import torch import torch.nn as nn import torch.nn.functional as F import torchvision try: from torchvision.models.utils import load_state_dict_...
12,349
36.087087
126
py
w2ot
w2ot-main/w2ot/external/benchmark/plotters.py
# This file is from # https://github.com/iamalexkorotin/Wasserstein1Benchmark/commit/647a1acc85f88e207733d087cbe87987cc0dea06 # and remains under the original licensing. import matplotlib import numpy as np import matplotlib.pyplot as plt from .tools import ewma, freeze import torch import gc def plot_benchmark_emb(...
6,286
39.824675
114
py
w2ot
w2ot-main/w2ot/external/benchmark/potentials.py
# This file is from # https://github.com/iamalexkorotin/Wasserstein1Benchmark/commit/647a1acc85f88e207733d087cbe87987cc0dea06 # and remains under the original licensing. import torch import torch.nn as nn import torch.autograd as autograd import numpy as np class BasePotential(nn.Module): def __init__(self, batch...
4,662
36.910569
120
py
w2ot
w2ot-main/w2ot/external/benchmark/tools.py
# This file is from # https://github.com/iamalexkorotin/Wasserstein1Benchmark/commit/647a1acc85f88e207733d087cbe87987cc0dea06 # and remains under the original licensing. import pandas as pd import numpy as np import os import itertools import torch from torch import nn import torch.nn.functional as F from tqdm impo...
5,316
28.703911
122
py