sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
e4e631022e3720ecfac175ab5db5ee3d6eed25495c4f37f9b9c2499103fc5405
Python
4,544
110
""" ONNX-runtime validation script This script was created to verify accuracy and performance of exported ONNX models running with the onnxruntime. It utilizes the PyTorch dataloader/processing pipeline for a fair comparison against the originals. Copyright 2020 Ross Wightman """ import argparse import numpy as np im...
1c451f197c362cfb285ae3aef689126e3470c0757637d4374a1864affc53a4dc
Python
4,546
170
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
c9cf413364038ab6e6c9e9db047bd291a6bd8674d1251f58d84c3d3e4a27675d
Python
4,546
140
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from neuron import h import Functions.globalFunctions.morphology_v2 as mphv2 from Model import Cells font = {'family': 'helvetica', 'size': 10} mpl.rc('font', **font) image_w = 9 pttocm = 0.0352777778 scale_diams = image_w/pttocm/1...
88a6300c35d175c63a37943be714a9b7677edf001489897a95746f720d695b19
Python
4,549
143
""" Activation Factory Hacked together by / Copyright 2020 Ross Wightman """ from typing import Callable, Optional, Type, Union from .activations import * from .activations_me import * from .config import is_exportable, is_scriptable from .typing import LayerType # PyTorch has an optimized, native 'silu' (aka 'swish'...
dba9cbd74eafe40dd8bfb21a2923c53bd5e838b4be1c8e64db503bed1086ec24
Python
4,549
153
# Copyright (c) OpenMMLab. All rights reserved. import gzip import hashlib import os import os.path import shutil import tarfile import urllib.error import urllib.request import zipfile __all__ = ['rm_suffix', 'check_integrity', 'download_and_extract_archive'] def rm_suffix(s, suffix=None): if suffix is None: ...
7044d623f7ad15a6cd6a37429aae0d75a93259042de6f96a8b2cfb3d1f042de0
Python
4,556
106
import torch import torch.nn.functional as F import numpy as np from torchvision.utils import draw_segmentation_masks def heaviside(input, threshold=0.5): """Heaviside function Arguments: input {torch.Tensor} -- Input tensor Keyword Arguments: threshold {float} -- Input values...
ee3a994ded9d9ebc594c96b6b9650663570e02178bfa1f22219daab40c7116f6
Python
4,565
172
import pdb import torch import torch.nn as nn from DT_for_WDN_leak_localization.model_architectures.transformers import DecoderLayer, EncoderLayer, PositionalEmbedding from DT_for_WDN_leak_localization.models.parameter_encoder import ( CategoricalEmbeddingLayer, ParameterEncoder, TransformerEmbedding ) cl...
c051c3130c0fa82d9137cf7c2304006fedd11ffde435460a38fcc79dfbff8c61
Python
4,566
113
import tensorflow as tf import h5py import numpy as np #################################################################################################### #HELPER FUNCTIONS ################################################################################################### def _bytes_feature(value): """Returns a by...
8700bab43430a5eada02f674faf495515e58ee009e6f6cd43f9815c3380961cd
Python
4,569
119
import numpy as np def saveSVMClassifier (clf): kernelsName = clf.kernel supportShape = clf.support_vectors_.shape VECDIM = clf.n_features_in_ nbSupportVectors = supportShape[0] vectorDimensions = supportShape[1] dualCoefs = clf.dual_coef_ dualCoefs = dualCoefs.reshape(nbSupportVectors) ...
240397cdb106ce2d32e6d99981a3a9f247290463f7f51dc0cea1488f6ab30568
Python
4,570
127
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
82c466d9e7d4a91603b6b515d57a606da1ffb76fbd7b721e0fe2215a9adb0779
Python
4,573
126
##################################################################################################################### # Date created : 10/21/2022 # Date modified: 10/21/2022 # Purpose : This program reads and loads inputs data and passes them to the inference program ############################################...
d1fe7b7b7106d8af2fa731b479e3aba2a5a913824a43c8f9fe500e54ac098411
Python
4,575
143
#!/bin/env python """ Cascade decomposition ===================== This example script shows how to compute and plot the cascade decompositon of a single radar precipitation field in pysteps. """ from matplotlib import cm, pyplot as plt import numpy as np import os from pprint import pprint from pysteps.cascade.bandp...
3f684753a58a04d32d3f797331fb36176261d8bf5c20594ffa44e5d1a7bca3a9
Python
4,576
100
import matplotlib.pyplot as plt import numpy as np from ..spiketrain import SpikeTrain from .spiketrain import SpikeTrainsPlotter from ..utils.time import get_dt, searchsorted class DecodingPlotter: def __init__(self, t=None, model=None, optimizer=None, mask_spikes=None, neurons=None, files=None, stim_dec=None, ...
bdf8d626ea09faaea6e0d820a6410e2401d768f9a371a34eebb9f455a4bd4a2e
Python
4,577
168
# Copyright (C) 2021-2022 Severin Strobl <git@severin-strobl.de> # # SPDX-License-Identifier: MIT # # Exact calculation of the overlap volume of spheres and mesh elements. # http://dx.doi.org/10.1016/j.jcp.2016.02.003 import numpy as np import overlap def test_sphere(): sphere = overlap.Sphere((1, 1, 1), 1) ...
11807b0ab333722dff42e10e4a56606761ac20eda25c09f2b8e33e8dc37d4bb0
Python
4,581
111
import torch import torch.nn as nn import torch.nn.functional as F class AcceleratedCreator(object): def __init__(self, input_dim, base_out_dim, k): super(AcceleratedCreator, self).__init__() self.input_dim = input_dim self.base_out_dim = base_out_dim self.computer = Extractor(k) ...
3637a144bfd61c0e8116921ae41076256f091f91f423fbfaa24c90f4df2c708a
Python
4,583
139
import numpy as np import torch from torchvision import datasets, transforms def get(mini=False, fixed_order=False): data = {} taskcla = [] size = [1, 28, 28] labelsize = 10 #2 seeds = np.array(list(range(labelsize)), dtype=int) if not fixed_order: np.random.shuffle(seeds)...
09ae7c8e8f4e2f519d8c1d99bd009caca5b3f45ebb898e6b71b9d0c53f8ba5c5
Python
4,584
130
""" All the metrics are to be called from here """ from typing import Union import torch from sklearn.metrics import balanced_accuracy_score import numpy as np import torchmetrics as tm from ..utils import get_output_from_calculator def classification_accuracy( prediction: torch.Tensor, target: torch.Tensor, par...
8a553cd16ec4f7535f67b5b9f542f68defa46cfab8b74cdf0949c35d299b806c
Python
4,589
106
import os import numpy as np import tensorflow as tf from util.util import myNumExt import time from sort.rafd8 import pet as myDB from ipdb import set_trace as st from math import ceil import random from options.AV45 import BaseOptions from tqdm import tqdm import logging opt = BaseOptions().parse() # parameter set...
5e8b1e5c4b4917642d8e589c3c7f44c9843dcff3b56dfe49a160c18a554c7d39
Python
4,603
133
import numpy as np from .dataset import Datasets, Dataset # CONSTANT WHERE TO FIND THE DATA from config import SVESSEL_DIR as VESSEL_DIR import SimpleITK as sitk import os from .dataset import Datasets, Dataset, GraphDataset import torch from torch_geometric.data import (Dataset, Data) import torch_geometric.transforms...
c428c89569029c47c0eb416e2bdd51bde7d6fef8146f5f3044886f1338393472
Python
4,604
131
#!/usr/bin/env python import sys import os import deepchem from deepchem.models import GraphConvModel, WeaveModel from deepchem.models.sklearn_models import RandomForestRegressor, SklearnModel import pandas as pd from rdkit import Chem import itertools from esol import ESOLCalculator # Turn off TensorFlow logging os.e...
1640462a3baaef554ce4d586ee21389e2cb4311c22cd5385a7a0c403b9bae344
Python
4,605
102
import numpy as np from torch.utils.data import Dataset, DataLoader, SequentialSampler import torch.nn.functional as F import torch.nn as nn #from torch_plus import additional_samplers from HiSiNet.HiCDatasetClass import HiCDatasetDec, SiameseHiCDataset,GroupedHiCDataset import HiSiNet.models as models import torch im...
6591a0ffaf95c1d45817462102911dd9ed52ef28979da488573ed84eff647342
Python
4,609
165
""" Model / Layer Config singleton state """ import os import warnings from typing import Any, Optional import torch __all__ = [ 'is_exportable', 'is_scriptable', 'is_no_jit', 'use_fused_attn', 'set_exportable', 'set_scriptable', 'set_no_jit', 'set_layer_config', 'set_fused_attn', 'set_reentrant_ckpt', 'u...
153cb3e7afd8b59b8ad2ccf5e012dd83608f636034434bac8c5ad5fcbf1de9b2
Python
4,613
147
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
e51e9b44ca1b74f921ca5484f32c4485769cb840b4fc7bf2a6f036d40954b94e
Python
4,613
139
# This file is part of pyunicorn. # Copyright (C) 2008--2026 Jonathan F. Donges and pyunicorn authors # URL: <https://www.pik-potsdam.de/members/donges/software-2/software> # License: BSD (3-clause) # # Please acknowledge and cite the use of this software and its authors # when results are used in publications or publi...
cb98b3bf932e12af89804bc65f456c3443f175d4dffe84e6aa0ba743d80cd7c6
Python
4,615
93
from pydantic import validate_call, ConfigDict, Field, BaseModel from typing import Annotated, List, Tuple, Union from enum import Enum import numpy as np from cellprofiler_library.measurements.measurement_model import LibraryMeasurements from cellprofiler_library.functions.measurement import get_granularity_measureme...
485fe656031877d64242dcf06fc2d85bd6fe8922716d9579823928edb09b6241
Python
4,618
105
import torch from .base_model import BaseModel from . import networks class CNNModel(BaseModel): """ This class implements a base CNN model using only the generator architecture. The model training requires '--dataset_mode aligned or np_array_aligned' dataset. By default, it uses a '--netG unet256' U-Net...
233ff42fad01734d69b60880adee72e4392534230f487475215f3568bf7cbc4e
Python
4,623
137
import numpy as np import torch import cv2 from torchio.data.image import ScalarImage from .base import TemplateNormalizeBase from .utils import rgb2od, od2rgb from .stain_extractors import VahadaneExtractor, RuifrokExtractor, MacenkoExtractor class StainNormalizer(TemplateNormalizeBase): """Stain normalization ...
61ee65bd7d52e7387a9edda40e09dcc37c3ac4c45977bc6717a49c2ef54d5da9
Python
4,624
103
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Aug 22 10:59:54 2018 @author: saskiad """ import numpy as np import pandas as pd import os, h5py import scipy.stats as st import core def do_sweep_mean(x): return x[28:35].mean() def do_sweep_mean_shifted(x): return x[30:40].mean() class Loc...
800d6e6c792c45f74d6c3b6ca05e01a5d042484062d480abfe09d7034411d45d
Python
4,625
113
import pdb import numpy as np import matplotlib.pyplot as plt import torch.nn as nn import torch.optim as optim import torch class Preprocessor(): def __init__(self, num_pipes: int, num_nodes: int): self.num_pipes = num_pipes self.num_nodes = num_nodes self.min_flow_rate = 1e8*torch.ones...
68103b6f3e465e83d59c2ea88a260878eade0741f31c38c63e31fa32996ecd26
Python
4,629
101
"""Registry of natural-language query terms -> direct NIDM/BIDS predicates. Some NIDM facts are stored as *direct predicates* on entities rather than as ``nidm:DataElement`` / ``nidm:PersonalDataElement`` nodes. For example ``bidsmri2nidm`` / ``csv2nidm`` write, on the imaging acquisition object:: niiri:... nid...
9258e94dc30e1a482ed2e926bea3017b848643ce5adf59721bc4fd88eb3a3d91
Python
4,631
102
""" @author: Johanna Rahm Research group Heilemann Institute for Physical and Theoretical Chemistry, Goethe University Frankfurt a.M. Handle saving of DeepSTORM2DAddOns Jupyter Notebook. """ import os import csv import tifffile def save_convert_file(data_path, converted_file): # Convert localization file (csv ...
bc6418c03893dd8f3293fc4b36407c0e05b5ad8a44730629d1309d08ee68593b
Python
4,631
142
from huggingface_hub import HfApi, snapshot_download, ModelCardData, ModelCard from typing import List, Union from GANDLF import version from pathlib import Path from GANDLF.utils import get_git_hash import re def validate_model_card(file_path: str): """ Validate that the required fields in the model card are...
6f54d79e0987212823891833e822aff3bc6b39f7164e80a63a2e2e98ec5ec4bc
Python
4,632
143
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
968bd3a50c5ed5fe26a6ffb7417585b7be4a5bda24e98b4b6b5a738100a45bec
Python
4,632
106
"""Dataset class template This module provides a template for users to implement custom datasets. You can specify '--dataset_mode template' to use this dataset. The class name should be consistent with both the filename and its dataset_mode option. The filename should be <dataset_mode>_dataset.py The class name should...
d65ecee263a1e5ef932f028402011f76090051b192edee127ff4a4a43db43ec5
Python
4,632
116
import pytest from click.testing import CliRunner from GANDLF.entrypoints.generate_metrics import new_way, old_way from . import CliCase, run_test_case, TmpDire, TmpFile, TmpNoEx # This function is a place where a real logic is executed. # For tests, we replace it with mock up, and check if this function is ca...
ef2e758d7db419228ef3ad1d710d9c2db96670e6f6b3372539bce9c5d438acb5
Python
4,632
132
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Visualize the results of the sensor optimization. Read the results to be visualized from the folder passed as command-lie parameter to this script. """ import math import sys from math import isclose import numpy as np import matplotlib.pyplot as plt from mayavi impor...
85c17ba985d1cd63ff03ee3d667100cd0e84f750bcf50ae3b184ac14c015b0bf
Python
4,633
108
from abc import abstractmethod, ABC from sklearn.model_selection import RepeatedStratifiedKFold from src.datamodules.tabular import TabularDataModule import numpy as np from src.utils import utils from itertools import combinations from math import comb log = utils.get_logger(__name__) class CVSplitter(ABC): de...
e96c8041b38b4961e05cb680e59dcaeb7e027361a6e4b2f19c60dc09f702d36e
Python
4,634
142
# -*- coding: utf-8 -*- import numpy as np import pytest from pysteps.utils import get_method interp_methods = ( "idwinterp2d", "rbfinterp2d", ) @pytest.mark.parametrize("interp_method", interp_methods) def test_interp_univariate(interp_method): coord = np.random.rand(10, 2) input_array = np.random....
4c6f2ea40e48ad05f2963efa66ff46b36b6c921f1846583dc3b213c3fcf0a2d0
Python
4,636
154
'''Train CIFAR10 with PyTorch.''' import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn import torchvision import torchvision.transforms as transforms import os import argparse from models import * from utils import progress_bar parser =...
799dc51f7356a31ea46303a44cb3e87c560d4ad965d8fb4d90c9cfdf7dad2b94
Python
4,638
149
import pdb import torch import matplotlib.pyplot as plt import ray from DT_for_WDN_leak_localization.inference.forward_model import BaseForwardModel from DT_for_WDN_leak_localization.inference.likelihood import Likelihood from DT_for_WDN_leak_localization.inference.true_data import TrueData #@ray.remote(num_gpus=1) d...
972b79a845fc25f98647240d95d67ac6c84be5772e94caaad54d23af86a40ec0
Python
4,639
131
# JHK # Python script for generating ED Figure 7 from netCDF4 import Dataset import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap, cm import os #========================================================== # Set main directory #=====================================================...
a993a20085a488be8aa85a23e99ba8e9056bc55d4acf40e7104d251d40b634fd
Python
4,644
98
import os from unittest import TestCase from .gisles2018 import get_files_patient_path, load_nifti, _ISLESFoldIndices from config import ISLES2018_DIR class DatasetGILSES2018Test(TestCase): def test_get_files_patient_path(self): patient_path = os.path.join(ISLES2018_DIR, "raw", "TRAINING", "case_1") ...
27e2162b44db7d9dfa68f2dc172baf3ef1692006d9762f223388e7cc72b4eba8
Python
4,648
137
import numpy as np import torch from torchvision import datasets, transforms def get(mini=False, fixed_order=False): data = {} taskcla = [] size = [3, 32, 32] labelsize = 10 #2 seeds = np.array(list(range(labelsize)), dtype=int) if not fixed_order: np.random.shuffle(seeds)...
c14f1b2b8103249d7cadc3e9d6bceac86f992e85d5172ff175018f700aa1b902
Python
4,651
146
# from nidm.core.provone import ProvONEDocument import pytest from nidm.core.dot import provone_to_dot pytestmark = pytest.mark.skip( reason="had to comment provone import - was breaking tests from experiment" ) @pytest.fixture(scope="module") def doc(): # Create new provone document with namespaces from...
5fa6a9b5f5eb62125fde132ccd5b388d147910936f13eb66f6bc9e55e4e324a3
Python
4,652
127
import numpy as np import pandas as pd from scipy.stats import f_oneway from typing import Dict, Tuple, Set def extract_significant_p(df: pd.DataFrame, p_value_limit: float): """Return a df, which replaces values that are above p_value_limit with `None`""" return ( df.loc(axis=1)[f"p-value"] ...
6789f14c27c6646a4e3e8a3588743e0e059de7281216e954c8378609a9cc654d
Python
4,653
148
#!/bin/env python """ Probability forecasts ===================== This example script shows how to forecast the probability of exceeding an intensity threshold. The method is based on the local Lagrangian approach described in Germann and Zawadzki (2004). """ import matplotlib.pyplot as plt import numpy as np from ...
c6da2658ef175f4d749009238f54fac3e799de54807ebc5036d1e1a8dedeb17f
Python
4,656
179
# -*- coding: utf-8 -*- """ pysteps.postprocessing.ensemblestats ==================================== Methods for the computation of ensemble statistics. .. autosummary:: :toctree: ../generated/ mean excprob banddepth """ import numpy as np from scipy.special import comb def mean(X, ignore_nan=Fal...
35b701cc85835c9fb5bf713388e0ac2a33cc86d92dadfc63137f0fade9539a81
Python
4,660
152
import numpy as np import sys import seaborn as sns import matplotlib.pyplot as plt import os import os.path as osp sys.path.append('..') from functions.individual_variability import grab_data from functions.def_ROIs_EarlyVisualAreas import roi def color_pal(cluster): palette_tmp = sns.color_palette("PRGn_r") ...
b34da9c704e9a98bd452565c534dbb0bc991f9553877c8695c2f3549762c6c7f
Python
4,663
155
from os import getcwd from os.path import basename, join import nibabel as nib import numpy as np from mrHARDI.base.shell import launch_shell_process from mrHARDI.base.utils import if_join_str, split_ext from mrHARDI.compute.math.stats import center_of_mass_difference from mrHARDI.compute.utils import (compute_reorien...
03d39f699f2bd810ba036b865f134d866c8134e45407f31ea890b6f5945e6e7c
Python
4,664
137
""" Author: "Keitaro Yamashita, Garib N. Murshudov" MRC Laboratory of Molecular Biology This software is released under the Mozilla Public License, version 2.0; see LICENSE. """ from __future__ import absolute_import, division, print_function, generators import os import gemmi import numpy import argparse import j...
731988e170f35bed95f7f81f1bc82e0dacaa44a336e1c7a48fe05cfe1f684e93
Python
4,664
121
import torch import torch.nn as nn import torch.utils.data from torch.utils.data import TensorDataset, DataLoader from sklearn import metrics import pandas as pd import numpy as np from vajiraGAN_original import Pulse2pulseDiscriminator print('Reading in the test data...') # For testing on only NORM/MI patients, cha...
d46a7e46e002e9a511f7a983fa1ba2991ecec5bb1f17d8c97190f2b47cb18d10
Python
4,666
154
''' adapted from https://github.com/all-umass/ManifoldWarping ''' ''' Alignment techniques ''' import numpy as np import scipy as sp from ManinetCluster_python.neighborhood import laplacian from ManinetCluster_python.util import block_antidiag from functools import reduce def _manifold_setup(Wx,Wy,Wxy,mu): Wxy = m...
7523d591ba2c3c7ac6efe374483f1dc5eaf5357baa953dbb475dd10807449750
Python
4,668
145
""" NormAct (Normalization + Activation Layer) Factory Create norm + act combo modules that attempt to be backwards compatible with separate norm + act instances in models. Where these are used it will be possible to swap separate BN + act layers with combined modules like IABN or EvoNorms. Hacked together by / Copyr...
02b393db4474c8e1ba8aee5896b63a48c9b960c41694487fdf63b1ea29518286
Python
4,670
131
# This file is part of pyunicorn. # Copyright (C) 2008--2026 Jonathan F. Donges and pyunicorn authors # URL: <https://www.pik-potsdam.de/members/donges/software-2/software> # License: BSD (3-clause) # # Please acknowledge and cite the use of this software and its authors # when results are used in publications or publi...
f744446bfc130c54d3e9df7a96001c3ee7dd58a4982c3d1bd9f79c5445f6d36d
Python
4,672
98
import os import json import subprocess import numpy as np import pandas as pd import pickle as pkl import nibabel as nib from scipy.stats import zscore from os.path import join as pjoin from sklearn.preprocessing import StandardScaler from scipy.stats import pearsonr from nod_utils import save_ciftifile # change to p...
d54abd0fade1dc4952dd33f981ca7e5fadf38a609907617efcfd2517053c5f5b
Python
4,679
134
# JHK # Python script for generating ED Figure 9 import matplotlib matplotlib.use('Agg') import numpy as np from netCDF4 import Dataset import matplotlib.pyplot as plt import os #========================================================== # Set main directory #==========================================================...
f1d2aeb227ae5fda0ca4cc992d4970739a9a0654c78e1fb7d15c9e6a3476f2b8
Python
4,679
146
""" A demo for multi-output regression ================================== The demo is adopted from scikit-learn: https://scikit-learn.org/stable/auto_examples/ensemble/plot_random_forest_regression_multioutput.html#sphx-glr-auto-examples-ensemble-plot-random-forest-regression-multioutput-py See :doc:`/tutorials/mult...
eab5598d7c47c1f245ab0d7d52244c60adee17ae7a4207ccc160f3f8b38751ac
Python
4,692
127
import torch import torchmetrics as tm import torch.nn.functional as F # from torch.nn.functional import one_hot from ..utils import get_output_from_calculator from GANDLF.utils.generic import determine_classification_task_type def overall_stats(prediction: torch.Tensor, target: torch.Tensor, params: dict) -> dict: ...
aa03dbeb136ebc42edfc639d9321ec687dad7520cab5919532936d55c576f2c2
Python
4,700
144
from cellprofiler_core.module.image_segmentation import ImageSegmentation from cellprofiler_core.setting import Binary from cellprofiler_core.setting.text import Integer from cellprofiler_library.modules._convertimagetoobjects import convert_image_to_objects HELP_BINARY_IMAGE = """\ This module can also convert a gray...
4b3e69bb843917dbe9b80d6d4c6e3437a8c55ae80549dd9e7c4cd8b277190d75
Python
4,705
125
import torch import torch.nn as nn import torch.nn.functional as F from .resnet import conv3x3, PreActResNet, PreActResNet_cifar class SE_PreActBlock(nn.Module): '''Pre-activation version of the BasicBlock.''' expansion = 1 def __init__(self, in_planes, planes, stride=1): super(SE_PreActBlock, se...
532e86f00a7d8b89bcb088ea48544771e910e6c2746f58e9e1324f8caabdc274
Python
4,707
208
# -*- coding: utf-8 -*- import numpy as np import pytest from numpy.testing import assert_array_almost_equal from pysteps.utils import transformation # boxcox_transform test_data = [ ( np.array([1]), { "accutime": 5, "transform": None, "unit": "mm/h", ...
a970a00f9c342ff99968643cb3bf8de9ef0e6dc0dcf0e75253647fca083b25b5
Python
4,713
106
import os import numpy as np import tensorflow as tf from utils import utils class TrainDataGenerator(tf.keras.utils.Sequence): '''inherits from Keras Sequence base object, allows to use multiprocessing in .fit_generator''' def __init__(self, samples, img_dir, batch_size, n_classes, basenet_preprocess, img_f...
dcb3edcf985fe260cf94ff51be661004b011d794ffd95495cddf157a1bf810ec
Python
4,716
118
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
2e14e6a7655e627ec934acbccdaff9d52e80eeffc9b8af0f6588f2601fe396c4
Python
4,722
107
""" Educational Use License This software is provided solely for educational purposes. Any use of this software for commercial or non-educational purposes is prohibited. If you use this software in an academic setting, you must cite the following paper in any resulting publications or presentations: [Sanaullah, Ko...
91d131173fc39ba35e535b9bf5c1d56a7b4e39307cb915f4078d116ab560020e
Python
4,722
89
import numpy from pydantic import Field, validate_call, ConfigDict from typing import Annotated, Optional, Tuple, Dict, Callable from numpy.typing import NDArray from cellprofiler_library.functions.image_processing import flip_image_both, flip_image_left_to_right, flip_image_top_to_bottom, rotate_image_angle, rotate_im...
cb2882ef351411dff6e006933cd4aec808782cf10f621dbdd152a5d66af659f5
Python
4,729
104
if __name__ == '__main__': import Functions.setup as stp import matplotlib.pyplot as plt import numpy as np from Model import Cells import Functions.globalFunctions.ExtracellularField as eF from Functions.globalFunctions.utils import MyEncoder,Dict import json import os from datetime...
5e884e351565a9aedc9c8aad5c77710eca654bffeff40fbf09d177b7f8c9672d
Python
4,730
132
import os import random import torch import torch.nn as nn from torch.optim import Adam from model import CNN from torchtext import data from torchtext import vocab from data import DataIterator from collections import namedtuple, defaultdict from sklearn.metrics import classification_report from loss import FocalLoss ...
ef1029d52ae9a5d056d144c937f9e82bd68c7ae42a3e1a28f44182772e256a8d
Python
4,732
175
import pdb import torch import torch.nn as nn from DT_for_WDN_leak_localization.model_architectures.transformers import DecoderLayer, EncoderLayer, PositionalEmbedding from DT_for_WDN_leak_localization.models.parameter_encoder import ( CategoricalEmbeddingLayer, ParameterEncoder, TransformerEmbedding ) cl...
30b615fcd19e38f5d10692ffdab4c07aec452bbcdb549d4f5e9a4ff8978eee7d
Python
4,733
134
""" ClinicalASL - Clinical Arterial Spin Labeling processing pipeline Repository: https://github.com/JSIERO/ClinicalASL Author: Jeroen Siero Institution: UMCU (University Medical Center Utrecht), The Netherlands Contact: j.c.w.siero@umcutrecht.nl Description: This script provides a function to smooth ASL...
e0ef3504d330a2491dec3d1cf0a9d025751257b6dc4c1a4703434384720570aa
Python
4,733
151
__all__ = ['imread', 'imread_collection'] import skimage.io as io try: from astropy.io import fits as pyfits except ImportError: try: import pyfits except ImportError: raise ImportError( "PyFITS could not be found. Please refer to\n" "http://www.stsci.edu/resources/...
baff8d074cf90935fd0050d5b0e8483aeafbf2f1a3017797ae58c109c90ea582
Python
4,735
121
import importlib from pathlib import Path import numpy as np import pandas as pd import torch.nn as nn import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler from models.aggregators.aggregator import BaseAggregator def get_loss(name, **kwargs): # Check if the name is a valid loss name i...
d1201f7a84164b057ae12e7dabfc1f30e4e7ad7deddacf4dc372c2198b87318c
Python
4,735
121
import importlib from pathlib import Path import numpy as np import pandas as pd import torch.nn as nn import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler from models.aggregators.aggregator import BaseAggregator def get_loss(name, **kwargs): # Check if the name is a valid loss name i...
d56723061552ab182985159435f003a23b6029ad4127f0d78fcbd08b2b2f3d1d
Python
4,735
156
import click from GANDLF.entrypoints import append_copyright_to_help from GANDLF.cli.huggingface_hub_handler import push_to_model_hub, download_from_hub from pathlib import Path huggingfaceDir_ = Path(__file__).parent.absolute() huggingfaceDir = huggingfaceDir_.parent # Huggingface template by default Path for the M...
135d155ae55cda6089029940738eeb8eaff9946725459bd76a426a317934ab25
Python
4,737
93
import numpy from typing import Tuple, Optional, Any, Dict, Union, Annotated, List from numpy.typing import NDArray from cellprofiler_library.types import Image2DBinary, ObjectSegmentation, Image2DColor, Image2DGrayscale from pydantic import Field, validate_call, ConfigDict, BaseModel from cellprofiler_library.function...
ef8b65e99e6ba1044128fa7a5935194e6b919c9ae1a84089354b8b6871875bc2
Python
4,739
183
"""Render the two embedded raster assets for the graphical abstract. paper_figures/ga_brain.png — glass-brain (lateral) with 32 region-coloured AFIDs, transparent paper_figures/ga_crop.png — tight crop of the /learn interface (viewer + tutor) """ from __future__ import annotations from pathlib import Pat...
effc50cc017066d60f3e8bc9f4a65b2765ad374a1b4da7bf023c1db99e8f1cd9
Python
4,740
173
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
a8e05605018a5c1a21680b78b4596544de870ccc7231f07657257ee67463ef5e
Python
4,743
161
""" @author: Nikolai M Chapochnikov Created in 2022 Testing that the SNMF functions is doing what we want it to do on different datasets ALL TESTS PASS if not, need to decrease relative error tolerance """ import pandas as pd import numpy as np import pytest from scipy import linalg as LA import functions.datasets...
a3c2c0b7a2829792a02cd38bc4f66a8dc8a6a4e68c1e578b627aa4283bcf7121
Python
4,747
139
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
28251d0dea2c907b61004296b7792bc9294a809a02c137b496e9f069824b89ad
Python
4,748
109
import numpy as np import tensorflow as tf import tensorflow_probability as tfp from optimiser_tools import * import tqdm tfd = tfp.distributions @tf.function def softplus(x, k=1.0): k = tf.cast(k, float) return tf.math.divide(tf.math.log(tf.math.add(1.0, tf.math.exp(tf.math.multiply(x, k)))), k) # initializ...
33a7284d6c96562f4b360764e845a6d79d7df8220e22b3ecc57eace075352afc
Python
4,748
119
from __future__ import absolute_import import numpy as np import unittest import centriole.index as I class TestIndexes(unittest.TestCase): def test_00_00_oh_so_empty(self): ind = I.Indexes([[]]) self.assertEqual(ind.length, 0) self.assertEqual(len(ind.fwd_idx), 0) self.assertEqua...
dc902672bf9d237a0ff1bf4a365018ca4ea7715a2528429d79c989b17be4580a
Python
4,749
125
from data.base_dataset import BaseDataset, get_transform from data.image_folder import make_dataset from util.util import normalize from skimage import io from util import util import numpy as np class SimulationCropDataSet(BaseDataset): """ This class is a modified version of DiceImage dataset module, only w...
f0006fbe47da13aa1a632d75bc1acac0479d939eb2368f5730cc6c4b937ab5a8
Python
4,751
161
import os.path as op def bool_arr_type(var): return var def str_arr_type(var): return var def int_arr_type(var): return var def float_arr_type(var): return var def list_of_int_lists_type(var): return var def add_arguments(parser, arguments): for argument in arguments: parser.add_argument(argument) def ...
716b96e6d87f950571077ee768c218c848caf766f97b407eb85abc836241a470
Python
4,760
172
import pdb import torch import torch.nn as nn from DT_for_WDN_leak_localization.model_architectures.transformers import DecoderLayer, EncoderLayer, PositionalEmbedding from DT_for_WDN_leak_localization.models.parameter_encoder import ( CategoricalEmbeddingLayer, ParameterEncoder, TransformerEmbedding ) cl...
f004377ac93703426c2ab4799c73d0c0bf588eed0beb1bb2c839b6b222781365
Python
4,763
128
#Importing libraries: import pandas as pd import numpy as np import wfdb import ast #Define function to load the data: def load_raw_data(df, sampling_rate, path): if sampling_rate == 100: data = [wfdb.rdsamp(path+f) for f in df.filename_lr] else: data = [wfdb.rdsamp(path+f) for f in df.filenam...
762f3393c12044abb9cb4f80ab46814e0acaa37d1258cf3074bb2755e0da66a5
Python
4,765
112
import warnings from typing import Optional, Tuple, Union import torch import psutil from .loss_and_metric import get_loss_and_metrics def step( model: torch.nn.Module, image: torch.Tensor, label: Optional[torch.Tensor], params: dict, train: Optional[bool] = True, ) -> Tuple[float, dict, Union[tor...
ec97493f10da5f36b42762c60e8277ba842552d0e21b6357278827374ca47ecb
Python
4,766
165
import torch import os import numpy as np import tifffile from skimage import transform class Train_Dataset(torch.utils.data.Dataset): def __init__(self, dirc_data, transform_train): self.dirc_data = dirc_data self.list_data = os.listdir(self.dirc_data) self.list_data.sort(key=lam...
e5229d0a125c8aa1c9b2f68ebd59b9ab1edda4050878d643ae5e162893d435ec
Python
4,769
102
""" Author: Mingjian He <mh1@stanford.edu> Testing functions for switching methods in somata/switching """ import numpy as np from test_load_data import _load_data # type: ignore def test_switching(): from somata.switching import switching from somata import OscillatorModel as Osc input_data = _load_d...
9335f0552048f30648827ffcd7134d493005c18bc366e61a8f1153453a7c1eff
Python
4,772
122
"""Install public assets, catalog metadata, and shared markup in the documentation.""" import argparse import re from contextlib import suppress from functools import partial from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from shutil import copy2 def install(documentat...
c494782d0a13e00fade749912cb18f3fbdb1a3d65141a008b3ab218c8d88efa9
Python
4,777
142
elements = {"Ag": 106.905095, "Al": 26.981541, "Ar": 39.962383, "As": 74.921596, "Au": 196.96656, "B": 11.009305, "Ba": 137.905236, "Be": 9.012183, "Bi": 208.980388, "Br": 78.918336, "C": 12, ...
a478bd6625f5e3be42b2c9bb51b630c5439bc6bf46d300fd7cc7e76d17587fd3
Python
4,785
202
from __future__ import division from numpy import * import numpy as np import sys sys.path.insert(0, '../../helpers/') from circ_stats import * import random import itertools import scipy from joblib import Parallel, delayed import multiprocessing import scipy.signal from scipy.signal import correlate from pickle imp...
9466e6c39b05897af3970f14814b67c414a5bd24550284beef3abdc46ce79b37
Python
4,787
138
import torch import torch.nn.functional as F import numpy as np class TaskLoss(torch.nn.Module): def __init__(self, losses=['cross_entropy'], gamma=2.0, num_classes=13, alpha=None, weight=None, ignore_index=None, reduction='mean'): super(TaskLoss, self).__init__() self.losses = losses self...
7017214b1d3f27b8288162fde13476189c9bc48a0a1d7372abdcc819fa176114
Python
4,792
165
import tensorflow as tf import numpy as np from lib.network import Network from lib.pinn import PINN from Helper import calcW import matplotlib.pyplot as plt import pandas as pd import os linewidth = 4 fontsize = 20 font = {'family' : 'monospace', 'weight' : 'bold', 'size' : fontsize } plt.rc('fon...
d02f45d96035ff6fe99780726a1ed746ee1ccdd7e463caf0388b9ddfad1dc737
Python
4,797
169
""" MeasureImageSkeleton ==================== **MeasureImageSkeleton** measures the number of branches and endpoints in a skeletonized structure such as neurons, roots, or vasculature. This module can analyze the number of total branches and endpoints for branching objects in an image. A branch is a pixel with more t...
d9c0126be5abf106bad3d2c36b7c2b1da70630f60f88418b90281b115781bb32
Python
4,803
178
import time import numpy as np import os import warnings import scipy.io as scio import math from matplotlib import pyplot as plt import torch from braincog.base.node.node import * import turicreate as tc from braincog.base.brainarea.BrainArea import * from braincog.utils import * warnings.filterwarnings('ignore') np...
7c0bf243ee97998fa12c507bb65efb5bd07367929c09bcfd7bb48908c9396960
Python
4,808
143
# JHK # Python script for generating Figure 3. from netCDF4 import Dataset import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl #========================================================== # Set main directory #========================================================== hdir = '/home/jhkim/model/...
5ffe7c417482b52e1a88ebbef0bc7770114621a9db97348f1a2286bc708f7c3f
Python
4,809
110
r""" pysteps.nowcasts.interface ========================== Interface for the nowcasts module. It returns a callable function for computing nowcasts. The methods in the nowcasts module implement the following interface: ``forecast(precip, velocity, timesteps, **keywords)`` where precip is a (m,n) array with inpu...
10428cbb544a5aa9d283e5321c09ad67cf8e0640b6deae46b85a0b11ec5f3996
Python
4,820
158
""" This file implements Oja's hebbian learning rule. Relevant book chapters: - http://neuronaldynamics.epfl.ch/online/Ch19.S2.html#SS1.p6 """ # This file is part of the exercise code repository accompanying # the book: Neuronal Dynamics (see http://neuronaldynamics.epfl.ch) # located at http://github.com/EPFL-LC...
74162e4fc95f360e1f37214eded9524d19e1907983613a09456ecac860e89777
Python
4,820
164
import os import threading from copy import deepcopy from http.server import HTTPServer, SimpleHTTPRequestHandler from tempfile import mkdtemp import requests_cache from . import get_logger lgr = get_logger() class LoggingRequestHandler(SimpleHTTPRequestHandler): def log_message(self, format, *args): l...
4acab0d838f5cfab4ceafccaa334e668e1f3e8cd3864aeb106c49536c978000e
Python
4,821
161
import math import numpy import cellprofiler_core.image class TestImage: def test_init(self): cellprofiler_core.image.Image() def test_init_image(self): x = cellprofiler_core.image.Image(numpy.zeros((10, 10))) def test_init_image_mask(self): x = cellprofiler_core.image.Image( ...
553b437f702a51901d245a714fd59509b812294671d19eee074c17942b9e2382
Python
4,822
124
from __future__ import absolute_import import unittest import numpy as np from centriole.otsu import otsu, entropy, otsu3, entropy3 from centriole._np_compat import np_NaN class TestOtsu(unittest.TestCase): def test_01_TwoValues(self): """Test Otsu of two values is between the two""" x = otsu([0.2...