sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
418e35fd39364dc40e36e7033ff6cc458be67df122fb786f1549b3a1bacf5402 | Python | 1,810 | 43 | import numpy as np
import torch
IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
BATCH_PER_GPU = 2
NUM_WORKERS = 6
TRAIN_SUBSAMPLE_DATASET = True
NUM_ITER_PER_EPOC... |
363b75fd9fb5e5ff2e250a5c7afc42b940479113d7fe9e674fda931add2f9604 | Python | 1,811 | 42 | import numpy as np
import pandas as pd
from sklearn.decomposition import FastICA
from sklearn.feature_selection import VarianceThreshold
from sklearn.pipeline import make_pipeline
from tpot.builtins import OneHotEncoder
from tpot.export_utils import set_param_recursive
from metstab_shap.grid import SVC_rbf
from metsta... |
a1436c00072778e54b717245eb2ce6f283408df77468886d6d7871c089cb225e | Python | 1,814 | 68 |
import torch.utils.data as data
import os
from PIL import Image
import numpy as np
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
def img_loade... |
3585512ed58b0d58c85ccd941a8eb69ecb5283f9e1d2239db13b911b45b0c25e | Python | 1,816 | 60 | def parse_seqs(path):
with open(path) as handle:
seq_id = next(handle).split()[0][1:]
seq = ""
for line in handle:
if line[0] == ">":
yield seq_id, seq
seq_id = line.split()[0][1:]
seq = ""
else:
seq += l... |
085b74ab872f0c9f587e1dc07a8c518ae83e6642819a6d270651d38eeaa7c63f | Python | 1,823 | 68 | from abc import ABC
from dataclasses import dataclass
from enum import IntEnum
from typing import Optional
import numpy as np
import numpy.typing as npt
class PageType(IntEnum):
"""
Type of the page
"""
Waveform = 2
Text = 3
@dataclass
class DataPage(ABC):
"""
Shared attributes for vari... |
762c3132d17a6881e13ca53f22c3a47e7eeb1de0098d3d70bc9c9574ba66bc3b | Python | 1,823 | 67 | #!/usr/local/bin/python
import sys
import subprocess
import os
import numpy as np
if len(sys.argv) < 2:
print('usage:' + sys.argv[0] + ' <in bam 1> <in bam 2> <..>')
exit(1)
for i in range(1,len(sys.argv)):
bam_file = sys.argv[i]
p = subprocess.Popen(\
['samtools', 'view', '-H', bam_file]... |
b9a458be8e586b28586fe3f246c3bffd063e85b319f9ca4e8617fee731911726 | Python | 1,824 | 39 | import numpy as np
import random
class HistMatch2:
def __init__(self):
self.templates = None
def __call__(self, sample):
image, mask, misc = sample['image'], sample['mask'], sample['misc']
if "train" in misc['img_path']:
if self.templates is None:
self.templ... |
0304f4a520ff39cabd203eb08dff77861c7466a9d3056afb3f1b76121cb38c12 | Python | 1,834 | 59 | from typing import Tuple, Union, List, Any
import eagerpy as ep
import foolbox as fbn
import foolbox.attacks as fa
from foolbox.devutils import flatten
from foolbox.attacks.brendel_bethge import BrendelBethgeAttack
import pytest
from conftest import ModeAndDataAndDescription
def get_attack_id(x: Tuple[BrendelBethge... |
09e07673dcba5f6ee32788abdff49508d6dbb582b7a91a2063b5ebdfc48095b9 | Python | 1,835 | 64 | import logging
from typing import List, Union
import torch
class OptRepo:
"""Collects and provides information about the subclasses of torch.optim.Optimizer.
"""
repo = {x.__name__.lower(): x for x in torch.optim.Optimizer.__subclasses__()}
@classmethod
def get_opt_names(cls) -> List[str]:
... |
3b6b4f3ab59177257cf17359ffaa61f86a3a12f58665ce46445d52d0d10f83aa | Python | 1,836 | 65 | import logging
from typing import List, Union
import torch
class OptRepo:
"""Collects and provides information about the subclasses of torch.optim.Optimizer.
"""
repo = {x.__name__.lower(): x for x in torch.optim.Optimizer.__subclasses__()}
@classmethod
def get_opt_names(cls) -> List[str]:
... |
9ba1082726e426b3065a4c215d7a24f1d569544a894b09fab0be6ac036ef0775 | Python | 1,839 | 72 | # 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/>
from sbi.neural_nets.net_builders.categorial import build_categoricalmassestimator
from sbi.neural_nets.net_builders.classifier import (
build_linear_... |
ea5a1bc5e4b024a4521f960056623531cada9b1f1b8415cdee2a7bec526cc1e9 | Python | 1,840 | 53 | # Author: Alfred Lim
# Location: Singapore
# Date: 2021-11-27
# Task: apply vowel-centered slot-based coding scheme to phonology
# Reference: Lim, O'Brien, & Luca (submitted)
# Import libraries
import re
import numpy as np
import pandas as pd
import sys
# Find the position of the first phonological vowel
def first_ph... |
1f14bcffed479536910087694727775f677b097fb0562873c6ca42445fa611c0 | Python | 1,844 | 58 | import pytest
import eagerpy as ep
import foolbox as fbn
from conftest import ModeAndDataAndDescription
attacks = [
fbn.attacks.InversionAttack(distance=fbn.distances.l2),
fbn.attacks.InversionAttack(distance=fbn.distances.l2).repeat(3),
fbn.attacks.L2ContrastReductionAttack(),
fbn.attacks.L2Contrast... |
fbde072825feca35e51f9077402662d7bdd544393c21e0fb59c50ce8b8b482aa | Python | 1,845 | 56 | import numpy as np
import pandas as pd
def eval(pred_path, curve_path, annot_path, out_path):
#chargements
curve = np.load(curve_path, allow_pickle=True)
preds = np.load(pred_path, allow_pickle=True).astype(int)
peaks = np.load(annot_path, allow_pickle=True).astype(int)
df_error = pd.DataFrame... |
47711307a7a56e4727682c693d2755d153edb4d1f9f65d5acb2e8a86a1409da9 | Python | 1,846 | 51 | import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
def pixelwise_ranks(rank_vec,
fov_height,
fov_width,
num_frames,
bheight,
bwidth,
... |
4481a66ed6f85aca7c86e32a100de9acdf36ce1ed9e40573e916ec9d3a8246b7 | Python | 1,851 | 49 | import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import accuracy_score, confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
# Load data from CSV file
# Create a new column after ... |
176043d55e8ca9d1304d3aae39a40e30ec62b4b4408b637cc791076f26852b16 | Python | 1,853 | 43 | import torch
import torchvision
from torchvision import transforms, datasets
from torchvision import transforms as torch_transforms
from base import BaseDataLoader
class Cifar10DataLoader(BaseDataLoader):
def __init__(self, data_dir, batch_size, shuffle=True, validation_split=0.0, num_workers=1, training=True,
... |
8299aa09c5aeb8104b7ef5dee40af1807466e819df13e0d29350fff529493d0c | Python | 1,853 | 43 | import numpy as np
import pandas as pd
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.pipeline import make_pipeline, make_union
from tpot.builtins import StackingEstimator
from tpot.export_utils import set_param_recursive
from sklearn.preprocessing import FunctionTransformer
from copy import copy
from ... |
84df520c5f4cfdb55ae0c1f0c68a75b35bff0b40b4cc3fefbb134a6352bfabb5 | Python | 1,854 | 43 | import numpy as np
import pandas as pd
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.pipeline import make_pipeline, make_union
from tpot.builtins import StackingEstimator
from tpot.export_utils import set_param_recursive
from sklearn.preprocessing import FunctionTransformer
from copy import copy
from ... |
953929c566dee7875b6bb9326cada0f1da085caf19c37ff3a7cb308053313d78 | Python | 1,854 | 59 | from scipy.spatial.distance import cdist
import jax
import jax.numpy as jnp
from einshape import jax_einshape as einshape
from functools import partial
# Define the covariance function
def rbf_kernel(x1, x2, sigma, l):
"""
Radial basis function kernel
"""
sq_norm = cdist(x1 / l, x2 / l, metric='sqeucli... |
cd062a18bb8fcbcaa1638f1dda5bdab4a71223f08266c65b15759e28cad4f747 | Python | 1,854 | 67 | import pytest
import pandas as pd
from binn import Network
@pytest.fixture
def network():
input_data = pd.DataFrame({"Protein": ["a", "b", "c"]})
pathways = pd.DataFrame(
{"source": ["A", "B", "C"], "target": ["path1", "path1", "path2"]}
)
translation = pd.DataFrame(
{"input": ["a", "b... |
83de9375746fcd6cb890c656fbf77c0d29f4392ec97b8c2c7226909fc364ffee | Python | 1,857 | 58 | from django.shortcuts import render
import os
import sys
import multiprocessing as mp
import pathlib
try:
from exsclaim.pipeline import Pipeline
except:
current_file = pathlib.Path(__file__).resolve(strict=True)
base_dir = current_file.parent.parent.parent.parent
sys.path.append(str(base_dir))
from ... |
828b7e98f445bfbbbeb588130ac769d353e655bf925519c6b5bb633c28ffae79 | Python | 1,862 | 50 | """Hardware gate for the optional Triton inference kernels.
The Triton AEV/ConvSV/geometry kernels are validated on NVIDIA GPUs with compute capability 8.0 or newer only.
Older GPUs and ROCm builds keep the equivalent PyTorch expressions, exactly as when Triton is not installed.
"""
from __future__ import annotations... |
280be1f7b9073f769e43a6badce21cc218dc1b5c4de99e0f0f26c41aed0b8ee4 | Python | 1,864 | 54 | # Copyright (c) OpenMMLab. All rights reserved.
from os.path import dirname, exists, join, relpath
import torch
from mmcv.runner import build_optimizer
def _get_config_directory():
"""Find the predefined detector config directory."""
try:
# Assume we are running in the source mmdetection repo
... |
2bf77b18ca90f1bc30d6ed3144e043f3f4b7166582ab7588979e13e1b695b530 | Python | 1,866 | 39 | import numpy as np
import pandas as pd
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.pipeline import make_pipeline, make_union
from sklearn.preprocessing import Binarizer, MinMaxScaler
from sklearn.tree import DecisionTreeRegressor
from tpot.builtins import StackingEstimator, ZeroCount
from tpot.export_... |
14f22d8963f747f50d1ee5bea3bc197073b150f11ba1d3f79a815553a34f238e | Python | 1,874 | 52 | import torch
import torchvision.transforms.functional as F
class Normalize3d(object):
"""Normalize a tensor volume given the mean and standard deviation.
:param mean: mean value.
:param std: standard deviation value.
"""
def __init__(self, mean, std, training=True):
if isinstance(mean, li... |
e0e378f765629ddbe8ca54e97d64a4932c773a1fc414e572c14665fe7b9dd45c | Python | 1,875 | 50 | from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt
# Define the cubic function to fit
def cubic_function(x, a, b, c, d):
return a*x**3 + b*x**2 + c*x + d
def fix_x_in_range(xmin, xmax, function):
# Generate x values in the range [-1, 1]
x_values = np.linspace(xmin, xm... |
2fed6d44229bfe3c28c5c88d8c6558170350506693268dd1f7a8fe083a27fd45 | Python | 1,877 | 54 | # Same structure as pre-trained network for transfer learning | standard learning
# Created: 5/22/2021
# Status: OK
# CUBLAS_WORKSPACE_CONFIG=:4096:8 python cnn_main.py
# Consider merge into 1 main file
import sys
import torch
sys.path.insert(1, '../plot/')
from networks import CNN_Wrapper
from utils import read_json
... |
6f9c7dd75e9ee47b48ccb0de10b4b28e7c3ee5afaf9427914ac2028fcb537c20 | Python | 1,877 | 42 | from fedml_api.distributed.classical_vertical_fl.message_define import MyMessage
from fedml_core.distributed.client.client_manager import ClientManager
from fedml_core.distributed.communication.message import Message
class HostManager(ClientManager):
def __init__(self, args, comm, rank, size, trainer):
su... |
c8bee797d52c8ea8a849135b75fda3fb4afbf81e53b3ce75fcc88662bc9ae951 | Python | 1,880 | 63 | import argparse
import json
import pathlib
from exsclaim.figures.scale.evaluate_scale import test_label_reading
from exsclaim.figures.scale.train_label_reader import train_crnn
current_file = pathlib.Path(__file__).resolve(strict=True)
parent_directory = current_file.parent
ap = argparse.ArgumentParser()
ap.add_argu... |
e586e388055fe7d0bed3b5fc84a427c01b2384e68f1cc84b0ec3e2208fb7a19e | Python | 1,880 | 70 | import copy
import pytest
import torch
from daart.models import Segmenter
from daart.models.tcn import DilatedTCN
def test_tcn(hparams, data_generator, check_batch):
hp = copy.deepcopy(hparams)
hp['backbone'] = 'dtcn'
hp['variational'] = False
model = Segmenter(hp)
model.to(hp['device'])
#... |
f74d278089e43d442b4c292ea85d49a05d64e0ca318b031c186fb8f43b4932be | Python | 1,881 | 44 | from pytorch_lightning.callbacks import Callback
import torchvision
import torch
class CleftImageLogger(Callback):
def __init__(self, num_images=256, log_steps=100):
self.log_steps = log_steps
self.num_images = num_images
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_id... |
c742fb58086e8d90764211c370a8eda40959388fe0dcad19dac60d4b20726e40 | Python | 1,882 | 46 | import numpy as np
import random
from scipy import ndimage, misc
class RandomRotate:
def __init__(self, tilt=False, training=True):
self.training = training
self.tilt = tilt
def __call__(self, sample):
"""
Randomly flip the numpy image horizontal or/and vertical
Args:
... |
f9e9f19494d2a90418e5a8e75a0c250525846f877350f5316918ffa79ad0377d | Python | 1,882 | 44 | import torch
from torch.nn import functional as F
def tversky_loss(output, target, misc, alpha=0.5, beta=0.5, eps=1e-7):
"""Computes the Tversky loss [1].
Args:
target: a tensor of shape [B, H, W] or [B, 1, H, W].
output: a tensor of shape [B, C, H, W]. Corresponds to
the raw output... |
fc0ac11de5831d6dcaa4e01dcbfcd5d533a86a6c45253a2e900fc04d2baecbda | Python | 1,883 | 59 | from abc import abstractmethod, ABCMeta
from typing import Optional, Tuple
from torch import nn, Tensor
class BaseWrapper(nn.Module, metaclass=ABCMeta):
r"""Base class for model wrappers.
Children of this class should implement the `forward` method,
which calls `self.model(z, pos, batch=batch)` at some p... |
910a2d0bdc8978fba617a0d2f6e3e2d4b7e7789d034f829cc29d4deefee6f06a | Python | 1,884 | 54 | import os
import numpy as np
import sys
# create config files for all possible models
saving_dir = '.'
n_conv_layers = [1, 3, 5]
model_dims_hidden_sizes = [16, 64, 256]
dense_layers = [1, 3]
dr = [0.0, 0.2]
lr = [.01, .001, .0001, .00001, .000001]
batchnorm = [True, False]
batchsize = [8, 32, 128]
scheduler = [-1., ... |
44af00efbef3006d5cfb92bc38b05c24ab9ff18e02cba88106bd2893a7523356 | Python | 1,886 | 57 | import ctypes
import logging
import threading
import time
import traceback
from ..message import Message
class MPISendThread(threading.Thread):
def __init__(self, comm, rank, size, name, q):
super(MPISendThread, self).__init__()
self._stop_event = threading.Event()
self.comm = comm
... |
c1847fb0a8b0c0bcb91bd61b25c917ba4623905f3d9d7c508693afa875c3b243 | Python | 1,887 | 49 | from torch import nn
class BasePrior(nn.Module):
r"""Base class for prior models.
Derive this class to make custom prior models, which take some arguments and a dataset as input.
As an example, have a look at the `torchmdnet.priors.atomref.Atomref` prior.
"""
def __init__(self, dataset=None):
... |
7b63f18baee9c8bea0d1f95b07dfc831d15f840b61babdb7461c048f46222034 | Python | 1,888 | 48 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from torch.utils.data import DistributedSampler as _DistributedSampler
from mmpose.core import sync_random_seed
class DistributedSampler(_DistributedSampler):
"""DistributedSampler inheriting from
`torch.utils.data.DistributedSampler`.
In pyto... |
bb415aa1075063f6e83690e62145d151d24eb96006fdb03f3a98cf59572f7382 | Python | 1,888 | 45 | from fedml_api.distributed.base_framework.message_define import MyMessage
from fedml_core.distributed.client.client_manager import ClientManager
from fedml_core.distributed.communication.message import Message
class BaseClientManager(ClientManager):
def __init__(self, args, comm, rank, size, trainer):
sup... |
16d0c58493f3c13e9006d35fc65aeb0d35636298c2900c5e668d8d0aac251b38 | Python | 1,890 | 66 | import torch
import torch.nn as nn
from asteroid.losses.sdr import SingleSrcNegSDR
class CompositeLoss(nn.Module):
def __init__(self, r = 0, n = 1) -> None:
super().__init__()
self.l1_loss = nn.L1Loss(reduce=False)
self.snrloss = SingleSrcNegSDR('snr')
self.r = r
self.neg_s... |
0e214cb3fa8d4328a3bd9520977259d0e7ebd4061000573c3616ce7fef9bb77d | Python | 1,891 | 64 | import numpy as np
import struct
import os
import getopt
def read_data_from_file(file_name):
f = open(file_name, "rb")
line = f.readline()
line = line.split()
nparam = int(line[0])
rec_len = int(line[1])
nrec = int(line[2])
nlast = int(line[3])
print(nparam, rec_len, nrec, nlast)
a... |
ff871bca72b1a1602980a679f28782d0f55049d1acae587751ba695bf8abd018 | Python | 1,891 | 64 | from ase.calculators.calculator import Calculator, all_changes
from ase.calculators.calculator import InputError, ReadError
from ase.calculators.calculator import CalculatorSetupError
from ase import io
import numpy as np
from ase.units import Bohr, Hartree, kcal, mol, Angstrom
import os
import torch
class MyCalc(Cal... |
de6415c2f8c8e2f7930f77a11d27bd6f35c2b1fcf38b76ee024e925361632e61 | Python | 1,893 | 57 | import textwrap
class P4Error(Exception):
"""A class for exceptions in p4.
You can raise this with a string, or a list of strings. If its
a single string, it gets wrapped. If its a list of 2 strings, the
first one is output flush and unwrapped, and the second is
indented and wrapped."""
de... |
edbe75df351d5daee565b6749e08337acd86c0f07efa77ef6464878fbadee0ca | Python | 1,896 | 44 | ############################################
# imports
############################################
from abc import ABC, abstractmethod
from oligo_designer_toolsuite.database import OligoDatabase
############################################
# Property Base Class
############################################
class B... |
ae3d2ff85582b778e6a9990d9d34d078b5260cecdb7bcf7696b590109dfeefff | Python | 1,897 | 59 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.colors import ListedColormap
# other=0=black, TP=1=yellow, FP=2=red, TN=3=black, FN=4=blue
TP = [1., 1., 0.]
FP = [1., 0., 0.]
TN = [0., 0., 0.]
FN = [0., 0., 1.]
c_map = [[0., 0., 0.], TP, FP, TN, FN]
def eval_pr... |
9f007651c9017d0a4418a78bdaa7bdc77dfdd61bea80050d46951326988dd19d | Python | 1,898 | 63 | # Copyright (c) OpenMMLab. All rights reserved.
import copy
import pytest
import torch
from mmcv import Config
from numpy.testing import assert_almost_equal
from mmpose.datasets import DATASETS
def test_NVGesture_dataset():
dataset = 'NVGestureDataset'
dataset_info = Config.fromfile(
'configs/_base... |
ad1dcb31808538baea0e1441cb5c5eab9bb3a52b70db6819ee938cc4e381c9aa | Python | 1,898 | 60 | # Author: Alfred Lim
# Location: Singapore
# Date: 2021-11-27
# Task: create binary orthographic vectors for neural networks
# Reference: Lim, O'Brien, & Luca (submitted)
## Import libraries
import re
import numpy as np
import pandas as pd
import torch
# Find letter position index, e.g. "a" = 0
def lette... |
3e642407802f068cf5d70d84fa20b05b9d347376b6df8f696d1211b10d46e9c6 | Python | 1,899 | 58 | import xarray as xr
import pandas as pd
nc_file_in = r'V:\asap\Seasonal_forecasts\monthly-precipitation\ecmwf-51\historical\monthly-means\06\ecmwf-51_06.nc'
nc_file_out = r'V:\asap\Seasonal_forecasts\monthly-precipitation\ecmwf-51\historical\monthly-means\06\ecmwf-51_06-06.nc'
# Open the NetCDF file
ds = xr.open_datas... |
4428bae643a4e6741145409b811814988a69a744cef591ebaf3c1428cd59d1ad | Python | 1,900 | 72 | # Copyright (c) OpenMMLab. All rights reserved.
import logging
from argparse import ArgumentParser
from mmcv import Config, DictAction
from mmpose.apis.webcam import WebcamExecutor
from mmpose.apis.webcam.nodes import model_nodes
def parse_args():
parser = ArgumentParser('Webcam executor configs')
parser.a... |
fb5180bf3ae661f3e6338fae12d8a241515656e5acf811ab6f5fb5560adb1b4b | Python | 1,905 | 57 | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import weighted_loss
@weighted_loss
def mse_loss(pred, target):
"""Warpper of mse loss."""
return F.mse_loss(pred, target, reduction='none')
@LOSSES.register_module... |
f2536db5c0ce18c45f7a86a0e6cf5b98921944dbaa5b7754de21ee8de9cd696b | Python | 1,906 | 59 | """This script shows how pyDentate could be used after the
refactoring and gives an entry point to prototype its usage with
the grid model."""
from neuron import h, gui
from pyDentate import net_tunedrev, neuron_tools, inputs
import numpy as np
import scipy.stats as stats
"""Connectivity and time stamp creation still... |
8e99556641515c20355bbdf94d150edf144449d566c9081fc137fb9ee1680b0a | Python | 1,907 | 64 | from collections import defaultdict
def parse_seqs(path):
with open(path) as handle:
seq_id = next(handle).split()[0][1:]
seq = ""
for line in handle:
if line[0] == ">":
yield seq_id, seq
seq_id = line.split()[0][1:]
seq = ""
... |
424db1b04e0c57f8c6db7e6b65c2bf33521f18caab4576b08514119a637e0a77 | Python | 1,908 | 70 | import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.keras.models import load_model
from gradient_accumulator import GradientAccumulateModel
def normalize_img(image, label):
"""Normalizes images: `uint8` -> `float32`."""
return tf.cast(image, tf.float32) / 255., label
def test_train_mn... |
522ceacf6ab2293636a12e66f3d098ef7eb298fd974b39b7931fdabb11508da8 | Python | 1,917 | 42 | from mpi4py import MPI
from fedml_api.distributed.fednas.FedNASAggregator import FedNASAggregator
from fedml_api.distributed.fednas.FedNASClientManager import FedNASClientManager
from fedml_api.distributed.fednas.FedNASServerManager import FedNASServerManager
from fedml_api.distributed.fednas.FedNASTrainer import FedN... |
5a01a4727e97705e69111b704b88c2b0736852f0283b96523538daefab2edd4a | Python | 1,918 | 64 | #!/usr/bin/env python
import sys
import tempfile
import os
import gzip
import shutil
from leafcutter_cluster import *
def main(options,libl):
sort_junctions(libl, options)
merge_junctions(options)
get_numers(options)
if __name__ == "__main__":
from optparse import OptionParser
parser = ... |
74ed4e13f8e232f0aec17f537c301393be6218d47cafcd4f8da57ed004242236 | Python | 1,919 | 57 | # Pre-training network for transfer learning
# Created: 5/21/2021
# Status: OK
# CUBLAS_WORKSPACE_CONFIG=:4096:8 python pretrain_main.py
# Consider merge into 1 main file
import sys
import torch
import numpy as np
sys.path.insert(1, '../plot/')
from networks import CNN_Wrapper_Pre
from utils import read_json
def cnn... |
a7d83cd43f4f2b69f2784ffa502556fac3cb16b5ece0d65415d112c7fb3fd6ed | Python | 1,919 | 43 | import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.feature_selection import RFE
from sklearn.naive_bayes import BernoulliNB
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from tpot.e... |
c0d3ae3c5a47947813f89ba0c0dde21501b0428fe1daaa79c28e18b360e7f299 | Python | 1,921 | 57 | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
from mmpose.core.bbox.transforms import bbox_cs2xywh
def convert_db_to_output(db, batch_size=2, keys=None, is_3d=False):
outputs = []
len_db = len(db)
for i in range(0, len_db, batch_size):
keypoints_dim = 3 if is_3d else 2
... |
f2694ae530f706132e3abf7945836933981f4282f5f34e486aecd001d4ae29b5 | Python | 1,921 | 49 | """RDFlex gives the same results whether outcome and treatment are stored as integers or as floats."""
import numpy as np
import pandas as pd
import pytest
from sklearn.linear_model import LinearRegression, LogisticRegression
import doubleml as dml
from doubleml.rdd import RDFlex
from doubleml.rdd.datasets import mak... |
6ba6df4f81dfcac3329cb7a9346121297922d8d5dfa26ae38e5f32d9465cc1cc | Python | 1,922 | 52 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import neuralop.models as models
class FNO(nn.Module):
def __init__(self, config):
super().__init__()
'''
in_dim: the input dimension of features, should be # data points * data dimension
hidden_... |
494750fd164f86c2098b8c281716394b9ec3b76a4d8c4827190d7d19168f763e | Python | 1,925 | 69 | import os
import numpy as np
import matplotlib.pyplot as plt
import mne
import cv2
import tempfile
import os
def general(fname):
# =============================================================================
# fname = "X:/EEG/Felnott Kontroll/eszti220405_nemo.bdf"
# ==================================... |
f345204413f99ff04c359ef10ff4d6fd2b3bc8d3b6487633fd060cb563926fff | Python | 1,927 | 70 | import copy
import pytest
import torch
from daart.models import Segmenter
from daart.models.temporalmlp import TemporalMLP
def test_temporal_mlp(hparams, data_generator, check_batch):
hp = copy.deepcopy(hparams)
hp['backbone'] = 'temporal-mlp'
hp['variational'] = False
model = Segmenter(hp)
mod... |
757eaa156a361a319eac2327e066a0ab2183142e900fe3b9adc0f8e57b7a0d3f | Python | 1,930 | 53 | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.runner import BaseModule, auto_fp16
from mmdet.models.builder import HEADS
@HEADS.register_module()
class FeatureRelayHead(BaseModule):
"""Feature Relay Head used in `SCNet <https://arxiv.org/abs/2012.10150>`_.
Args:
in_... |
592322b907322b5e64e6ec5821bfd39cb280c899f17c60a32f14f12855a3a92a | Python | 1,934 | 55 | import math
import torch.nn as nn
from layers import BBB_Linear, BBB_Conv2d
from layers import BBB_LRT_Linear, BBB_LRT_Conv2d
from layers import FlattenLayer, ModuleWrapper
class BBB3Conv3FC(ModuleWrapper):
"""
Simple Neural Network having 3 Convolution
and 3 FC layers with Bayesian layers.
"""
de... |
688b1e2fbac4bc6e6c71d3a192fbd25770ed86252856e8a6e862f6a62e6e9cc9 | Python | 1,935 | 53 | import torch.nn as nn
import math
from layers import BBB_Linear, BBB_Conv2d
from layers import BBB_LRT_Linear, BBB_LRT_Conv2d
from layers import FlattenLayer, ModuleWrapper
class BBBAlexNet(ModuleWrapper):
'''The architecture of AlexNet with Bayesian Layers'''
def __init__(self, outputs, inputs, priors, laye... |
96c05b71829b92956fb31c7fbaa1bc2fe594a0e03c8f4bd7d59bffe6ae40d2c2 | Python | 1,938 | 59 | import os
import argparse
import glob
import random
import json
def main(args):
random.seed(args.seed)
train_prop = args.train_prop
test_prop = args.test_prop
val_prop = args.val_prop
assert abs(train_prop + test_prop + val_prop - 1) < 1e-3, "Sum of train, test and val proportions is not equal t... |
a1cdac3176deeee304f8b48cbd47d0d5e17054bf474f0573f2b781b823dc5552 | Python | 1,938 | 78 | from enum import Enum
#marker_size_3d = 1.25 #0.75
marker_size = {
'big': {
'3d': 2,
'2d': 6
},
'default': {
'3d': 1.25,
'2d': 3
}
}
font_size = {
'big': {
'tickfont_size_3d': 20,
'tickfont_size': 26,
'plot_font_size': 44, # 32, # 20
... |
b1a636c6cecb4509b0addd72fb411ab771596211279069e5961c1edf3d0a0ded | Python | 1,938 | 39 | from mpi4py import MPI
from fedml_api.distributed.split_nn.client import SplitNN_client
from fedml_api.distributed.split_nn.client_manager import SplitNNClientManager
from fedml_api.distributed.split_nn.server import SplitNN_server
from fedml_api.distributed.split_nn.server_manager import SplitNNServerManager
def Sp... |
cfaec9ef4e314ae7a6a642ebc088bc8c0c38909ac693ef7e922f2167a2caa014 | Python | 1,938 | 53 | #!/usr/bin/env python3
from flystim.stim_server import launch_stim_server
from flystim.screen import Screen
from time import sleep
def main():
stim_time = 4
x_trajectory = {'name': 'tv_pairs',
'tv_pairs': [(0, -2), (stim_time, 2)],
'kind': 'linear'}
y_trajecto... |
cbb086b175db54d00967c47f9b561720e4759dc88c2c0b74a3d0d274fa431527 | Python | 1,948 | 57 | # Pre-training network for transfer learning
# Created: 5/21/2021
# Status: OK
# CUBLAS_WORKSPACE_CONFIG=:4096:8 python pretrain_main.py
# Consider merge into 1 main file
import sys
import torch
import numpy as np
sys.path.insert(1, '../plot/')
from networks import CNN_Wrapper_Pre
from utils import read_json
torch.se... |
6b5ef2ed3d9535b4f092cced9794ca5f692ce8232e1111e039391d1916bba674 | Python | 1,959 | 44 | """This module contains classes and routines associated with manipulating smiles, including resolving R-groups into
individual chemical compounds"""
from typing import List
from utils.utils import erase_elements, euclidean_distance
from utils.vectorised import DiagramVectoriser
from reactiondataextractor.models impor... |
b82ff6efb77b2f7478a1b1681fa75fcc78b3de9c9adb4fb2d81e28904ef865b5 | Python | 1,961 | 37 | # Copyright (c) OpenMMLab. All rights reserved.
from .base_roi_head import BaseRoIHead
from .bbox_heads import (BBoxHead, ConvFCBBoxHead, DIIHead,
DoubleConvFCBBoxHead, SABLHead, SCNetBBoxHead,
Shared2FCBBoxHead, Shared4Conv1FCBBoxHead)
from .cascade_roi_head import Cas... |
cf9dd03d2b9bba22d578e8bcc3fbc981787159ddba4ecd342e945160615d82a1 | Python | 1,962 | 47 | def convert_coords_to_labelbox(bbox_coordinates):
""" Converts x1,y1,x2,y2 to [{"x": x1, "y": y1}, ...] """
x1, y1, x2, y2 = bbox_coordinates
return [{"x": x1, "y": y1}, {"x": x1, "y": y2},
{"x": x2, "y": y2}, {"x": x2, "y": y1}]
def convert_labelbox_to_coords(geometry):
""" Converts from [... |
369ff532514b9e4e6541eeb147c9fb2252e25506eb4ac363b5c3d6751dd6904a | Python | 1,965 | 58 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class ShiftedSoftplus(nn.Module):
"""
Shifted softplus activation function with learnable feature-wise parameters:
f(x) = alpha/beta * (softplus(beta*x) - log(2))
softplus(x) = log(exp(x) + 1)
For beta -> 0 : f(x) -> 0... |
d2aacafd66db9670982f6d2e7c632b6430942e7593d58387f6490ca6609a88e9 | Python | 1,971 | 61 | import torch
def embed_3D(d_target, edge_index, init_pos, edge_order=None, alpha=0.5, mu=0, step_size=None, num_steps=None, verbose=0):
assert torch.is_grad_enabled, '`embed_3D` requires gradients'
step_size = 8.0 if step_size is None else step_size
num_steps = 1000 if num_steps is None else num_steps
... |
713d42938e903df94aca2da1ad19cdc0f62d07c8fee1daa38b0774ad7247fcc2 | Python | 1,972 | 52 | # Copyright (c) OpenMMLab. All rights reserved.
from .atss import ATSS
from .autoassign import AutoAssign
from .base import BaseDetector
from .cascade_rcnn import CascadeRCNN
from .centernet import CenterNet
from .cornernet import CornerNet
from .deformable_detr import DeformableDETR
from .detr import DETR
from .fast_r... |
4d75b3bf654f4247e732c9b7422a9a8e696bdcbdbd4913323980d0bd990ee9a7 | Python | 1,973 | 55 | import numpy as np
class RandomCrop:
"""
Crop the 2D numpy [c, h, w] and mask [h, w] in a sample
"""
def __init__(self, output_size, crop_pos=None, padding=0, training=True):
assert isinstance(output_size, (int, list))
if isinstance(output_size, int):
self.output_size = (o... |
15de696d9d24aab87571b0a62abd0dcf13cf1485b517bf86fb9057c5599c58bf | Python | 1,974 | 60 | import numpy as np
import torch
from utils.clean_noise import CleanNoise
def one_cls_dice(output, target, label_idx):
"""
Calculate Dice metrics for one channel
:param output:Output dimension: Batch x Channel x X x Y (x Z) float
:param target:Target dimension: Batch x X x Y (x Z) int:[0, Channel]
... |
c3f165cfba17a2a3d4ad4975387fdbc4e37def539cd378bf9cf0354841f67667 | Python | 1,981 | 55 | import torch
class Wrapper:
def __init__(self, natoms, bonds, device):
self.groups, self.nongrouped = calculate_molecule_groups(natoms, bonds, device)
def wrap(self, pos, box, wrapidx=None):
nmol = len(self.groups)
box = box[:, torch.eye(3).bool()] # Use only the diagonal
if ... |
a2bddd2c9684d9accc16b7c78f973ed2edf36650ad77cb2b9008bfb52c5b4ac8 | Python | 1,982 | 55 | from data_loader import load_partition_data_landmarks
'''
You can run with python check_download.py to check if you have all
data samples in federated_train.csv and test.csv.
'''
if __name__ == '__main__':
data_dir = './cache/images'
fed_g23k_train_map_file = './cache/datasets/mini_gld_train_split.cs... |
84d4e25018fccb9b35911c42e5dc1e8d47d3d4f6705ba41ca6f3233e012ab5f4 | Python | 1,984 | 42 | # @author semese
import numpy as np
# demographic columns
demogr_cols = [
'Lives_Father_-1.0', 'Lives_Father_0.0', 'Lives_Father_1.0',
'Lives_Mother_-1.0', 'Lives_Mother_0.0', 'Lives_Mother_1.0',
'Lives_Child_-1.0', 'Lives_Child_0.0', 'Lives_Child_1.0',
'Lives_Siblings_-1.0', 'Lives_Siblings_0.0', 'Li... |
25c72a9a970e78eb99b4f0b1d9c7fb232d41c023ee4eebe5213cbd1537a209a0 | Python | 1,985 | 62 | import argparse
import pathlib
from exsclaim.pipeline import Pipeline
# Path to/ Name of Query JSON, used if no command line argument is supplied
# If no file extension (.json) is supplied, path will be assumed to be:
# path/to/exsclaim/query/<QUERY>.json
QUERY = "nature-haadf-ag-nanoparticles"
# First letter of too... |
3e14ac5370ab7ce00c142c5330d9719d1102004f8461349b6c743f0fda26e628 | Python | 1,985 | 72 | import matplotlib.pyplot as plt
import numpy as np
# short fun to colorize boxplots
def color_boxplot(thos, bp, colors, alpha=0.7):
for key in ["boxes", "medians"]:
for i, b in enumerate(bp[key]):
b.set(color=colors[i], alpha=alpha)
for idx, patch in enumerate(bp["boxes"]):
patch.... |
576b3d319626fda86777ebfa3bf6c72f85df37dae596725b877b66b8f895c547 | Python | 1,986 | 69 | #!/usr/bin/env python
import sys
import numpy as np
import glob
from optparse import OptionParser
import l_bp
def main():
usage ="""%prog <VCF file 1> <VCF file 2> ... <VCF file N>
l_sort
Author: Ryan Layer, Colby Chiang, & Ira Hall
Description: sort N VCF files into a single file
Version: 0.01
"""
if len(sy... |
380dce739b837be808125b02052238e769b87cb2bb72e0282c21b68dcedec322 | Python | 1,989 | 63 | import os
import random
import numpy as np
from PIL import Image
# Cal mean std
def compute_mn_std_channel(data_dir, num=2000, i=0):
pixvlu, npix = 0, 0
for fname in os.listdir(data_dir)[:num]:
if fname.endswith('.jpeg'):
img = Image.open(os.path.join(data_dir, fname)).convert("RGB")
... |
e49fe1046dd1ca4501a3fdadc359a27b6487d1cf4798fb37ddca0b698e84678f | Python | 1,989 | 44 | import glob
import shutil
import os
import pandas as pd
import logging
df = pd.read_excel('only_1000_images.xlsx', skiprows = 1)
empiar_ids = df['EMPIAR_ID']
gain_extensions = df['Gain Ext']
SOURCE_ADDRESS = '/gpfs/alpine/bif135/scratch/ashwind/CryoEM/data_downloads_dump_has_more_than1000/444_gainref_data/'
DESTINATIO... |
1a4e08ca84927ec9f22759aafe56ca5929465109c7700d2b8e295d42fbb8d038 | Python | 1,992 | 51 | import pathlib
from sys import path
import os
def initialize_results_dir(results_dir=None):
""" Determine where to save results for a pipeline run
The output directory will be resolved in this order:
1. if results_dir is provided, results will be saved there
2. if results_dir has previously be... |
0112cf067d8afab0004773927741724961b7318a3ebc3c632a6483daa93b962d | Python | 1,993 | 53 | import os
import gzip
import urllib
import urllib.request
import subprocess
from Bio import AlignIO
from Bio import SeqIO
from selbstaufsicht.datasets._utils import get_family_ids
root = os.environ['DATA_PATH'] + '/Xfam'
path = root + '/Rfam/14.6/seed/train/'
filename = 'Rfam.gz'
fasta_base_url = 'ftp://ftp.ebi.ac.uk... |
1b0d7232ac9a0612b432509f1decc5288132dd52ae8554d95f26cd4ecac70542 | Python | 1,995 | 52 | from data.manual_labels.data_reader import ManualLabels
import pandas as pd
data = ManualLabels(outcome = 'any_cancer', text='NARR+IMPRESS')
# data = ManualLabels(outcome = 'any_cancer', text='NARR')
# data = ManualLabels(outcome = 'any_cancer', text='IMPRESS')
x_train, x_validate, x_test, y_train, y_validate, y_test, ... |
9775f2b742e5ba40648d5ce37847c3adf6961251854f80fd9121e9e71b3a173a | Python | 1,996 | 51 | from .utils import transform_tensor_to_list
class FedGanTrainer(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... |
9bb3004514da5714841d88e16c18c2ea5167c2c5ee8bb0ec463c5832dd6167fd | Python | 1,996 | 51 | from .utils import transform_tensor_to_list
class FedSegTrainer(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... |
084aafe56f7a4e0d14d8f2b2342349fef02af39a061368a150aa751705993da0 | Python | 1,997 | 39 | import argparse
import pickle
import os
def unpickle(where_pkl):
with open(where_pkl, 'rb') as f:
return pickle.load(f)
class Patient:
def __init__(self, plot_path, assessment_path, baseline_file, files_to_remove, vta_path):
self.plot_path = plot_path
self.assessment_path = assessment... |
d9f5b08d1c5eed8ad7817b500159cb1c6e8885a8f2d1bad68224a76565903348 | Python | 1,997 | 54 | import torch
import torch.nn as nn
class Swish(nn.Module):
"""
Swish activation function with learnable feature-wise parameters:
f(x) = alpha*x * sigmoid(beta*x)
sigmoid(x) = 1/(1 + exp(-x))
For beta -> 0 : f(x) -> 0.5*alpha*x
For beta -> inf: f(x) -> max(0, alpha*x)
Arguments:
nu... |
c8bd118dbeeccc2485dcc0768dc17df1ad803f790194c97c13793168a6902ad2 | Python | 1,999 | 44 | import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.feature_selection import RFE
from sklearn.naive_bayes import BernoulliNB, GaussianNB, MultinomialNB
from sklearn.pipeline import make_pipeline, make_union
from tpot.builtins import... |
8fced2dfae7ac8d5873fa1b255ff814998d731a5de788b2e9426fe83069ccad2 | Python | 2,000 | 43 |
import h5py
import numpy as np
train_all = "../../../../datasets/fedgan_syn/brats_h5_all/brats_resnet_9blocks_epoch160_experiment_0.h5"
train_h5 = "../../../../datasets/fedgan_seg_data_brats/brats_resnet_9blocks_epoch160_experiment_0_trainset.h5"
val_h5 = "../../../../datasets/fedgan_seg_data_brats/brats_resnet_9blo... |
bbc4e20a8154ffe1125c7651f44f502623294827b2a299f4f10b8829f47e5f2d | Python | 2,000 | 67 | from dataclasses import dataclass
from typing import Optional, Union
from .exceptions import StopCodonValidationError
from .modes import StopCodonMode
STOP_CODONS = frozenset({"TAA", "TAG", "TGA", "UAA", "UAG", "UGA"})
def normalize_stop_codon_mode(
mode: Union[StopCodonMode, str, None],
) -> Optional[StopCodon... |
8cdd9431b3b07c5aa4b7257f927b241323e429ea8ae85da51f168168b9283ef0 | Python | 2,005 | 68 | # Module containing the abstract classes used by the framework
#
# Author: Fernando García Gutiérrez
# Email: fgarcia@fundacioace.org
#
import multiprocessing as mp
from abc import ABCMeta, abstractmethod
class BaseWrapper(object):
""" Class inherited by all the wrappers of the algorithms implemented in... |
401bb988796f6694f3a6c143e3a6c08a32aa17a3f9e01066b3b22cca6ebd1145 | Python | 2,008 | 51 | # from .utils import transform_tensor_to_list
class FedMedGanTrainer(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
... |
5cf896c8c97eb6a41e985ce839b6ac68e20ae0b972bede808d1458c9cbdf08f1 | Python | 2,009 | 72 | 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}}
training_splits = [0,1,4,6,7,9]
number_repo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.