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 |
|---|---|---|---|---|---|---|
more-or-let | more-or-let-master/pydrobert/mol/model.py | '''Tensor ops and models'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import keras.backend as K
import numpy as np
from keras.callbacks import CSVLogger
from keras.callbacks import ModelCheckpoint
from keras.initializers import RandomUnif... | 23,829 | 37.874388 | 83 | py |
more-or-let | more-or-let-master/pydrobert/mol/ctc_2.py | '''Tensor ops and models related to Connectionist Temporal Classification
All CTC classes accept input via generators in one of the following forms:
1. Numpy arrays of shape `(time, bank_size)` representing individual audio
samples. This is used for decoding
2. Tuples of `(audio_sample, label_seq)`, where `label_s... | 23,792 | 37.687805 | 84 | py |
flores | flores-main/shared_tasks/dynalab/handler.py | # Copyright (c) Facebook, Inc. and its affiliates.
import json
import logging
import time
import os
from pathlib import Path
import fairseq.checkpoint_utils
import sentencepiece
import torch
from typing import NamedTuple
from dynalab.handler.base_handler import BaseDynaHandler
from dynalab.tasks.flores_small1 import ... | 10,595 | 33.514658 | 94 | py |
flores | flores-main/previous_releases/floresv1/scripts/translate.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import os
import torch
from subprocess import check_call, check_output
from glob im... | 7,695 | 41.054645 | 144 | py |
flores | flores-main/previous_releases/floresv1/scripts/train.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import os
import torch
from subprocess import check_call, check_output
from glob im... | 6,101 | 36.435583 | 153 | py |
code-nerf | code-nerf-main/src/utils.py |
import imageio
import numpy as np
import torch
# import json
# from torchvision import transforms
import os
def get_rays(H, W, focal, c2w):
i, j = torch.meshgrid(torch.linspace(0, W - 1, W), torch.linspace(0, H - 1, H))
i = i.t()
j = j.t()
dirs = torch.stack([(i - W * .5) / focal, -(j - H * .5) / foc... | 2,512 | 34.394366 | 94 | py |
code-nerf | code-nerf-main/src/model.py | import torch
import torch.nn as nn
def PE(x, degree):
y = torch.cat([2.**i * x for i in range(degree)], -1)
w = 1
return torch.cat([x] + [torch.sin(y) * w, torch.cos(y) * w], -1)
class CodeNeRF(nn.Module):
def __init__(self, shape_blocks = 2, texture_blocks = 1, W = 256,
num_xyz_fre... | 2,360 | 43.54717 | 83 | py |
code-nerf | code-nerf-main/src/data.py |
import imageio
import numpy as np
import torch
# import json
# from torchvision import transforms
import os
def load_poses(pose_dir, idxs=[]):
txtfiles = np.sort([os.path.join(pose_dir, f.name) for f in os.scandir(pose_dir)])
posefiles = np.array(txtfiles)[idxs]
srn_coords_trans = np.diag(np.array([1, -1... | 3,451 | 37.786517 | 92 | py |
code-nerf | code-nerf-main/src/trainer.py |
import numpy as np
import torch
import torch.nn as nn
import json
from data import SRN
from utils import get_rays, sample_from_rays, volume_rendering, image_float_to_uint8
from model import CodeNeRF
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import os
import math
import ... | 8,307 | 46.204545 | 121 | py |
code-nerf | code-nerf-main/src/optimizer.py |
import numpy as np
import torch
import torch.nn as nn
import json
from data import SRN
from utils import get_rays, sample_from_rays, volume_rendering, image_float_to_uint8
from skimage.metrics import structural_similarity as compute_ssim
from model import CodeNeRF
from torch.utils.data import DataLoader
from torch.ut... | 11,915 | 47.636735 | 134 | py |
pynbody | pynbody-master/pynbody/plot/stars.py | """
stars
=====
"""
import logging
import warnings
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from .. import array, filt, units, units as _units
from ..analysis import angmom, profile
from ..sph import Kernel2D, render_spherical_image
from .sph import image
logger = logging.getLogger('py... | 41,698 | 29.661029 | 199 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/util_for_bert.py | import jieba
import torch
import pandas as pd
from torch.utils.data import DataLoader,Dataset
from gensim.models import word2vec
import json
import re
from how_net import is_sememe
import args
from tqdm import tqdm
from args import *
def load_word_vocab():
path ='data/chinese/bq_corpus/word_vocab.txt'
vocab = ... | 2,812 | 31.333333 | 80 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/hownet_bert.py | import torch
import math
import torch.nn as nn
import torch.optim as optim
import args
from numpy import *
from util_for_bert import *
from tqdm import tqdm_notebook, tqdm
from torch.nn import functional as F
from sklearn import metrics
from torch.optim.lr_scheduler import ExponentialLR, MultiStepLR
import numpy as np
... | 11,154 | 38.556738 | 118 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/Pre-processing.py | import jieba
import torch
import pandas as pd
from torch.utils.data import DataLoader,Dataset
from gensim.models import word2vec
import json
import re
from how_net import is_sememe
import args
from tqdm import tqdm
from args import *
def load_word_vocab():
path ='data/chinese/AFQMC/word_vocab.txt'
vocab = [lin... | 4,059 | 33.40678 | 147 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/util_for_BQ.py | import jieba
import torch
import pandas as pd
from torch.utils.data import DataLoader,Dataset
from gensim.models import word2vec
import json
import re
from how_net import is_sememe
import args
from tqdm import tqdm
from args import *
import pickle
def load_word_vocab():
path ='data/chinese/bq_corpus/word_vocab.txt... | 4,742 | 33.369565 | 112 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/hownet.py | import torch
import math
import torch.nn as nn
import torch.optim as optim
import args
from numpy import *
from util_for_BQ import *
from tqdm import tqdm_notebook,tqdm
from torch.nn import functional as F
from sklearn import metrics
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def length... | 7,787 | 38.135678 | 127 | py |
EOS | EOS-main/cifar_FE.py | import argparse
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from sklearn.metrics import accuracy_score
from sklearn.metrics import balanced_accura... | 12,215 | 32.105691 | 96 | py |
EOS | EOS-main/losses.py | """
code adapted from: https://github.com/kaidic/LDAM-DRW
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def focal_loss(input_values, gamma):
"""Computes the focal loss"""
p = torch.exp(-input_values)
loss = (1 - p) ** gamma * input_values
return l... | 3,252 | 30.582524 | 101 | py |
EOS | EOS-main/resnet_cifar_FE.py | '''
Properly implemented ResNet for CIFAR10 as described in paper [1].
The implementation and structure of this file is hugely influenced by [2]
which is implemented for ImageNet and doesn't have option A for identity.
Moreover, most of the implementations on the web is copy-paste from
torchvision's resnet and has wron... | 5,692 | 31.718391 | 120 | py |
EOS | EOS-main/linear_sm.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torch.nn import Parameter
class Lin(nn.Module):
def __init__(self):
super(Lin, self).__init__()
self.linear = nn.Linear(64, 10)
def forward(self, x):
... | 375 | 14.04 | 39 | py |
EOS | EOS-main/cifar_train_os.py | """
code adapted from: https://github.com/kaidic/LDAM-DRW
"""
import argparse
import os
import random
import time
import warnings
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.dat... | 26,091 | 33.65073 | 141 | py |
EOS | EOS-main/utils.py | """
code adapted from: https://github.com/kaidic/LDAM-DRW
"""
import torch
import shutil
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
class ImbalancedDatasetSampler(to... | 5,820 | 31.519553 | 97 | py |
EOS | EOS-main/cifar_train.py | """
code adapted from: https://github.com/kaidic/LDAM-DRW
"""
import argparse
import os
import random
import time
import warnings
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datas... | 25,808 | 35.147059 | 141 | py |
EOS | EOS-main/imbalance_cifar.py | """
code adapted from: https://github.com/kaidic/LDAM-DRW
"""
import torch
import torchvision
import torchvision.transforms as transforms
import numpy as np
import pandas as pd
torch.cuda.manual_seed(0)
class IMBALANCECIFAR10(torchvision.datasets.CIFAR10):
cls_num = 10
torch.cuda.manual_seed(0)
def __init... | 3,529 | 34.3 | 98 | py |
EOS | EOS-main/resnet_cifar.py | '''
code adapted from: https://github.com/kaidic/LDAM-DRW
Properly implemented ResNet for CIFAR10 as described in paper [1].
The implementation and structure of this file is hugely influenced by [2]
which is implemented for ImageNet and doesn't have option A for identity.
Moreover, most of the implementations on the we... | 5,614 | 32.622754 | 120 | py |
EOS | EOS-main/reassemble.py | import argparse
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from sklearn.metrics import accuracy_score
from losses import LDAMLoss, FocalLoss, AS... | 13,195 | 29.759907 | 96 | py |
knodle-develop | knodle-develop/examples/trainer/preprocessing.py | from typing import List, Union, Tuple
from joblib import dump
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from torch.utils.data import TensorDataset
def get_tfidf_features(
train_data: List, test_data: List = None, dev_data: List = None, path_to_cache: str = None,
... | 2,606 | 43.186441 | 112 | py |
knodle-develop | knodle-develop/examples/trainer/cleanlab/cleanlab_training_tutorial.py | import argparse
import os
import statistics
import sys
import json
from itertools import product
from torch import Tensor, LongTensor
from torch.nn import CrossEntropyLoss
from torch.optim import Adam
from torch.utils.data import TensorDataset
from examples.trainer.preprocessing import get_tfidf_features
from example... | 4,080 | 36.787037 | 120 | py |
knodle-develop | knodle-develop/examples/trainer/simple_auto_trainer/auto_trainer_tutorial.py | import os
from typing import List
from tqdm.auto import tqdm
import joblib
from minio import Minio
import pandas as pd
import numpy as np
import scipy.sparse as sp
import torch
from torch.utils.data import TensorDataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AdamW
from examples... | 3,496 | 29.146552 | 105 | py |
knodle-develop | knodle-develop/examples/trainer/simple_auto_trainer/multi_trainer_tutorial.py | import os
from torch import Tensor
from tqdm.auto import tqdm
import joblib
from minio import Minio
import pandas as pd
import numpy as np
import scipy.sparse as sp
import torch
from torch.utils.data import TensorDataset
from transformers import AdamW
from examples.trainer.preprocessing import get_tfidf_features
fr... | 3,491 | 31.333333 | 105 | py |
knodle-develop | knodle-develop/examples/trainer/[WIP]_baseline/baseline_training_example.py | import logging
import os
from torch import Tensor
from torch.optim import SGD
from torch.utils.data import TensorDataset
from knodle.data.download import MinioConnector
from knodle.model.logistic_regression_model import (
LogisticRegressionModel,
)
from examples.ImdbDataset.utils import init_logger
from examples... | 2,507 | 29.962963 | 109 | py |
knodle-develop | knodle-develop/examples/trainer/wscrossweigh/wscrossweigh_training_tutorial.py | import argparse
import os
import sys
import joblib
import pandas as pd
from minio import Minio
from torch import Tensor, LongTensor
from torch.optim import Adam
from torch.utils.data import TensorDataset
from tqdm import tqdm
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification, AdamW
from... | 7,220 | 48.122449 | 129 | py |
knodle-develop | knodle-develop/examples/trainer/wscrossweigh/wscrossweigh_training_with_BiLSTM_tutorial.py | import argparse
import os
import sys
from typing import Dict
import numpy as np
import pandas as pd
import torch
from torch import Tensor, LongTensor
from torch.optim import Adam
from torch.utils.data import TensorDataset
from knodle.evaluation.other_class_metrics import score
from knodle.model.bidirectional_lstm_mod... | 8,183 | 40.125628 | 120 | py |
knodle-develop | knodle-develop/examples/data_preprocessing/MIMIC_CXR_dataset/prepare_mimic_cxr.py | # -*- coding: utf-8
"""
Preprocessing of MIMIC-CXR dataset
This file illustrates how weak supervision can be applied on medical images
and the corresponding reports. Since there are two sources of data (images and
reports) we establish a double layer weak supervision.
In this example the MIMIC-CXR dataset is used... | 21,914 | 37.179443 | 126 | py |
knodle-develop | knodle-develop/tests/trainer/test_multi_label.py | from torch.nn import BCEWithLogitsLoss
from knodle.trainer import MajorityVoteTrainer, MajorityConfig
from tests.trainer.generic import std_trainer_input_1
def test_auto_train(std_trainer_input_1):
(
model,
model_input_x, rule_matches_z, mapping_rules_labels_t,
_
) = std_trainer_input... | 849 | 27.333333 | 106 | py |
knodle-develop | knodle-develop/tests/trainer/generic.py | import pytest
import numpy as np
import torch
from torch.utils.data import TensorDataset
from knodle.model.logistic_regression_model import LogisticRegressionModel
@pytest.fixture
def std_trainer_input_1():
num_samples = 64
num_features = 16
num_rules = 6
num_classes = 2
x_np = np.ones((num_sam... | 1,813 | 28.737705 | 92 | py |
knodle-develop | knodle-develop/tests/trainer/cleanlab/test_cl.py | from torch.nn import CrossEntropyLoss
from tests.trainer.generic import std_trainer_input_2
from knodle.trainer.cleanlab.cleanlab import CleanLabTrainer
from knodle.trainer.cleanlab.config import CleanLabConfig
def test_cleanlab_base_test(std_trainer_input_2):
(
model,
inputs_x, mapping_rules_la... | 875 | 27.258065 | 101 | py |
knodle-develop | knodle-develop/tests/trainer/wscrossweigh/test_wscw_data_preparation.py | import torch
from torch.utils.data import TensorDataset
import pytest
import numpy as np
from knodle.trainer.wscrossweigh.data_splitting_by_rules import get_rules_sample_ids, get_samples_labels_idx_by_rule_id
@pytest.fixture(scope='session')
def get_test_data():
rule_assignments_t = np.array([[1, 0, 0],
... | 5,521 | 39.903704 | 119 | py |
knodle-develop | knodle-develop/tests/trainer/snorkel/test_utils.py | import numpy as np
from scipy import sparse as ss
import torch
from torch.utils.data import TensorDataset
from knodle.trainer.snorkel.utils import (
z_t_matrix_to_snorkel_matrix,
prepare_empty_rule_matches,
add_labels_for_empty_examples
)
def test_z_t_matrix_to_snorkel_matrix():
# test dense case
... | 2,626 | 24.019048 | 111 | py |
knodle-develop | knodle-develop/tests/transformation/test_filter.py | import numpy as np
import torch
from torch.utils.data import TensorDataset
from knodle.transformation.filter import filter_empty_probabilities, filter_probability_threshold
def test_filter_empty_probabilities():
input_ids = np.ones((3, 4))
input_ids[0, 0] = 0
input_mask = np.ones((3, 4))
input_mask[1... | 1,837 | 28.174603 | 118 | py |
knodle-develop | knodle-develop/tests/transformation/generic.py | import pytest
import torch
from torch.utils.data import TensorDataset
import numpy as np
@pytest.fixture
def filter_input():
input_ids = np.ones((3, 4))
input_ids[0, 0] = 0
input_mask = np.ones((3, 4))
input_mask[1, 1] = 0
class_probs = np.array([
[0.5, 0.5],
[0.3, 0.7],
[... | 932 | 16.942308 | 92 | py |
knodle-develop | knodle-develop/tests/transformation/torch_input.py | import numpy as np
from numpy.testing import assert_array_equal
from torch import Tensor, equal
from torch.utils.data import TensorDataset
from knodle.transformation.torch_input import input_labels_to_tensordataset
def test_input_labels_to_tensordataset():
a = np.ones((4, 4))
b = np.ones((4, 3))
labels... | 604 | 27.809524 | 86 | py |
knodle-develop | knodle-develop/knodle/trainer/auto_trainer.py | from typing import Callable
import numpy as np
from torch.utils.data import TensorDataset
from knodle.trainer.trainer import Trainer
class AutoTrainer:
""" The factory class for creating training executors
See See https://medium.com/@geoffreykoh/implementing-the-factory-
pattern-via-dynamic-registry-and... | 1,469 | 30.956522 | 102 | py |
knodle-develop | knodle-develop/knodle/trainer/config.py | import pathlib
from typing import Callable, Dict
import os
import logging
from snorkel.classification import cross_entropy_with_probs
import torch
from torch import Tensor
from torch.optim import SGD
from torch.optim.optimizer import Optimizer
from knodle.trainer.utils.utils import check_and_return_device, set_seed
... | 6,907 | 44.447368 | 121 | py |
knodle-develop | knodle-develop/knodle/trainer/multi_trainer.py | import copy
import logging
from typing import Callable, List, Dict
import numpy as np
from torch.utils.data import TensorDataset
from knodle.trainer import AutoTrainer
from knodle.trainer.utils import log_section
logger = logging.getLogger(__name__)
class MultiTrainer:
""" The factory class for creating train... | 1,699 | 33.693878 | 92 | py |
knodle-develop | knodle-develop/knodle/trainer/trainer.py | import logging
import os
from abc import ABC, abstractmethod
from typing import Union, Dict, Tuple, List
import numpy as np
import skorch
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.metrics import classification_report
from torch import Tensor
from torch.nn import Module
from torch.... | 14,273 | 42.386018 | 119 | py |
knodle-develop | knodle-develop/knodle/trainer/baseline/majority.py | import logging
import numpy as np
import torch.nn as nn
from torch.optim import SGD
from torch.utils.data import TensorDataset
from knodle.transformation.majority import input_to_majority_vote_input
from knodle.transformation.torch_input import input_labels_to_tensordataset
from knodle.trainer.trainer import BaseTr... | 2,436 | 37.68254 | 100 | py |
knodle-develop | knodle-develop/knodle/trainer/cleanlab/cleanlab.py | import logging
import numpy as np
from cleanlab.classification import LearningWithNoisyLabels
from skorch import NeuralNetClassifier
from torch.utils.data import TensorDataset
from knodle.trainer import MajorityVoteTrainer
from knodle.trainer.auto_trainer import AutoTrainer
from knodle.trainer.cleanlab.config import ... | 4,376 | 44.59375 | 119 | py |
knodle-develop | knodle-develop/knodle/trainer/wscrossweigh/wscrossweigh_weights_calculator.py | import copy
import logging
import os
import torch
from torch.utils.data import DataLoader
from joblib import dump
from knodle.trainer.baseline.majority import MajorityVoteTrainer
from knodle.trainer.utils import log_section
from knodle.trainer.wscrossweigh.data_splitting_by_rules import k_folds_splitting_by_rules
fro... | 5,533 | 43.99187 | 120 | py |
knodle-develop | knodle-develop/knodle/trainer/wscrossweigh/utils.py | import logging
import random
from typing import Dict
import numpy as np
import torch
from torch.utils.data import TensorDataset
logger = logging.getLogger(__name__)
def get_labels_randomly(
rule_matches_z: np.ndarray, rule_assignments_t: np.ndarray
) -> np.ndarray:
""" Calculates sample labels basing on... | 4,180 | 36.666667 | 119 | py |
knodle-develop | knodle-develop/knodle/trainer/wscrossweigh/config.py | from torch.optim import Optimizer
from knodle.trainer.baseline.config import MajorityConfig
from knodle.trainer.auto_config import AutoConfig
@AutoConfig.register("wscrossweigh")
class WSCrossWeighConfig(MajorityConfig):
def __init__(
self,
partitions: int = 2,
folds: int = 10... | 3,386 | 39.807229 | 123 | py |
knodle-develop | knodle-develop/knodle/trainer/wscrossweigh/data_splitting_by_rules.py | import logging
import random
from typing import List, Dict, Union, Tuple
import scipy.sparse as sp
import numpy as np
import torch
from torch.utils.data import TensorDataset
from knodle.trainer.wscrossweigh.utils import return_unique
from knodle.transformation.torch_input import input_info_labels_to_tensordataset, in... | 14,185 | 49.483986 | 120 | py |
knodle-develop | knodle-develop/knodle/trainer/wscrossweigh/wscrossweigh.py | import logging
import os
from copy import copy
import numpy as np
import torch
from joblib import load
from torch.nn import Module
from torch.optim import SGD
from torch.utils.data import TensorDataset
from knodle.trainer.auto_trainer import AutoTrainer
from knodle.trainer.baseline.majority import MajorityVoteTrainer... | 6,409 | 45.115108 | 119 | py |
knodle-develop | knodle-develop/knodle/trainer/knn_aggregation/knn.py | import os
import logging
import joblib
import numpy as np
from torch.optim import SGD
from torch.utils.data import TensorDataset
from scipy.sparse import csr_matrix
from sklearn.neighbors import NearestNeighbors
from annoy import AnnoyIndex
from knodle.transformation.majority import input_to_majority_vote_input
fro... | 6,376 | 40.953947 | 115 | py |
knodle-develop | knodle-develop/knodle/trainer/utils/utils.py | import random
import logging
import torch
from torch import Tensor, argmax
from torch.utils.data import TensorDataset
import numpy as np
import matplotlib.pyplot as plt
def log_section(text: str, logger: logging, additional_info: {} = None) -> None:
"""
Prints a section
Args:
text: Text to print
... | 2,163 | 26.392405 | 88 | py |
knodle-develop | knodle-develop/knodle/trainer/snorkel/snorkel.py | from typing import Tuple
import numpy as np
from snorkel.labeling.model import LabelModel
from torch.optim import SGD
from torch.utils.data import TensorDataset
from knodle.transformation.torch_input import input_labels_to_tensordataset
from knodle.trainer.auto_trainer import AutoTrainer
from knodle.trainer.baselin... | 6,133 | 43.129496 | 115 | py |
knodle-develop | knodle-develop/knodle/model/logistic_regression_model.py | import torch
from torch import nn
class LogisticRegressionModel(nn.Module):
def __init__(self, input_dim: int, output_classes: int):
super(LogisticRegressionModel, self).__init__()
self.linear = torch.nn.Linear(input_dim, output_classes)
def forward(self, x):
x = x.float()
out... | 365 | 25.142857 | 64 | py |
knodle-develop | knodle-develop/knodle/model/logisitc_regression_with_emb_layer.py | import torch
from torch import nn
import numpy as np
class LogisticRegressionModel(nn.Module):
def __init__(
self,
input_size: int,
word_input_dim: int,
word_output_dim: int,
word_embedding_matrix: np.ndarray,
output_classes: int,
):
... | 1,040 | 30.545455 | 78 | py |
knodle-develop | knodle-develop/knodle/model/bidirectional_lstm_model.py | import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.rnn import pad_packed_sequence
class BidirectionalLSTM(nn.Module):
def __init__(
self,
word_input_dim,
word_output_dim,
word_embedding_matrix,
num_... | 2,448 | 31.653333 | 100 | py |
knodle-develop | knodle-develop/knodle/model/EarlyStopping/__init__.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, verbose=False, delta=0, name="checkpoint"):
"""
Args:
patience (int): How long to wait after last time vali... | 1,854 | 34.673077 | 108 | py |
knodle-develop | knodle-develop/knodle/transformation/filter.py | from typing import Tuple, Union, List
import numpy as np
from torch.utils.data import TensorDataset
def filter_tensor_dataset_by_indices(dataset: TensorDataset, filter_ids: Union[np.ndarray, List[int]]) -> TensorDataset:
"""Filters each tensor of a TensorDataset, given some "filter_ids".
Args:
datas... | 2,543 | 39.380952 | 120 | py |
knodle-develop | knodle-develop/knodle/transformation/majority.py | import logging
import random
import warnings
import numpy as np
import scipy.sparse as sp
from torch.utils.data import TensorDataset
from knodle.transformation.filter import filter_empty_probabilities, filter_probability_threshold
logger = logging.getLogger(__name__)
def probabilities_to_majority_vote(
pro... | 10,110 | 46.027907 | 125 | py |
knodle-develop | knodle-develop/knodle/transformation/torch_input.py | import numpy as np
import torch
from torch.utils.data import TensorDataset
def input_labels_to_tensordataset(model_input_x: TensorDataset, labels: np.ndarray) -> TensorDataset:
"""
This function takes Dataset with data features (num_samples x features dimension x features) and
labels (num_samples x labels... | 1,667 | 42.894737 | 115 | py |
FantasticNetworksNoData | FantasticNetworksNoData-main/train.py | from __future__ import print_function
import os
import json
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torch.optim as optim
import datetime
from datetime import datetime
import numpy as np
import copy
from torchvision import datasets, transforms, models... | 18,369 | 35.161417 | 180 | py |
FantasticNetworksNoData | FantasticNetworksNoData-main/models/resnet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import linalg as LA
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, HW, stride=1):
super(BasicBlock, self).__init__()
#self.kwargs = kwargs
self.conv1 = nn.Conv2d(in_planes,... | 5,019 | 32.691275 | 110 | py |
brain_sas_baseline | brain_sas_baseline-main/baseline.py | import argparse
from multiprocessing import Pool
import os
from time import time
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch.utils.data import Dataset
from utils.data_utils import DatasetHandler, load_mr_scan
from utils import evaluation, utils
class DataPreloader(Dataset):
def __... | 4,617 | 34.79845 | 96 | py |
brain_sas_baseline | brain_sas_baseline-main/utils/utils.py | import matplotlib.pyplot as plt
import numpy as np
from skimage.exposure import equalize_hist
from skimage.measure import label, regionprops
import torch
import torch.nn.functional as F
from torchvision.utils import make_grid, save_image
from tqdm import tqdm
""" General utilities """
def torch2np_img(img: torch.Ten... | 4,772 | 28.103659 | 79 | py |
brain_sas_baseline | brain_sas_baseline-main/utils/data_utils.py | from glob import glob
import os
import nibabel as nib
import numpy as np
import torch
from torchvision.datasets.folder import IMG_EXTENSIONS
from warnings import warn
from utils.utils import CenterCrop3D, ResizeGray, histogram_equalization
DATAROOT = str(os.environ.get('DATAROOT'))
DICOM_EXT = ('.dcm', )
NIFTI_EXT ... | 5,620 | 31.304598 | 108 | py |
brain_sas_baseline | brain_sas_baseline-main/utils/evaluation.py | import warnings
import matplotlib.pyplot as plt
import numpy as np
from skimage import measure
from sklearn.metrics import auc, precision_recall_curve, roc_auc_score, roc_curve
import torch
from tqdm import tqdm
from torchvision.utils import make_grid
from utils.utils import connected_components_3d, torch2np_img
de... | 11,908 | 34.655689 | 118 | py |
clinicalBERT | clinicalBERT-master/downstream_tasks/run_classifier.py | # Code is adapted from the PyTorch pretrained BERT repo - See copyright & license below.
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not ... | 33,551 | 41.57868 | 139 | py |
IDEC-toy | IDEC-toy-master/DEC.py | """
Toy implementation for Deep Embedded Clustering as described in the paper:
Junyuan Xie, Ross Girshick, and Ali Farhadi. Unsupervised deep embedding for clustering analysis. ICML 2016.
Main differences with original code at https://github.com/piiswrong/dec.git:
1. Autoencoder is pretrain in an end-to-e... | 13,998 | 39.459538 | 120 | py |
IDEC-toy | IDEC-toy-master/datasets.py | import numpy as np
def load_mnist():
# the data, shuffled and split between train and test sets
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x = np.concatenate((x_train, x_test))
y = np.concatenate((y_train, y_test))
x = x.reshape((x.shape[0], -1))
... | 5,688 | 36.675497 | 113 | py |
IDEC-toy | IDEC-toy-master/IDEC.py | """
Toy implementation for Improved Deep Embedded Clustering as described in paper:
Xifeng Guo, Long Gao, Xinwang Liu, Jianping Yin. Improved Deep Embedded Clustering with Local Structure
Preservation. IJCAI 2017.
The Autoencoder is pretrained directly in an end-to-end manner, NOT greedy layer-wise tr... | 9,906 | 42.073913 | 116 | py |
CE-OCL | CE-OCL-main/src/run_MLmodels.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# module load python/3.6.3
# module load sloan/python/modules/3.6
# srun --pty --mem=16G -p sched_mit_sloan_interactive python3
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn import tree
from sklearn.model_selection import GridSearchCV
fr... | 22,467 | 46.004184 | 123 | py |
Ranger-Deep-Learning-Optimizer | Ranger-Deep-Learning-Optimizer-master/setup.py | #!/usr/bin/env python
import os
from setuptools import find_packages, setup
def read(fname):
with open(os.path.join(os.path.dirname(__file__), fname)) as f:
return f.read()
setup(
name='ranger',
version='0.1.dev0',
packages=find_packages(
exclude=['tests', '*.tests', '*.tests.*', 't... | 696 | 24.814815 | 67 | py |
Ranger-Deep-Learning-Optimizer | Ranger-Deep-Learning-Optimizer-master/ranger/rangerqh.py | # RangerQH - @lessw2020 github
# Combines Quasi Hyperbolic momentum with Hinton Lookahead.
# https://arxiv.org/abs/1810.06801v4 (QH paper)
# #Lookahead paper --> MZhang,G Hinton https://arxiv.org/abs/1907.08610
# Some portions = Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed un... | 6,752 | 35.901639 | 107 | py |
Ranger-Deep-Learning-Optimizer | Ranger-Deep-Learning-Optimizer-master/ranger/ranger913A.py | # Ranger deep learning optimizer - RAdam + Lookahead + calibrated adaptive LR combined.
# https://github.com/lessw2020/Ranger-Deep-Learning-Optimizer
# Ranger has now been used to capture 12 records on the FastAI leaderboard.
#This version = 9.13.19A
#Credits:
#RAdam --> https://github.com/LiyuanLucasLiu/RAdam
#L... | 8,362 | 39.400966 | 133 | py |
Ranger-Deep-Learning-Optimizer | Ranger-Deep-Learning-Optimizer-master/ranger/ranger.py | # Ranger deep learning optimizer - RAdam + Lookahead + Gradient Centralization, combined into one optimizer.
# https://github.com/lessw2020/Ranger-Deep-Learning-Optimizer
# and/or
# https://github.com/lessw2020/Best-Deep-Learning-Optimizers
# Ranger has now been used to capture 12 records on the FastAI leaderboard.
... | 7,915 | 41.789189 | 169 | py |
Ranger-Deep-Learning-Optimizer | Ranger-Deep-Learning-Optimizer-master/ranger/ranger2020.py | # Ranger deep learning optimizer - RAdam + Lookahead + Gradient Centralization, combined into one optimizer.
# https://github.com/lessw2020/Ranger-Deep-Learning-Optimizer
# and/or
# https://github.com/lessw2020/Best-Deep-Learning-Optimizers
# Ranger has been used to capture 12 records on the FastAI leaderboard.
# Th... | 9,051 | 42.311005 | 176 | py |
RADio | RADio-main/dart/preprocess/nlp.py | import datetime
# if that doesn't work, do pip install -U numpy
# https://discuss.pytorch.org/t/valueerror-and-importerror-occurred-when-import-torch/5818
import nl_core_news_sm
import pandas as pd
import en_core_web_sm
from textblob import TextBlob
import textstat
import json
import os
import dart.Util
config = da... | 2,500 | 28.081395 | 90 | py |
acoustic-images-distillation | acoustic-images-distillation-master/setup.py | from setuptools import setup
setup(
name='codebase',
version='0.0.1',
packages=['codebase'],
install_requires=['librosa', 'numpy', 'tensorflow-gpu==1.4.0', 'torchfile'],
url='https://gitlab.iit.it/aperez/acoustic-images-distillation',
license='',
author='Andres Perez',
author_email='and... | 423 | 29.285714 | 81 | py |
acoustic-images-distillation | acoustic-images-distillation-master/codebase/models/soundnet.py | import tensorflow as tf
import tensorflow.contrib.slim as slim
import torchfile
def soundnet_arg_scope(is_training=True,
weight_decay=0.0001):
"""Defines the SoundNet arg scope.
Args:
is_training: Boolean flag indicating whether we are in training or not.
weight_decay: The ... | 15,910 | 51.167213 | 113 | py |
acoustic-images-distillation | acoustic-images-distillation-master/codebase/models/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 ... | 14,617 | 43.567073 | 166 | py |
synorim-merged | synorim-merged/pytorch/evaluate.py | import torch
import bdb, traceback, pdb
import importlib
import argparse
from pathlib import Path
from utils import exp
import numpy as np
from tqdm import tqdm
from dataset.base import DatasetSpec
def visualize(test_result, data):
try:
import open3d as o3d
except ImportError:
print("Please im... | 4,097 | 37.299065 | 120 | py |
synorim-merged | synorim-merged/pytorch/train.py | import argparse
import bdb
import importlib
import pdb
import shutil
import traceback
from pathlib import Path
import torch
from omegaconf import OmegaConf
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from utils import exp
def train_epoch():
global global_step
net_model.train()
... | 3,917 | 31.114754 | 112 | py |
synorim-merged | synorim-merged/pytorch/metric.py | import torch
class PairwiseFlowMetric:
def __init__(self, batch_mean: bool = False, compute_epe3d: bool = True, compute_acc3d_outlier: bool = False,
scene_level: bool = False):
"""
:param batch_mean: Whether to return an array with size (B, ) or a single scalar (mean)
:par... | 3,005 | 45.246154 | 113 | py |
synorim-merged | synorim-merged/pytorch/dataset/base.py | import collections
import multiprocessing
import torch
from numpy.random import RandomState
from torch.utils.data import Dataset
import zlib, json
from enum import Enum
class DatasetSpec(Enum):
FILENAME = 100
PC = 200
# Flow and masks are dictionary with key (view_i, view_j).
FULL_FLOW = 300
FULL... | 3,050 | 32.527473 | 109 | py |
synorim-merged | synorim-merged/pytorch/models/base_model.py | import functools
import importlib
import tempfile
from pathlib import Path
from typing import Mapping, Any, Optional, Callable, Union
import numpy as np
import torch
from torch import nn
from omegaconf import OmegaConf
from torch.optim.lr_scheduler import LambdaLR
from utils.exp import AverageMeter, parse_config_yaml
... | 3,644 | 37.776596 | 109 | py |
synorim-merged | synorim-merged/pytorch/models/basis_net_self.py | from collections import defaultdict
import torch
from torch.utils.data import DataLoader
from dataset.base import DatasetSpec as DS, list_collate
from dataset.flow_dataset import FlowDataset
from models.basis_net import Model as BaseModel
from models.desc_net_self import Model as DescModel
class Model(BaseModel):
... | 3,726 | 50.763889 | 108 | py |
synorim-merged | synorim-merged/pytorch/models/desc_net.py | import torch
import MinkowskiEngine as ME
from torch.nn import Parameter
from torch.utils.data import DataLoader
from dataset.base import DatasetSpec as DS, list_collate
from dataset.flow_dataset import FlowDataset, DataAugmentor
from metric import PairwiseFlowMetric
from models.spconv import ResUNet
from models.base... | 6,939 | 51.180451 | 113 | py |
synorim-merged | synorim-merged/pytorch/models/full_sync.py | from collections import defaultdict
import torch.linalg
from torch.utils.data import DataLoader
from dataset.base import DatasetSpec as DS, list_collate
from dataset.flow_dataset import FlowDataset
from metric import PairwiseFlowMetric
from models.base_model import BaseModel
import numpy as np
from utils.point impor... | 10,385 | 41.740741 | 119 | py |
synorim-merged | synorim-merged/pytorch/models/desc_net_self.py | from collections import defaultdict
import numpy as np
import torch
from torch.utils.data import DataLoader
from dataset.base import DatasetSpec as DS, list_collate
from dataset.flow_dataset import FlowDataset
from models.desc_net import Model as BaseModel
class Model(BaseModel):
"""
Self-supervised setting... | 4,150 | 48.416667 | 105 | py |
synorim-merged | synorim-merged/pytorch/models/basis_net.py | import random
from collections import defaultdict
import MinkowskiEngine as ME
import torch
import torch.nn.functional as F
from torch.nn import Parameter
from torch.utils.data import DataLoader
from dataset.base import DatasetSpec as DS, list_collate
from dataset.flow_dataset import FlowDataset, DataAugmentor
from m... | 19,450 | 48.874359 | 119 | py |
synorim-merged | synorim-merged/pytorch/models/spconv.py | import torch
import torch.nn as nn
import MinkowskiEngine as ME
import MinkowskiEngine.MinkowskiFunctional as MEF
class BasicBlockBase(nn.Module):
"""
A double-conv ResBlock with relu activation, with residual connection.
"""
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, ... | 4,471 | 38.22807 | 107 | py |
synorim-merged | synorim-merged/pytorch/utils/exp.py | import pickle
import random
from collections import OrderedDict
import sys
import numpy as np
import torch
import functools
from pathlib import Path
from omegaconf import OmegaConf
def seed_everything(seed: int):
"""
Setup global seed to ensure reproducibility.
:param seed: integer value
"""
rand... | 5,232 | 32.120253 | 110 | py |
synorim-merged | synorim-merged/pytorch/utils/point.py | import torch
def index_points_group(points, knn_idx, t=False):
"""
Input:
points: input points data, [B, N', C], or [B, C, N'](transposed)
knn_idx: sample index data, [B, N, K]
Return:
new_points:, indexed points data, [B, N, K, C] or [B, C, N, K](transposed)
"""
B, Np, C =... | 2,010 | 34.280702 | 109 | py |
stylegan3 | stylegan3-main/legacy.py | # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... | 16,561 | 50.117284 | 154 | py |
stylegan3 | stylegan3-main/gen_video.py | # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... | 7,283 | 39.243094 | 190 | py |
stylegan3 | stylegan3-main/avg_spectra.py | # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... | 12,693 | 44.826715 | 146 | py |
stylegan3 | stylegan3-main/gen_images.py | # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... | 5,735 | 38.287671 | 144 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.