sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
6bec9e9b44cb45bb0cd255f7616177a4630a45e0510bb2f7cb2d4a751df522fb | Python | 2,200 | 74 | from model.builders.JAMA_builders import any_cancer_JAMA
import os
from copy import copy, deepcopy
filename = os.path.basename(__file__)
# data_base ={'id':'progression','type': 'updated_label' , 'params': {'outcome': 'progression', 'text': 'NARR+IMPRESS', 'training_split':0}}
data_base ={'id':'progression','type': 'up... |
95b6d49b391bcd3e415311ed2c1f1ada806cf6be826d48a056bdd6349602b5bf | Python | 2,200 | 75 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
simulate_data.py: Routines to simulate spiking observations
from grid fields. Used for ground-truth for inference
routines.
"""
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
from lgcpsp... |
074bae17a228b84a23b637275d85dbc7f56f1cdd6b73af0e6a8556a5e5cd7224 | Python | 2,203 | 52 | import torch as th
import numpy as np
import scanpy as sc
import scipy as scp
from sklearn.model_selection import train_test_split
from latentvelo.utils import normalize, sparse_mx_to_torch_sparse_tensor
class DatasetNoGCN(th.utils.data.Dataset):
def __init__(self, adata, shuffle=True, test=0.1, random_seed=42):... |
90ca31b2ba4fcc4695f8ae2f2378a8e18405922889e590407e63e200cdcf28a2 | Python | 2,207 | 58 | import numpy as np
'''
Given sos and eos, it computes % to use in congig file for each predictions (every early-month form month 1 to the end
'''
### USER PART
# SOS and EOS in dek
sos = 7
eos = 21
### END OF USER PART
# The following is copied from a10
sosMonth = int(np.ceil(sos / 3)) # note ceil makes it correct, th... |
ae6dd1b7b72545f3f966c7d3b836a3dbeea43e291411c8b51f51deb2545e805c | Python | 2,207 | 88 | # This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed
# under the Apache License Version 2.0, see <https://www.apache.org/licenses/>
# flake8: noqa
from sbi.utils.analysis_utils import get_1d_marginal_peaks_from_kde
from sbi.utils.io import get_data_root, get_log_root, get_project_root
... |
af48ed74da00f2b12174e2a2436cbe756427a5e509cb96c09a2acc1a6197a4ff | Python | 2,208 | 61 | """Installed-wheel CPU smoke test; run with ``python -I`` outside the checkout.
This intentionally exercises the public calculator with one released .pt model,
including shipped model configuration and long-range parameter assets. Model
weights use the normal AIMNet cache/download mechanism.
"""
import importlib
impo... |
3fed480c9d9ea4b239c46f98ea812b30a0b62df7a6c81ac083f874633be25e4a | Python | 2,209 | 64 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
3af5e0528d899ccad297f340d731dfbeadd36e2090592e7153b1a7c8d4de4c8f | Python | 2,214 | 76 | from model.builders.JAMA_builders import any_cancer_JAMA
import os
from copy import copy, deepcopy
filename = os.path.basename(__file__)
data_base ={'id':'response','type': 'updated_label' , 'params': {'outcome': 'response', 'text': 'NARR+IMPRESS', 'training_split':0}}
# training_splits = [0,1,4,6,7,9]
# number_report... |
a14ea6a12dbce6121dea4de9669d6eb00006e3893cdef1ab8003e7b5a6992118 | Python | 2,216 | 62 | import argparse
import logging
import os
import socket
import sys
import numpy as np
import psutil
import setproctitle
import torch
# add the FedML root directory to the python path
sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../")))
from fedml_api.distributed.decentralized_framework.algorithm_... |
ef5993b1a79a7994aa1fe83b81c50cac59a6188499bca485b5bbd9485a510104 | Python | 2,217 | 48 | import numpy as np
from skimage.transform import resize
class Resize:
def __init__(self, load_size, interp="bilinear", training=True):
"""
Resize the image: C x H x W to the C x load_size[0] x load_size[1]
order will apply to image and mask separately. 0: nearest-neighbor, 1: bi-linear(def... |
b9fe792419fa5c591eae53e439fcdda949ac101739dbe9c79ad0157fc47dce7b | Python | 2,220 | 77 | import torch
import torchvision.transforms
from PIL import Image
import numpy as np
from utils.constants import IMAGENET_MEAN, IMAGENET_STD
from utils.utils import IOU, visualize_wall, accuracy
from utils.constants import DEVICE
from tqdm import tqdm
def validation_step(segmentation_module, loader, writer, epoch):
... |
65604145e2443d70fb42cf2bd939bf81dadf4570b851c0916804607103b0ce9f | Python | 2,228 | 76 | from model.builders.JAMA_builders import any_cancer_JAMA
import os
from copy import copy, deepcopy
filename = os.path.basename(__file__)
data_base ={'id':'progression','type': 'updated_label' , 'params': {'outcome': 'progression', 'text': 'NARR+IMPRESS', 'training_split':0, 'split_path': 'splits_new'}}
# training_spli... |
0cf06cb034d785c2faa136e1c90d14d216760a9b5d5c08e4f439bf9f5745736f | Python | 2,231 | 65 | import sys
from rdkit import Chem
import numpy as np
import pandas as pd
import time
from serenityff.charge.tree.tree import Tree
tree_pruned_folder = "./tree"
sdf_file_path = "./test.sdf"
# get jobindex as argument
jobindex = int(sys.argv[1])
sys.setrecursionlimit(10000)
mol_sup = Chem.SDMolSupplier(sdf_file_path,... |
478ca8abba1677f032b99704a0f82262be8477df126f654c19333b0647870f17 | Python | 2,231 | 62 | import os
import time
import nibabel as nib
import numpy as np
import scipy.io as sio
meg_dir = '/path/to/megdata/and/results/'
parcellationDir = '/path/to/SchaeferParcellation/fslr4k/'
# load subj list
subjList = sio.loadmat(os.path.join(meg_dir, 'myMEGList.mat'))['myMEG']
subjList = [subjList[i][0][0][4:] for i in... |
68854a1f1c25b5211f0631ba9951d305bc1d792f26f419f64d65dfbc7b94f75c | Python | 2,239 | 80 | from typing import Tuple, Any, Dict, Callable, TypeVar
import numpy as np
import pytest
import foolbox as fbn
import eagerpy as ep
distances = {
0: fbn.distances.l0,
1: fbn.distances.l1,
2: fbn.distances.l2,
ep.inf: fbn.distances.linf,
}
data: Dict[str, Callable[..., Tuple[ep.Tensor, ep.Tensor]]] = {}... |
9198a1688600870c71633f2d98f8ff44729574a72e8c6c59d8817abd9dee68ee | Python | 2,241 | 63 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from suite2p.extraction import dcnv
def correct_suite2p_outputs(F, iscell, Fneu, neu_factor=0.7):
nROIs, nFrames = F.shape
print('Number of ROIs: ', nROIs)
print('Number of frames: ', nFrames)
cells_index = np.flatnonzero(iscell[:,... |
4351984324f43a286a52b95f4d74e936c8db5eea6644a478c8440c2c6daa6561 | Python | 2,242 | 85 | # This script shows how to use the Atomic Simulation Environment Calculator (ASE)
# inferface of TorchMD-Net with an AceFF model
import time
import sys
import ase
from ase.io import read
from torchmdnet.calculators import TMDNETCalculator
# The AceFFs models are available from HuggingFace under an Apache2.0 license
fr... |
5afa53575b5bbd4a0b3e196a643883216d4eb1c65f17435f0684f3b76e1c7c91 | Python | 2,242 | 76 | from model.builders.JAMA_builders import any_cancer_JAMA
import os
from copy import copy, deepcopy
filename = os.path.basename(__file__)
data_base ={'id':'response','type': 'updated_label' , 'params': {'outcome': 'response', 'text': 'NARR+IMPRESS', 'training_split':0, 'split_path': 'splits_new'}}
# training_splits = [... |
b865611583dde5ebe2356c4cd1be8d6e02092325672661e61272f843c976c62d | Python | 2,243 | 67 | import sys
from rdkit import Chem
# import numpy as np
import pandas as pd
import time
from serenityff.charge.tree.tree import Tree
tree_pruned_folder = "./tree"
sdf_file_path = "./test.sdf"
# get jobindex as argument
jobindex = int(sys.argv[1])
mol_sup = Chem.SDMolSupplier(sdf_file_path, removeHs=False)
print(len(... |
df09573f4c9150b14fe53f0df657be2db5119f8958aaab39eb108f2c78fae38c | Python | 2,250 | 73 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 21 17:34:13 2021
@author: fhu14
Module used to load in gammas that were precomputed per fold.
"""
#%% Imports, definitions
import os, pickle, re
from typing import List
#%% Code behind
def load_elems_per_fold(data_path: str, pattern: str) -> List:
r"""Generic loadi... |
e50df6a156706146d5e7dc8412326d4f5c0d8e00bbe0ee86a259879543b229aa | Python | 2,250 | 64 | import os
import h5py
import numpy as np
from .progress_bar import progress_bar
class SysBioData(object):
def __init__(self,
filename,
camera, mover,
channel=None):
self.filename = filename
self.prefix = "/" + channel + "/" if channel else "/"
... |
636f8bc044efe8629d54faa8e9384b83c0126c4b622ed0cc40aeb4d00ab9d5d1 | Python | 2,252 | 71 | import torch
from torch import nn
from pulses_dens import PulsesDataset
from torch.utils.data import DataLoader
import models
from torch.utils.data import random_split
import torch.optim as optim
import numpy as np
import pandas as pd
#Params
BATCH = snakemake.config['batch']
SPLIT = snakemake.config['split']
LR = sna... |
2204cedecf729294c5c281665cdc8b940aebcab3d4609a0522ffe17f148f6438 | Python | 2,254 | 48 | import numpy as np
from skimage.transform import resize
class Resize:
def __init__(self, load_size, interp="bilinear", training=True):
"""
Resize the image: C x H x W to the C x load_size[0] x load_size[1]
order will apply to image and mask separately. 0: nearest-neighbor, 1: bi-linear(def... |
8516a34e63d6098e6ba2ade5aec77dd19aa2e3b23fc88770bd957f3370f6c5a1 | Python | 2,256 | 110 | qualification_feat = [
'grade',
# 'sub_grade',
# 'emp_title',
'emp_length',
'home_ownership',
'annual_inc_comp',
# 'annual_inc',
# 'annual_inc_joint',
'verification_status',
# 'verification_status_joint',
# 'issue_d',
# 'earliest_cr_line',
'total_rev_hi_lim',
'tot... |
8a944cd464c34572427bc2607d99dee96e3c05245c1f971cdf6a48cec30a948e | Python | 2,256 | 64 | import logging
import os
import torch.utils.data as data
from PIL import Image
from torchvision import transforms
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
class Landmarks(data.Dataset):
def __init__(self, data_dir, allfiles, dataidxs=None, train=True, transform=None, tar... |
bb5ff42d7ee058c3987e83add732dea59182eb0c39b10ff0635714b21d5d9993 | Python | 2,256 | 58 | import logging
from mpi4py import MPI
from .FedSegAggregator import FedSegAggregator
from .FedSegTrainer import FedSegTrainer
from .FedSegClientManager import FedSegClientManager
from .FedSegServerManager import FedSegServerManager
from .MyModelTrainer import MyModelTrainer
def FedML_init():
comm = MPI.COMM_WOR... |
dec8d75c588e56f0e58ed7800466fdf98695c2f0a8a146c3aed3c524ed53720b | Python | 2,256 | 58 | import logging
from mpi4py import MPI
from .FedGanAggregator import FedGanAggregator
from .FedGanTrainer import FedGanTrainer
from .FedGanClientManager import FedGanClientManager
from .FedGanServerManager import FedGanServerManager
from .MyModelTrainer import MyModelTrainer
def FedML_init():
comm = MPI.COMM_WOR... |
5d02b7ea2ee442d3fd6754bd865d464281a20ba7f4c3674da764c9ab9d1205a8 | Python | 2,258 | 70 | # Copyright (c) OpenMMLab. All rights reserved.
from mmcv.runner import build_optimizer
from mmcv.runner.optimizer import OPTIMIZER_BUILDERS as MMCV_OPTIMIZER_BUILDERS
from mmcv.utils import Registry, build_from_cfg
OPTIMIZERS = Registry('optimizers')
OPTIMIZER_BUILDERS = Registry(
'optimizer builder', parent=MMCV... |
cb0be0c47ca66bc7b42ec9341adf08573e0176d5bf52c80642e5a6f5bcde5b10 | Python | 2,258 | 70 | import torch
from torch import nn
from utils import PulsesDataset
from torch.utils.data import DataLoader
import models
from torch.utils.data import random_split
import torch.optim as optim
import numpy as np
import pandas as pd
#Params
BATCH = snakemake.config['batch']
SPLIT = snakemake.config['split']
LR = snakemake... |
d54631109e2e903503dfe132d2ec7fb2a503ea6f1766ed5ae7d80d9d09e93dad | Python | 2,258 | 78 | import os
import sys
import pandas as pd
import numpy as np
from sklearn import datasets
from sklearn.svm import SVR
sys.path.append(os.path.join('..', '..'))
import pywinEA2
def getDataset() -> pd.DataFrame:
""" Create the testing dataset """
X, y = datasets.make_friedman1(
n_samples=N... |
17c18bfd94323aa0aa86f90657959eb4c4045e8e57c07086381a4657af6422c3 | Python | 2,259 | 75 | import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing.text import one_hot
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Embedding, Dense
from tensorflow.keras.models import load_model... |
cd411c005e6cd7f6d7e1c4909a52fd7c107f2c428220e53c71c36b34618100db | Python | 2,259 | 42 | import numpy as np
import pandas as pd
from sklearn.feature_selection import SelectPercentile, f_regression
from sklearn.pipeline import make_pipeline, make_union
from sklearn.preprocessing import Binarizer
from sklearn.svm import LinearSVR
from tpot.builtins import StackingEstimator
from tpot.export_utils import set_p... |
36864e6bccb8697deeed19045511dc6632ed981a4085bdc0cc35d50779ef1606 | Python | 2,261 | 75 | ''' adapted from https://github.com/all-umass/ManifoldWarping '''
''' Inter-data correspondences '''
import numpy as np
class Correspondence(object):
def __init__(self, pairs=None, matrix=None):
assert pairs is not None or matrix is not None, \
'Must provide either pairwise or matrix correspondences'
... |
542d8672dad1efb45e71f2b1c7fad8eac70044fc7505eea2d52026aa83cd91dd | Python | 2,261 | 57 | from .utils import transform_tensor_to_list
class AsDGanTrainer(object):
def __init__(self, client_index, train_data_local_dict, train_data_local_num_dict,
test_data_local_dict, device, args, model_trainer):
self.trainer = model_trainer
self.client_index = client_index
s... |
52676c5d8e731be10ada8c2414d356351945b6fc2705a8246ac4d5a17d6b62db | Python | 2,263 | 62 | import torch
import torch.nn as nn
from src.models.temp_embedding import MobilityEncoderNet
class WHODASPredictor(MobilityEncoderNet):
"""
Recurrent neural network regression with self-attention.
Model description:
* T2V for half-hourly data embedding
* LSTM or GRU encoder for the embedde... |
7d8ed0d696dff943ad055bf213329ab7e09285e8135cea542a381183143e6932 | Python | 2,263 | 65 | """Offline regressions for atomic cache publication."""
import io
from http.client import RemoteDisconnected
from urllib.error import URLError
import pytest
from brainstat._utils import _download_file
class InterruptedStream(io.BytesIO):
def read(self, size=-1):
if self.tell():
raise Remote... |
c2822ceca6edbf575238187e9ba064852fe5e2bc7a72efe0cee93d9fe0f5a535 | Python | 2,264 | 66 | from model.builders.builders import build_full_network
import os
filename = os.path.basename(__file__)
from copy import copy, deepcopy
vocab_size = 20000
data_base ={'id':'progression','type': 'updated_label' , 'params': {'outcome': 'progression', 'text': 'NARR+IMPRESS', 'training_split':0}}
# training_splits = [0,1... |
4e4624bb6330ce4aea48add1b4fd6f900a2a8b10b64149ce13fb85b4fe5f5e21 | Python | 2,265 | 69 | import os
import sys
argv = sys.argv[1:]
root_dir = os.path.dirname(os.path.abspath(__file__))
dist_dir = os.path.join(root_dir, "dist")
dist_pypi_dir = os.path.join(dist_dir, "pypi")
def _build():
import shutil
source_dir = os.path.join(root_dir, "source")
shutil.rmtree(os.path.join(source_dir, "__pycac... |
a0b5946ee7bd5c1753b119b9cc8d5a37288f9ce3eecc7162f190a8b50d9df3bd | Python | 2,266 | 61 | # credit: https://github.com/davda54/sam
import torch
class SAM(torch.optim.Optimizer):
def __init__(self, params, base_optimizer, rho=0.05, adaptive=False, **kwargs):
assert rho >= 0.0, f"Invalid rho, should be non-negative: {rho}"
defaults = dict(rho=rho, adaptive=adaptive, **kwargs)
su... |
446326818a258117ac61e63bd1484b04c6063da5f6bf69ee4a626ba4218f4654 | Python | 2,270 | 56 | import multipagetiff as mtif
import argparse
import logging
import os
import numpy
from . import utils
from ..registration import register_with_ANTs
def main(*args, **kwargs):
parser = argparse.ArgumentParser(description="Run the registration of the given stacks using ANTs.\
Example: scape_registratio... |
7008b7f5e8f060a9bee682344a2d6cbf497b116f6556c3e1bf70910a0e694ca4 | Python | 2,270 | 52 | # Copyright (c) OpenMMLab. All rights reserved.
from mmcv.parallel import is_module_wrapper
from mmcv.runner.hooks import HOOKS, Hook
@HOOKS.register_module()
class YOLOXModeSwitchHook(Hook):
"""Switch the mode of YOLOX during training.
This hook turns off the mosaic and mixup data augmentation and switches
... |
7887539274fbf14aa8d611d691e25e2824183693e14c287b14eb6635084f5310 | Python | 2,270 | 52 | import argparse
import pandas as pd
import os
import numpy as np
def main(args):
patients_dir = sorted([el for el in os.listdir(args.project_path) if el.startswith('Patient')])
till_csv = 'VTA_tracts/plot/outcomes/Depression_scales_evolution.csv'
table_dict = {}
baseline_dict = {}
for pat in ... |
f3a005055d1a518df3c8b531a348ec1fc2ac2c28ff7785667fe76e0373de1199 | Python | 2,274 | 54 | # -*- coding: UTF-8 -*
import numpy as np
class Graph(object):
''' Note: adj_list shows each edge twice. So edge_num is really two times of edge number for undirected graph.'''
def __init__(self, node_num, edge_num, weighted):
self.G=None
self.node_num = node_num # n
self.edge_num = e... |
19e089ecd8c1691f2e0af1f2873b0c20e35c437faae1d7377e60ea701065c81a | Python | 2,275 | 62 | import torch
import torch.nn as nn
def get_activation_function(activation: str) -> nn.Module:
"""
Gets an activation function module given the name of the activation.
Supports:
* :code:`ReLU`
* :code:`LeakyReLU`
* :code:`PReLU`
* :code:`tanh`
* :code:`SELU`
* :code:`ELU`
:param... |
6c25c431b89fec5d2dce16c30f06027359015c8b62459bac692c90857d5d9490 | Python | 2,275 | 77 | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmpose.models import HourglassAENet, HourglassNet
def test_hourglass_backbone():
with pytest.raises(AssertionError):
# HourglassNet's num_stacks should larger than 0
HourglassNet(num_stacks=0)
with pytest.raises(... |
999095fe7cf39467477e8ae1e0886d20d5c0fd8248cd9973fb7c442b619545fc | Python | 2,276 | 96 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 10 14:26:41 2021
@author: fhu14
Contains all the constant namedtuple to ensure that all the code that's built
on top of this uses the same objects
I hate relative import systems in Python!
"""
from collections import namedtuple
#%% Model constants
RawData = namedtuple... |
bcaf6374970c5d610bb20a021975819faa036c265c21a96bbf37a6f0115cae90 | Python | 2,279 | 57 | import numpy as np
import matplotlib.pyplot as plt
from rdkit import Chem
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Draw
from rdkit.Chem.Draw import IPythonConsole
from rdkit.Chem import Descriptors
from rdkit.Chem import AllChem
from rdkit import DataStructs
from rdkit.Chem.Draw import SimilarityM... |
749f0c4b6fdfcf6156396ed0a3766316b12b28afa4df4af50c056a2753da8886 | Python | 2,283 | 63 | # Author: Alfred Lim
# Location: Singapore
# Date: 2021-11-27
# Task: apply vowel-centered slot-based coding scheme to orthography
# Reference: Lim, O'Brien, & Luca (submitted)
import re
import numpy as np
import pandas as pd
import sys
# Define function that finds the position of the first vowel
def firs... |
87f08ff2e44fa962dde38a622e28579a7949fce556cbbd5b9a5f30987d27da7d | Python | 2,283 | 58 | import numpy as np
class ExpRandomCrop3d:
"""
Crop the 3D numpy [c, h, w, d] and mask [d, 2] in a sample
"""
def __init__(self, output_size, padding=0, training=True):
assert isinstance(output_size, (int, list, tuple))
if isinstance(output_size, int):
self.output_size = (o... |
95ab46aa4d8d79847b8dd570cd3c1347c1fd1eae75c194066951bed40245d09b | Python | 2,287 | 63 | from dataclasses import dataclass
import numpy as np
import typing
from osgeo import osr, gdal, gdal_array
from georeferenced_data import GeoreferencedRaster
from scope_utils import Scope, Extent
@dataclass(init=False)
class BathymetryEstimations(GeoreferencedRaster[np.ndarray]):
def __init__(self, data: np.nd... |
607c7545e90c105aa9499e3233ed0faa862116905f101f82286971e0cd5408f8 | Python | 2,288 | 77 | from typing import Tuple
import foolbox as fbn
import eagerpy as ep
def test_correct_unperturbed(
fmodel_and_data: Tuple[fbn.Model, ep.Tensor, ep.Tensor]
) -> None:
fmodel, inputs, _ = fmodel_and_data
perturbed = inputs
logits = fmodel(perturbed)
labels = logits.argmax(axis=-1)
is_adv = fbn.M... |
74dda710ac1f3f0ea3f453c338e43241239fe980f3cf68b580224f4820ec1ac1 | Python | 2,290 | 73 | """
Evaluate a trained sleep stage classification model.
This script loads a pre-trained model and evaluates it on validation or test
datasets, computing per-class and aggregate metrics.
Usage: see run.md in config folder
The script:
1. Loads the trained model specified in the config (model.path)
2. Runs evaluation ... |
3aa8437d390cbf48df80b3f93842f435ccfdba1e23914281b7097f4d21c2220e | Python | 2,291 | 61 | import torch
from torch.nn import functional as F
def make_one_hot(labels, C=2):
size_list = labels.size()
new_size = [size_list[0]] + [C] + list(size_list[1:])
one_hot = torch.zeros(new_size).cuda()
target = one_hot.scatter_(1, labels.unsqueeze(1), 1)
return target
def dice_loss(input, target,... |
774e93b82d6a372864c01d25fb5eea04f0447e588fa11cf516f1a645a86cc137 | Python | 2,291 | 58 | # October 11th 2017
# Functions to work with figures
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D, proj3d
import numpy as np
import numpy.linalg as la
def ref_axes(ax,labels=True):
ax.tick_params(axis='x', which='both', direction='out', length=10, labelsize=20
, pad=-7)
ax.xax... |
47e173e9bee3893c4c2be05787ce3ac574bdf7ea2777f20a2a294f06d2d230b3 | Python | 2,292 | 78 | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import tempfile
import numpy as np
import torch
from mmpose.models.utils import SMPL
from tests.utils.mesh_utils import generate_smpl_weight_file
def test_smpl():
"""Test smpl model."""
# build smpl model
smpl = None
with tempfil... |
c240a0bd6d313b941b0e11eb0166cedf2f7906c44f26b41b80c4872b6d96e8cb | Python | 2,292 | 47 | """The stream on which the engines of this package are warmed up and captured."""
from __future__ import annotations
import threading
import torch
_STREAMS: dict[int, torch.cuda.Stream] = {}
_STREAMS_LOCK = threading.Lock()
def capture_stream(device: torch.device) -> torch.cuda.Stream:
"""One side stream per ... |
362288b5d70907233b69cc7f2e09cf8d23b9b8e59954a8f2e0e45a2d3eb9ee93 | Python | 2,293 | 59 | import logging
from mpi4py import MPI
from .AsDGanAggregator import AsDGanAggregator
from .AsDGanTrainer import AsDGanTrainer
from .AsDGanClientManager import AsDGanClientManager
from .AsDGanServerManager import AsDGanServerManager
from .DModelTrainer import DModelTrainer
from .GModelTrainer import GModelTrainer
de... |
822e7236be9d46ab77338638d66822994f52ca6bd131ba20482c69d601a645de | Python | 2,293 | 56 | import pandas as pd
import numpy as np
from os.path import join, dirname
dir_path = dirname(dirname(__file__))
dir_path = dir_path.replace('clinicalNLP2', 'clinicalNLP')
input_dir = join(dir_path, 'medical_notes/input/radiology_impressions_derived_data')
filename = join(input_dir, 'manual_label_analysis.csv')
label_... |
b22f8e8fa1cdbe8766833b09124373ed1a4df37aa19e8abd6c85979a8ab2b341 | Python | 2,293 | 80 | """Configuration file for the Sphinx documentation builder."""
import inspect
import os
import subprocess
import sys
import gradient_accumulator
# Project information
url = "https://github.com/andreped/GradientAccumulator"
# General configuration
master_doc = 'index'
# Sphinx extension modules
extensions = [
... |
b40540c762d09cd87e4a58c1abc12a2ede7e44c8ab979ae92d159809182f9854 | Python | 2,293 | 72 | import torch
import torch.nn as nn
import torch.optim as optim
class DenseModel(nn.Module):
def __init__(self, input_dim, output_dim, learning_rate=0.01, bias=True):
super(DenseModel, self).__init__()
self.classifier = nn.Sequential(
nn.Linear(in_features=input_dim, out_features=output... |
2a7dd2416c22cb7c1e5a662f6f6d60de9cb8348921c32ee53b33750b3684733a | Python | 2,295 | 58 | import logging
from mpi4py import MPI
from .FedMedGanAggregator import FedMedGanAggregator
from .FedMedGanTrainer import FedMedGanTrainer
from .FedMedGanClientManager import FedMedGanClientManager
from .FedMedGanServerManager import FedMedGanServerManager
from .MyModelTrainer import MyModelTrainer
def FedML_init():... |
351028a1807bbc723575a8ea073841da806441fb44dbe4167c63b8794f5bd936 | Python | 2,299 | 66 | # General parameter interface information:
# Dictionary: par = parDict['C-N']
# Constructor: par = SkfInfo(name='C-N', paramPath='./mio-0-1')
# Getters:
# par.GetSkInt(key='Hss0', dist=1.5)
# par.GetAtomProp(key='Es')
# par.GetRep(dist=1.5)
# SKF parameter interface:
import os
from SKF import SkfInfo
PARAMPATH... |
9c1808a15e246abb358af65681760cd98eaa946838924d6716f0c9d142866bff | Python | 2,302 | 54 | import argparse
import os
import numpy as np
def main():
parser = argparse.ArgumentParser(description='Selbstaufsicht Weakly Supervised Contact Prediction Script')
# Pre-trained model
parser.add_argument('--log-path', type=str, help="Path to logging data of the specific downstream run to be evaluated.")
... |
845135fada653de0fb18a0e97805bb4fa778499d0b725811172a3f4aa9cdf6e2 | Python | 2,304 | 69 | import numpy
class MyOVBox(OVBox):
def __init__(self):
OVBox.__init__(self)
self.nChannel = 0
self.sampling = 0
self.epochSampleCount = 0
self.startTime = 0.
self.endTime = 0.
self.dimensionSizes = list()
self.dimensionLabels = list()
self.timeBuffer = list()
self.signalBuffer = None
self.signal... |
cad29f0fb3d5eb0ebc19da585bbd2e2c6724a5c07d3922d8a4f07d8d91c1e6c2 | Python | 2,306 | 38 | import torch
class ModelArgs():
def __init__(self, conv_layers_num, model_dim, dense_layers_num, hidden_size, dropout,
batchnorm=False, loss_function='mse', device=None):
"""
Class that keeps arguments required to build chemprop.model.MoleculeModel
but with graphconv.GraphC... |
05f7c9d6fa78622df61c086c30067bf35859898b2ee3ac2d5eb747a18b5f1ca5 | Python | 2,307 | 77 | # Copyright (c) OpenMMLab. All rights reserved.
from mmdet.models.builder import HEADS
from .convfc_bbox_head import ConvFCBBoxHead
@HEADS.register_module()
class SCNetBBoxHead(ConvFCBBoxHead):
"""BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_.
This inherits ``ConvFCBBoxHead`` with modified forwar... |
c2055a95e23e606a0a2838c0a5e9c5605fd595be438674cbed14ffdce6e22473 | Python | 2,308 | 65 | # Author: Alfred Lim
# Location: Singapore
# Date: 2021-11-27
# Task: create binary phonological vectors for neural networks
# Reference: Lim, O'Brien, & Luca (submitted)
# Import libraries
import re
import numpy as np
import pandas as pd
# Make use of PyTorch for binary encoding
import torch
# Define function to get... |
68da79f5ffa8f186d476b9d0c292ad71b81b4426e5bf699660a4c2893eab4ca6 | Python | 2,309 | 50 | import os
import sys
# os.system("module purge")
cmd = "../../install/x86_64/bin/nrnivmodl ../../src/all_mechanisms"
if not os.path.isdir("./x86_64"):
os.system(cmd)
# generate binary dataset file for DeepDendrite
# @param1: original dataset file (*.npz)
# @param2: fold to save binary dataset file
# stim_img_trai... |
5d72e0cb8c97b65c24f1aab753cadcee1458a889fdb4c054839f110aeff25ba7 | Python | 2,310 | 67 | # Copyright (c) OpenMMLab. All rights reserved.
from mmcv.runner.hooks import HOOKS
from mmcv.runner.hooks.lr_updater import (CosineAnnealingLrUpdaterHook,
annealing_cos)
@HOOKS.register_module()
class YOLOXLrUpdaterHook(CosineAnnealingLrUpdaterHook):
"""YOLOX learning ra... |
6433c7b390844d75aa29866c2dbde47c318d01414b96185ef7045ce4255b1531 | Python | 2,310 | 67 | # Copyright (c) OpenMMLab. All rights reserved.
from mmcv import Config
from mmpose.datasets.builder import build_dataset
def test_concat_dataset():
# build COCO-like dataset config
dataset_info = Config.fromfile(
'configs/_base_/datasets/coco.py').dataset_info
channel_cfg = dict(
num_ou... |
08605846e70abd930f171d10f6466cde02fc9b2275ebf1c925b9a84abd1702b5 | Python | 2,311 | 87 | # -*- coding: utf-8 -*-
"""Logger, taken from Torch WC book"""
__author__ = "Sean Benson"
__copyright__ = "MIT"
import logging.handlers
import datetime
import time
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
# Some libraries attempt to add their own root logger handlers. This is
# annoying ... |
3c671be785cf8c2aac80e5883c56e96edbccea62118ef74902dd6990d01a1325 | Python | 2,312 | 75 | from typing import Tuple, Any, Optional
import numpy as np
import eagerpy as ep
def images(
images: Any,
*,
n: Optional[int] = None,
data_format: Optional[str] = None,
bounds: Tuple[float, float] = (0, 1),
ncols: Optional[int] = None,
nrows: Optional[int] = None,
figsize: Optional[Tupl... |
ca8e7a793a3288671860559950c0467cec343d37fdcd49182c35943a6a4f4378 | Python | 2,313 | 73 | #!/usr/bin/env python3
import torchvision.models as models
import eagerpy as ep
from foolbox import PyTorchModel, accuracy, samples
import foolbox.attacks as fa
import numpy as np
if __name__ == "__main__":
# instantiate a model (could also be a TensorFlow or JAX model)
model = models.resnet18(pretrained=True... |
fa4be6e8ca497bf6b130429757357f6c8a9e992cc3a74e581f1b44b83e880995 | Python | 2,314 | 53 | import torch as th
import numpy as np
import scanpy as sc
import scipy as scp
from sklearn.model_selection import train_test_split
from latentvelo.utils import normalize, sparse_mx_to_torch_sparse_tensor
class ANVIDatasetNoGCN(th.utils.data.Dataset):
def __init__(self, adata, shuffle=True, test=0.1, random_seed=... |
1a8603d5f0d00d4bb150687271378a5fa545d4841514387e3495ae64120bd7fc | Python | 2,319 | 56 | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
from ..builder import BBOX_SAMPLERS
from .random_sampler import RandomSampler
@BBOX_SAMPLERS.register_module()
class InstanceBalancedPosSampler(RandomSampler):
"""Instance balanced sampler that samples equal number of positive sample... |
850b48d16df0a39cd34f55b36047b5259a2f2d1bdcd52b11ffd69fc229f0e2cd | Python | 2,319 | 71 | import numpy as np
from importlib import reload
import sys
sys.path.insert(2,'support')
import functions
reload(functions)
import functions as f
import parameters
reload(parameters)
import parameters as p
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams.update({'font.size': p.fontsize})
plasticity... |
1dd36776238b15eb6e94f49d46a9e90dedc59832d4963b875205004547364475 | Python | 2,321 | 65 | """test_malloc.py
This file is part of the test suite for keras2c
Implements tests for dynamic memory allocation
"""
#!/usr/bin/env python3
import unittest
from tensorflow import keras
from keras2c import keras2c_main
import time
from test_core_layers import build_and_run
__author__ = "Rory Conlin"
__copyright__ = ... |
100acc960949ef70aea0597dfc7edd9742280f0e77a181badd763a830ef923b5 | Python | 2,324 | 65 | import codecs
import pathlib
import re
import warnings
import zipfile
from typing import Optional, Tuple
from .util import get_nonroot_uuid, get_root_uuid
_VERSION_MATCHER = (
r'QIIME 2\n'
r'archive: [0-9]{1,2}$\n'
r'framework: '
r'(?:20[0-9]{2}|2)\.(?:[1-9][0-2]?|0)\.[0-9](?:\.dev[0-9]?)?'
r'(?:\... |
09fa2e019a984e1a45c1d6bdd36257ded432b0fde2ad50e1d1ad46a8a3f4fd7f | Python | 2,326 | 54 | import numpy as np
from skimage.transform import resize
class Scale:
def __init__(self, load_size: int, interp="bilinear", training=True):
"""
Scale the image:
Input format: image: C x H x W mask: H x W
The output size will be matched smaller edge of the image.
If height >... |
20a8f3161ae961d05b34b496102276959d4489a9095bb1bd52d9bb52dc8f8d59 | Python | 2,326 | 67 | #!/usr/bin/env python3
import tensorflow as tf
import eagerpy as ep
from foolbox import TensorFlowModel, accuracy, samples, Model
from foolbox.attacks import LinfPGD
def main() -> None:
# instantiate a model (could also be a TensorFlow or JAX model)
model = tf.keras.applications.ResNet50(weights="imagenet")
... |
2620b71982f0e139b93627218aab42556f2aa1f7a64b57e69e60f8cbb781d2a9 | Python | 2,327 | 77 | from model.builders.JAMA_builders import any_cancer_JAMA
import os
from copy import copy, deepcopy
filename = os.path.basename(__file__)
data_base ={'id':'progression','type': 'updated_label' , 'params': {'outcome': 'progression', 'text': 'NARR+IMPRESS', 'training_split':0, 'split_path': 'splits_new'}}
# training_spli... |
5f2691a99e6c003c5ff80fc72fb7cca40aa35ee9e3902dbfdfddb4dcda1aa646 | Python | 2,327 | 63 | from typing import Tuple
import foolbox as fbn
import eagerpy as ep
import pytest
ModelAndData = Tuple[fbn.Model, ep.Tensor, ep.Tensor]
def test_accuracy(fmodel_and_data: ModelAndData) -> None:
fmodel, x, y = fmodel_and_data
accuracy = fbn.accuracy(fmodel, x, y)
assert 0 <= accuracy <= 1
assert accur... |
cae6ae0a3dc42ffe78c6524a46f7358407e6f0363a5cd4dd0611290b6c7f3115 | Python | 2,327 | 87 | import numpy as np
from mmdet.core.evaluation.mean_ap import eval_map, tpfp_default, tpfp_imagenet
det_bboxes = np.array([
[0, 0, 10, 10],
[10, 10, 20, 20],
[32, 32, 38, 42],
])
gt_bboxes = np.array([[0, 0, 10, 20], [0, 10, 10, 19], [10, 10, 20, 20]])
gt_ignore = np.array([[5, 5, 10, 20], [6, 10, 10, 19]]... |
d30e8fabc79a7af5cbba0198829cc5b5cbf1f9104bee3129fb3405152e707502 | Python | 2,327 | 64 | import sys
import json
import requests
import numpy as np
import pandas as pd
import joblib
sys.path.insert(0, "Classifier")
import SMART_3
import get_highlight
# Loading database into memory
DB, index_super = SMART_3.load_db(db_folder="./Classifier")
def search_smart3(nmr_data_df, output_image=None, channel=1, mw_f... |
5cd8c2e40136a867b0716d3f77195fe54e653190a823c8f792a1653955f12801 | Python | 2,332 | 44 | import numpy as np
import pandas as pd
from sklearn.pipeline import make_pipeline, make_union
from sklearn.preprocessing import MaxAbsScaler, RobustScaler
from tpot.builtins import StackingEstimator
from tpot.export_utils import set_param_recursive
from metstab_shap.grid import SVC_poly, SVC_rbf, SVC_sigmoid
from mets... |
a286d0924184bdc7c0ccd8a98ebdb4024e7cbc178d712dcf3a5a7d0d6793aa9b | Python | 2,333 | 53 | from .utils import transform_tensor_to_list
class FedAVGTrainer(object):
def __init__(self, client_index, train_data_local_dict, train_data_local_num_dict, test_data_local_dict,
train_data_num, device, args, model_trainer):
self.trainer = model_trainer
self.client_index = client... |
aad0d3874c687d8229c58966b00e2888b002bcffad528cc67615957ef05afec6 | Python | 2,333 | 72 | import logging
import torch.nn as nn
import torch.optim as optim
class SplitNN_server():
def __init__(self, args):
self.comm = args["comm"]
self.model = args["model"]
self.MAX_RANK = args["max_rank"]
self.init_params()
def init_params(self):
self.epoch = 0
sel... |
07ade33280cfdccb31d62c97662d90278337ea96291000a9fd5a8939bb36f9fa | Python | 2,334 | 52 | # Copyright (c) OpenMMLab. All rights reserved.
from .anchor_free_head import AnchorFreeHead
from .anchor_head import AnchorHead
from .atss_head import ATSSHead
from .autoassign_head import AutoAssignHead
from .cascade_rpn_head import CascadeRPNHead, StageCascadeRPNHead
from .centernet_head import CenterNetHead
from .c... |
2e64b4fbcb70e0c035b27b48ed4692fd4c9ccb20678902c76e7600b6abd2205b | Python | 2,334 | 51 | from fedml_api.distributed.classical_vertical_fl.message_define import MyMessage
from fedml_core.distributed.communication.message import Message
from fedml_core.distributed.server.server_manager import ServerManager
class GuestManager(ServerManager):
def __init__(self, args, comm, rank, size, guest_trainer):
... |
ea3303ce12c188b597f2299087014a1a1f0b1e70cebf653d605449e80ad18e1f | Python | 2,336 | 69 | import SimpleITK as sitk
import numpy as np
import argparse
def main(args):
print("Reading:", args.img)
sitk_img = sitk.ReadImage(args.img)
sitk_out = CorrectHisto(sitk_img, args.min_percentile, args.max_percentile, args.i_min, args.i_max)
print("Writing:", args.out)
sitk.WriteImage(sitk_out, ... |
6d71ae62c4878ba227cf7745f1107bb61c17b00dab2fe7ae8f2108a0fd897525 | Python | 2,339 | 64 | # Copyright (c) OpenMMLab. All rights reserved.
import mmcv
import numpy as np
import pycocotools.mask as mask_util
def split_combined_polys(polys, poly_lens, polys_per_mask):
"""Split the combined 1-D polys into masks.
A mask is represented as a list of polys, and a poly is represented as
a 1-D array. I... |
68fe858e95d488b3943bb6366e633cea5d9ca5d156eebd3eb73f64b0b37aa252 | Python | 2,342 | 77 | from model.builders.JAMA_builders import any_cancer_JAMA
import os
from copy import copy, deepcopy
filename = os.path.basename(__file__)
data_base ={'id':'response','type': 'updated_label' , 'params': {'outcome': 'response', 'text': 'NARR+IMPRESS', 'training_split':0, 'split_path': 'splits_new'}}
# training_splits = [... |
f1fdb60aafba75a38e609f9c6137d6d623e34dd80deb49a824cf53ec894f73a7 | Python | 2,343 | 63 | # Copyright Universitat Pompeu Fabra 2020-2023 https://www.compscience.org
# Distributed under the MIT License.
# (See accompanying file README.md file or copy at http://opensource.org/licenses/MIT)
from torch import nn, Tensor
from typing import Optional, Dict
class BasePrior(nn.Module):
r"""Base class for pri... |
164443ab143e53f0c3825677fe2148a4bd291afbc85981ef2d04b4784835012b | Python | 2,345 | 63 | import multiprocessing.pool
import re
from pathlib import Path
import pyrodigal_gv
from genomad import sequence
_orf_finder = pyrodigal_gv.ViralGeneFinder(meta=True, mask=True)
def _predict_genes(seq):
return (seq.accession, _orf_finder.find_genes(seq.seq))
class Prodigal:
def __init__(self, input_file: ... |
8c28473f4b29fb58bb3d3b85d6b5a740bff2f0cdcb358a126076569fb870c7c2 | Python | 2,346 | 89 | # Copyright Universitat Pompeu Fabra 2020-2023 https://www.compscience.org
# Distributed under the MIT License.
# (See accompanying file README.md file or copy at http://opensource.org/licenses/MIT)
from torchmdnet.priors import D2
import torch as pt
from pytest import mark
# This functions is intentionally not use... |
984b9ed3ae3e571501362b751108bf1b69764cb198b16102f4a0219df3c69027 | Python | 2,348 | 84 | import typing
import argparse
from osgeo_setup import *
def coordinate_reference_system(text: str) -> osr.SpatialReference:
srs_ = osr.SpatialReference()
methods: typing.List[typing.Callable[[osr.SpatialReference, str], int]] \
= [osr.SpatialReference.ImportFromWkt,
osr.SpatialReference.I... |
c7bea3d6cbbef8ef202a7a11294ab2aa90863428c77c8df36aa65fc78b078980 | Python | 2,348 | 72 | #!/usr/bin/env python
# Written by Lok Kan Lee
# Modified slightly by Brett Trost
import argparse
####################################
### Parse command-line arguments ###
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("depth_filename", type=str, help="sa... |
fdc0bf1bcb6f76179b068e67cca2b886681af20badddd70548ec20319403cb3c | Python | 2,348 | 65 | # Copyright (c) OpenMMLab. All rights reserved.
from abc import abstractmethod
from typing import Dict, List, Optional, Union
import numpy as np
from ..utils import FrameMessage, Message
from .node import Node
class BaseVisualizerNode(Node):
"""Base class for nodes whose function is to create visual effects, li... |
edf89da207ee7424fa7e32eae37f5987c890620db3c18da5796c6f20cb5e1273 | Python | 2,349 | 75 | """
Train a sleep stage classification model.
This script trains a neural network model (USleep, AnySleep, etc.) for sleep
stage classification using the configuration specified via Hydra.
Usage: see run.md in config folder
The script:
1. Loads the model, dataset, and trainer configuration from the specified config
... |
53bd0fc6c25dfee71a3de9b7dc84934df9c655d692fa8b6c0ebe36955eac05f8 | Python | 2,357 | 74 | from argparse import ArgumentParser
import numpy as np
import requests
from mmdet.apis import inference_detector, init_detector, show_result_pyplot
from mmdet.core import bbox2result
def parse_args():
parser = ArgumentParser()
parser.add_argument('img', help='Image file')
parser.add_argument('config', h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.