repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
document-image-binarization | document-image-binarization-master/binarize/util.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
import time
import random
import numpy as np
from keras import backend as K
#------------------------------------------------------------------------------
def init():
random.seed(1337)
np.set_printoptions(threshold=sys.maxsize)
... | 2,484 | 33.513889 | 121 | py |
document-image-binarization | document-image-binarization-master/binarize/utilDataGenerator.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import math
import cv2
import numpy as np
from keras import backend as K
# ----------------------------------------------------------------------------
def load_files(array_x_files, x_sufix, y_sufix):
x_data = []
y_d... | 6,388 | 34.893258 | 148 | py |
document-image-binarization | document-image-binarization-master/binarize/train.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys, os
import cv2
import argparse
import numpy as np
import warnings
from keras import backend as K
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import util, utilFit, utilDataGenerator, utilModelREDNet
util.init()
w... | 13,051 | 41.653595 | 156 | py |
med-dyn-reg | med-dyn-reg-main/train_ackis_sag.py | import tensorflow as tf
import os
import datetime
import argparse
import json
import numpy as np
from config import get_config
from src.models.fkvae import fKVAE
from src.callbacks import SetLossWeightsCallback, VisualizeResultCallback
def main(dim_y = (112,112),
dim_x = 4,
dim_z = 8,
... | 6,826 | 43.914474 | 147 | py |
med-dyn-reg | med-dyn-reg-main/train_ackis.py | import tensorflow as tf
import os
import datetime
import argparse
import json
import numpy as np
from collections import defaultdict
from config import get_config
from src.models.multi_model import MultiModel
from src.callbacks import SetLossWeightsCallbackMM, VisualizeResultCallbackMM
def main(dim_y = (112... | 6,337 | 42.410959 | 147 | py |
med-dyn-reg | med-dyn-reg-main/train_unity.py | import tensorflow as tf
import os
import datetime
import argparse
import json
import numpy as np
import glob
from config import get_config
from src.models.fkvae import fKVAE
from src.callbacks import SetLossWeightsCallback, VisualizeResultCallback
from src.data.mhaDataset import MergedDataLoader, VolunteerDataLoader
... | 6,254 | 41.842466 | 147 | py |
med-dyn-reg | med-dyn-reg-main/train_lgssm.py | import os
import argparse
import tensorflow as tf
import numpy as np
from tqdm import tqdm
from src.models.fkvae import fKVAE
from src.models.lgssm import FineTunedLGSSM
from src.result_utils import get_config
from src.data.mhaDataset import VolunteerDataLoader
def main(org_model_path,
loss_metric,
... | 3,202 | 33.815217 | 112 | py |
med-dyn-reg | med-dyn-reg-main/train_proknow.py | import tensorflow as tf
import os
import datetime
import argparse
import json
import numpy as np
import glob
from config import get_config
from src.models.fkvae import fKVAE
from src.callbacks import SetLossWeightsCallback, VisualizeResultCallback
from src.data.numpyDataset import ProKnowDataLoader, ComodoDataLoader
... | 6,616 | 42.248366 | 147 | py |
med-dyn-reg | med-dyn-reg-main/finetune_ssm.py | import argparse
import datetime
import os
import sys
import json
from tqdm import tqdm
import io
import matplotlib.pyplot as plt
import numpy as np
import inspect
import math
import tensorflow as tf
import tensorflow_probability as tfp
from config import get_config
from src.flow_models import fKVAE
from src.datasetLo... | 7,701 | 39.536842 | 165 | py |
med-dyn-reg | med-dyn-reg-main/train_sim.py | import tensorflow as tf
import os
import datetime
import argparse
import json
import numpy as np
import glob
from config import get_config
from src.models.fkvae import fKVAE
from src.callbacks import SetLossWeightsCallback, VisualizeResultCallback
from src.data.simDataset import SimDataLoader
def main(dim_y... | 6,267 | 41.931507 | 147 | py |
med-dyn-reg | med-dyn-reg-main/train_echonet.py |
import tensorflow as tf
import os
import datetime
import argparse
import json
from config import get_config
from src.models.fkvae import fKVAE
from src.data.datasetLoader import TensorflowDatasetLoader
from src.callbacks import SetLossWeightsCallback, VisualizeResultCallback
def main(dim_y = (112,112),
dim_... | 6,439 | 42.221477 | 152 | py |
med-dyn-reg | med-dyn-reg-main/train_vrnn.py | import tensorflow as tf
import os
import datetime
import argparse
import json
import numpy as np
import glob
from src.models.vrnn_model import VRNN
from src.data.mhaDataset import MergedDataLoader, VolunteerDataLoader
from src.callbacks import SetLossWeightsCallback, VisualizeResultCallback
from config import get_con... | 5,250 | 42.396694 | 147 | py |
med-dyn-reg | med-dyn-reg-main/src/losses.py | import tensorflow as tf
import tensorflow.experimental.numpy as tnp
import tensorflow.keras.backend as K
def _diffs(y):
org_shape = y.get_shape()
y = tf.reshape(y, (-1, y.shape[2], y.shape[3], y.shape[4]))
vol_shape = y.get_shape().as_list()[1:-1]
ndims = len(vol_shape)
df = [None] * ndims
for... | 6,023 | 32.281768 | 104 | py |
med-dyn-reg | med-dyn-reg-main/src/callbacks.py | from tensorflow.keras import backend as K
import tensorflow as tf
tfk = tf.keras
from .utils import plot_to_image, latent_plot
class SetLossWeightsCallback(tfk.callbacks.Callback):
def __init__(self, kl_growth):
self.kl_growth = kl_growth
def set_value(self, model, new_beta_value):
K.set_valu... | 10,288 | 41.692946 | 105 | py |
med-dyn-reg | med-dyn-reg-main/src/metrics.py | import numpy as np
import tensorflow as tf
import tensorflow.keras.backend as K
from tensorlayer.cost import dice_coe, dice_hard_coe
import pystrum.pynd.ndutils as nd
class NCC:
"""
Local (over window) normalized cross correlation loss.
"""
def __init__(self, win=None, eps=1e-5):
self.win = ... | 4,768 | 29.767742 | 93 | py |
med-dyn-reg | med-dyn-reg-main/src/evaluation/demons.py | import SimpleITK as sitk
import numpy as np
class Demons:
def calc(self, fixed, moving, moving_seg=None):
warped = np.zeros(fixed.shape)
jac = np.zeros(fixed.shape)
warped_seg = np.zeros(fixed.shape)
if len(fixed.shape) == 4: # batch
for b in range(fixed.shape[0]):
... | 6,274 | 41.687075 | 118 | py |
med-dyn-reg | med-dyn-reg-main/src/models/layers_skip2.py | import tensorflow as tf
import tensorflow_probability as tfp
from .utils import set_name
tfkl = tf.keras.layers
tfk = tf.keras
tfpl = tfp.layers
tfd = tfp.distributions
class Fc_block(tfkl.Layer):
def __init__(self, h, w, c, name='fc_block', dropout_prob=0.0, reg_factor=0.01, prefix=None, **kwargs):
supe... | 14,632 | 46.977049 | 143 | py |
med-dyn-reg | med-dyn-reg-main/src/models/layers_skip.py | import tensorflow as tf
import tensorflow_probability as tfp
from .utils import set_name
tfkl = tf.keras.layers
tfk = tf.keras
tfpl = tfp.layers
tfd = tfp.distributions
class Fc_block(tfkl.Layer):
def __init__(self, h, w, c, name='fc_block', dropout_prob=0.0, reg_factor=0.01, prefix=None, **kwargs):
supe... | 15,679 | 47.09816 | 143 | py |
med-dyn-reg | med-dyn-reg-main/src/models/vae.py | import tensorflow as tf
import tensorflow_probability as tfp
from .layers_skip import Encoder, Decoder
from .utils import ssim_calculation, set_name
tfd = tfp.distributions
tfk = tf.keras
tfpl = tfp.layers
class VAE(tfk.Model):
def __init__(self,
config,
name="vae",
... | 4,385 | 38.872727 | 174 | py |
med-dyn-reg | med-dyn-reg-main/src/models/vrnn_model.py | import tensorflow as tf
import tensorflow_probability as tfp
from voxelmorph.tf.layers import SpatialTransformer as SpatialTransformer
from voxelmorph.tf.layers import VecInt
import numpy as np
from .layers_skip import Encoder, Decoder
from ..losses import grad_loss
tfk = tf.keras
tfkl = tf.keras.layers
tfpl = tfp.lay... | 10,460 | 39.70428 | 125 | py |
med-dyn-reg | med-dyn-reg-main/src/models/kvae.py | import tensorflow as tf
import tensorflow_probability as tfp
from voxelmorph.tf.losses import NCC, MSE
from .layers_skip import Encoder, Decoder
from .lgssm import LGSSM
from .utils import set_name
tfk = tf.keras
tfd = tfp.distributions
class KVAE(tfk.Model):
def __init__(self, config, name='kvae', prefix=None, ... | 9,789 | 44.962441 | 174 | py |
med-dyn-reg | med-dyn-reg-main/src/models/fkvae.py | import tensorflow as tf
import tensorflow_probability as tfp
from voxelmorph.tf.layers import SpatialTransformer as SpatialTransformer
from voxelmorph.tf.layers import VecInt
from voxelmorph.tf.losses import Grad
tfk = tf.keras
tfpl = tfp.layers
tfd = tfp.distributions
from .layers_skip import Decoder
from .kvae imp... | 6,824 | 41.12963 | 116 | py |
med-dyn-reg | med-dyn-reg-main/src/models/lgssm.py | import tensorflow as tf
import tensorflow_probability as tfp
from .utils import set_name
tfk = tf.keras
tfpl = tfp.layers
def get_cholesky(A):
L = tfp.experimental.distributions.marginal_fns.retrying_cholesky(A, jitter=None, max_iters=5, name='retrying_cholesky')
return L[0]
class LGSSM(tfk.Model):
def... | 14,147 | 44.935065 | 157 | py |
med-dyn-reg | med-dyn-reg-main/src/models/multi_model.py | import tensorflow as tf
tfk = tf.keras
from .fkvae import fKVAE
class MultiModel(tfk.Model):
def __init__(self, config, name='multi_model', **kwargs):
super(MultiModel, self).__init__(self, name=name, **kwargs)
self.config = config
self.transversal_model = fKVAE(config, 'transversal_model'... | 2,578 | 47.660377 | 174 | py |
med-dyn-reg | med-dyn-reg-main/src/data/unityDataLoader.py | import numpy as np
import glob
import os
import SimpleITK as sitk
import ntpath
from tqdm import tqdm
import tensorflow as tf
cut2s = [os.path.join('V2_2035418238_ThoraxandPelvis','Fraction1'),
os.path.join('V2_2035418238_ThoraxandPelvis','Fraction2'),
os.path.join('V2_2035418238_ThoraxandPelvis','F... | 5,693 | 41.81203 | 160 | py |
med-dyn-reg | med-dyn-reg-main/src/data/datasetLoader.py | import tensorflow as tf
import numpy as np
import cv2
import pathlib
import os
import pandas as pd
from tqdm import tqdm
def loadvideo(filename: str):
"""Loads a video from a file.
Args:
filename (str): filename of video
Returns:
A np.ndarray with dimensions (frames, height, width). The
... | 23,617 | 32.311707 | 143 | py |
FastSpeech2 | FastSpeech2-master/evaluate.py | import argparse
import os
import torch
import yaml
import torch.nn as nn
from torch.utils.data import DataLoader
from utils.model import get_model, get_vocoder
from utils.tools import to_device, log, synth_one_sample
from model import FastSpeech2Loss
from dataset import Dataset
device = torch.device("cuda" if torch... | 3,596 | 28.975 | 170 | py |
FastSpeech2 | FastSpeech2-master/dataset.py | import json
import math
import os
import numpy as np
from torch.utils.data import Dataset
from text import text_to_sequence
from utils.tools import pad_1D, pad_2D
class Dataset(Dataset):
def __init__(
self, filename, preprocess_config, train_config, sort=False, drop_last=False
):
self.datase... | 7,912 | 30.031373 | 84 | py |
FastSpeech2 | FastSpeech2-master/synthesize.py | import re
import argparse
from string import punctuation
import torch
import yaml
import numpy as np
from torch.utils.data import DataLoader
from g2p_en import G2p
from pypinyin import pinyin, Style
from utils.model import get_model, get_vocoder
from utils.tools import to_device, synth_samples
from dataset import Tex... | 6,602 | 29.711628 | 97 | py |
FastSpeech2 | FastSpeech2-master/train.py | import argparse
import os
import torch
import yaml
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from utils.model import get_model, get_vocoder, get_param_num
from utils.tools import to_device, log, synth_one_sample
from model imp... | 7,064 | 34.502513 | 167 | py |
FastSpeech2 | FastSpeech2-master/audio/stft.py | import torch
import torch.nn.functional as F
import numpy as np
from scipy.signal import get_window
from librosa.util import pad_center, tiny
from librosa.filters import mel as librosa_mel_fn
from audio.audio_processing import (
dynamic_range_compression,
dynamic_range_decompression,
window_sumsquare,
)
... | 6,226 | 33.787709 | 85 | py |
FastSpeech2 | FastSpeech2-master/audio/tools.py | import torch
import numpy as np
from scipy.io.wavfile import write
from audio.audio_processing import griffin_lim
def get_mel_from_wav(audio, _stft):
audio = torch.clip(torch.FloatTensor(audio).unsqueeze(0), -1, 1)
audio = torch.autograd.Variable(audio, requires_grad=False)
melspec, energy = _stft.mel_sp... | 1,188 | 32.971429 | 88 | py |
FastSpeech2 | FastSpeech2-master/audio/audio_processing.py | import torch
import numpy as np
import librosa.util as librosa_util
from scipy.signal import get_window
def window_sumsquare(
window,
n_frames,
hop_length,
win_length,
n_fft,
dtype=np.float32,
norm=None,
):
"""
# from librosa 0.6
Compute the sum-square envelope of a window func... | 2,613 | 24.881188 | 86 | py |
FastSpeech2 | FastSpeech2-master/hifigan/models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm, remove_weight_norm
LRELU_SLOPE = 0.1
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.wei... | 5,515 | 30.701149 | 83 | py |
FastSpeech2 | FastSpeech2-master/utils/model.py | import os
import json
import torch
import numpy as np
import hifigan
from model import FastSpeech2, ScheduledOptim
def get_model(args, configs, device, train=False):
(preprocess_config, model_config, train_config) = configs
model = FastSpeech2(preprocess_config, model_config).to(device)
if args.restore... | 2,730 | 28.365591 | 80 | py |
FastSpeech2 | FastSpeech2-master/utils/tools.py | import os
import json
import torch
import torch.nn.functional as F
import numpy as np
import matplotlib
from scipy.io import wavfile
from matplotlib import pyplot as plt
matplotlib.use("Agg")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def to_device(data, device):
if len(data) == 12... | 10,195 | 31.062893 | 88 | py |
FastSpeech2 | FastSpeech2-master/model/modules.py | import os
import json
import copy
import math
from collections import OrderedDict
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from utils.tools import get_mask_from_lengths, pad
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class VarianceAdaptor(nn.M... | 9,819 | 32.063973 | 88 | py |
FastSpeech2 | FastSpeech2-master/model/loss.py | import torch
import torch.nn as nn
class FastSpeech2Loss(nn.Module):
""" FastSpeech2 Loss """
def __init__(self, preprocess_config, model_config):
super(FastSpeech2Loss, self).__init__()
self.pitch_feature_level = preprocess_config["preprocessing"]["pitch"][
"feature"
]
... | 3,354 | 35.075269 | 85 | py |
FastSpeech2 | FastSpeech2-master/model/fastspeech2.py | import os
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformer import Encoder, Decoder, PostNet
from .modules import VarianceAdaptor
from utils.tools import get_mask_from_lengths
class FastSpeech2(nn.Module):
""" FastSpeech2 """
def __init__(self, preprocess_confi... | 2,914 | 25.5 | 83 | py |
FastSpeech2 | FastSpeech2-master/model/optimizer.py | import torch
import numpy as np
class ScheduledOptim:
""" A simple wrapper class for learning rate scheduling """
def __init__(self, model, train_config, model_config, current_step):
self._optimizer = torch.optim.Adam(
model.parameters(),
betas=train_config["optimizer"]["beta... | 1,677 | 31.269231 | 84 | py |
FastSpeech2 | FastSpeech2-master/transformer/Layers.py | from collections import OrderedDict
import torch
import torch.nn as nn
import numpy as np
from torch.nn import functional as F
from .SubLayers import MultiHeadAttention, PositionwiseFeedForward
class FFTBlock(torch.nn.Module):
"""FFT Block"""
def __init__(self, d_model, n_head, d_k, d_v, d_inner, kernel_si... | 4,026 | 28.181159 | 86 | py |
FastSpeech2 | FastSpeech2-master/transformer/SubLayers.py | import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from .Modules import ScaledDotProductAttention
class MultiHeadAttention(nn.Module):
""" Multi-Head Attention module """
def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):
super().__init__()
self.n_head = n_hea... | 2,795 | 28.744681 | 86 | py |
FastSpeech2 | FastSpeech2-master/transformer/Modules.py | import torch
import torch.nn as nn
import numpy as np
class ScaledDotProductAttention(nn.Module):
""" Scaled Dot-Product Attention """
def __init__(self, temperature):
super().__init__()
self.temperature = temperature
self.softmax = nn.Softmax(dim=2)
def forward(self, q, k, v, ma... | 598 | 22.038462 | 50 | py |
FastSpeech2 | FastSpeech2-master/transformer/Models.py | import torch
import torch.nn as nn
import numpy as np
import transformer.Constants as Constants
from .Layers import FFTBlock
from text.symbols import symbols
def get_sinusoid_encoding_table(n_position, d_hid, padding_idx=None):
""" Sinusoid position encoding table """
def cal_angle(position, hid_idx):
... | 5,820 | 32.843023 | 84 | py |
hyper-task-descriptions | hyper-task-descriptions-main/hyper_task_descriptions/utils.py | # Copyright 2022 Google.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | 4,398 | 34.192 | 123 | py |
hyper-task-descriptions | hyper-task-descriptions-main/hyper_task_descriptions/common/testing.py | import logging
import os
import shutil
import tempfile
from pathlib import Path
import jax
class HyperTaskDescriptionsTestCase:
"""
A custom testing class that
* disables some of the more verbose logging,
* creates and destroys a temp directory as a test fixture
"""
PROJECT_ROOT = (Path(__f... | 4,032 | 25.886667 | 98 | py |
hyper-task-descriptions | hyper-task-descriptions-main/hyper_task_descriptions/python_scripts/poking_the_bear.py | """
Export the roberta model from the hypernetwork into a roberta huggingface model.
"""
# flake8: noqa
import argparse
import jax
from jax import numpy as jnp
from t5x import checkpoints
from transformers import AutoTokenizer, FlaxT5EncoderModel, T5EncoderModel
def extract_roberta_model(t5x_checkpoint_path, flax_du... | 2,315 | 32.565217 | 93 | py |
hyper-task-descriptions | hyper-task-descriptions-main/hyper_task_descriptions/python_scripts/fixed_roberta.py | """
I want to use a roberta encoder, but t5x needs internal parameters to be divisible by 2/4/8.
This messes with the token type and word embeddings, which are not even.
This script just fixes these things and then uploads to huggingface.
"""
from transformers import FlaxRobertaModel, RobertaModel
model = RobertaModel... | 1,609 | 37.333333 | 106 | py |
hyper-task-descriptions | hyper-task-descriptions-main/hyper_task_descriptions/python_scripts/interactive.py | import jax.numpy as jnp
import numpy as np
import optax
from flax import traverse_util
from t5x import optimizers, partitioning, utils
from hyper_task_descriptions import learning_rate_adafactor
from hyper_task_descriptions import utils as hyper_utils
from hyper_task_descriptions.hf_vocab import HuggingfaceVocabulary
... | 4,947 | 29.355828 | 100 | py |
hyper-task-descriptions | hyper-task-descriptions-main/hyper_task_descriptions/modeling/losses.py | from typing import Optional, Tuple, Union
import jax
import jax.numpy as jnp
def cosine_similarity_loss(
pred_vectors: jnp.ndarray,
target_vectors: jnp.ndarray,
ground_truth_similarity: jnp.ndarray,
) -> jnp.ndarray:
cosine_sim = jax.vmap(cosine_similarity_one_to_many, in_axes=[0, None])(
pre... | 3,540 | 39.701149 | 100 | py |
hyper-task-descriptions | hyper-task-descriptions-main/hyper_task_descriptions/modeling/hyper_interactive_model.py | # type: ignore
"""
Some changes to the t5x interactive model for dual-input setup.
"""
import functools
import inspect
import logging
from collections.abc import Iterator, Mapping, Sequence
from typing import Any, Callable, Tuple, Union
import clu.data.dataset_iterator
import jax
import seqio
import tensorflow as tf
f... | 13,200 | 42.567657 | 96 | py |
hyper-task-descriptions | hyper-task-descriptions-main/hyper_task_descriptions/modeling/lora.py | import functools
from typing import Any, Iterable, Optional, Tuple, Union
import jax
import jax.numpy as jnp
import numpy as np
from flax import linen as nn
from flax.linen import partitioning as nn_partitioning
from jax import lax
from t5x.examples.t5.layers import (
DenseGeneral,
_canonicalize_tuple,
_no... | 24,776 | 36.769817 | 100 | py |
hyper-task-descriptions | hyper-task-descriptions-main/hyper_task_descriptions/modeling/hyper_network.py | # Copyright 2022 The T5X Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | 51,138 | 39.394155 | 100 | py |
hyper-task-descriptions | hyper-task-descriptions-main/hyper_task_descriptions/modeling/layers.py | # Copyright 2022 The T5X Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | 16,568 | 42.488189 | 106 | py |
hyper-task-descriptions | hyper-task-descriptions-main/hyper_task_descriptions/modeling/hyper_transformer.py | """
Define wrapper class for three-input model.
Required so we can have different underlying encoder and hypernet inputs.
This is adapted from the EncoderDecoderModel class in t5x.
"""
import functools
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Mapping,
MutableMapping,
Optional... | 34,766 | 42.732075 | 115 | py |
hyper-task-descriptions | hyper-task-descriptions-main/tests/modeling/losses_test.py | import jax.numpy as jnp
from hyper_task_descriptions.modeling.losses import ( # safe_norm,
cosine_similarity,
cosine_similarity_loss,
cosine_similarity_one_to_many,
)
def test_cosine_similarity():
preds = jnp.array([1, 2, 3])
targets = jnp.array([1, 2, 3])
assert jnp.allclose(cosine_similar... | 1,340 | 28.8 | 98 | py |
hyper-task-descriptions | hyper-task-descriptions-main/tests/modeling/hyper_transformer_test.py | import functools
from unittest import mock
import flax
import jax
import jax.numpy as jnp
import numpy as np
import pytest
import tensorflow as tf
from absl.testing import parameterized
from flax import traverse_util
from seqio.test_utils import assert_dataset, create_default_dataset
from t5x import decoding
from hyp... | 38,114 | 42.3125 | 106 | py |
hyper-task-descriptions | hyper-task-descriptions-main/tests/modeling/layers_test.py | import dataclasses
import flax.linen as nn
import jax.numpy as jnp
import numpy as np
import pytest
from flax.core import freeze
from jax import random
from hyper_task_descriptions.modeling import layers
# from t5x.examples.t5.layers import MultiHeadDotProductAttention
def test_simple_linear():
module = layers... | 5,054 | 31.612903 | 95 | py |
hyper-task-descriptions | hyper-task-descriptions-main/tests/modeling/lora_network_test.py | import jax
import jax.numpy as jnp
import numpy as np
from absl.testing import parameterized
from t5x.examples.t5 import layers
from t5x.examples.t5.network import T5Config, Transformer
from hyper_task_descriptions.common.testing import (
get_test_model,
get_vanilla_test_model,
)
from hyper_task_descriptions.m... | 15,361 | 36.930864 | 97 | py |
hyper-task-descriptions | hyper-task-descriptions-main/tests/modeling/hyper_network_test.py | import jax
import numpy as np
from absl.testing import parameterized
from hyper_task_descriptions.common.testing import get_test_model
class NetworkTest(parameterized.TestCase):
def setUp(self):
super().setUp()
batch_size, max_decode_len, input_len, hyper_input_len = 2, 3, 4, 5
self.input... | 2,451 | 42.785714 | 97 | py |
hyper-task-descriptions | hyper-task-descriptions-main/tests/modeling/lora_test.py | import jax
import jax.numpy as jnp
import numpy as np
from t5x.examples.t5.layers import DenseGeneral, MultiHeadDotProductAttention
from hyper_task_descriptions.common.testing import get_prng_key
from hyper_task_descriptions.modeling.lora import (
LoraDenseGeneral,
LoraMultiHeadDotProductAttentionWithPrefix,
... | 6,487 | 34.07027 | 89 | py |
TIRE | TIRE-master/main.py | import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Lambda, Input, Dense
from tensorflow.keras.models import Model
import numpy as np
import random
import matplotlib.pyplot as plt
from scipy.signal import find_peaks, peak_prominences
import... | 1,988 | 30.571429 | 122 | py |
TIRE | TIRE-master/simulate.py | import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Lambda, Input, Dense
from tensorflow.keras.models import Model
import numpy as np
import random
import matplotlib.pyplot as plt
from scipy.signal import find_peaks, peak_prominences
import... | 5,334 | 38.518519 | 134 | py |
TIRE | TIRE-master/utils.py | import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Lambda, Input, Dense
from tensorflow.keras.models import Model
import numpy as np
import random
import matplotlib.pyplot as plt
from scipy.signal import find_peaks, peak_prominences
import... | 12,190 | 30.664935 | 131 | py |
TIRE | TIRE-master/TIRE.py | import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Lambda, Input, Dense
from tensorflow.keras.models import Model
import numpy as np
import random
import matplotlib.pyplot as plt
from scipy.signal import find_peaks, peak_prominences
import... | 7,089 | 34.808081 | 134 | py |
RLCT | RLCT-master/main.py | from __future__ import print_function
# from plotly.subplots import make_subplots
# import plotly.graph_objects as go
import os
import argparse
import random
# from sklearn.manifold import TSNE
# import seaborn as sns
import pandas as pd
from random import randint
import scipy.stats as st
import pickle
import math
imp... | 18,142 | 39.679372 | 189 | py |
RLCT | RLCT-master/ensembling_sgd.py | import argparse
import numpy as np
import os
from numpy.linalg import inv
import torch
import torch.nn as nn
from torch.utils.data import TensorDataset
import torch.optim as optim
from torch.distributions.multivariate_normal import MultivariateNormal
from torch.distributions.uniform import Uniform
from torch.distribut... | 12,745 | 41.345515 | 175 | py |
RLCT | RLCT-master/visualization.py | import torch
import numpy as np
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import os
import argparse
import random
# from sklearn.manifold import TSNE
# import seaborn as sns
import pandas as pd
from random import randint
import scipy.stats as st
import pickle
import math
import loggin... | 4,132 | 36.572727 | 190 | py |
RLCT | RLCT-master/dataset_factory.py | from __future__ import print_function
import torch
import torch.nn as nn
#from torchvision import datasets, transforms
from sklearn.datasets import load_iris, load_breast_cancer
from sklearn.model_selection import train_test_split
from torch.utils.data import TensorDataset, SubsetRandomSampler
from torch import Tensor
... | 9,456 | 47.25 | 163 | py |
RLCT | RLCT-master/mcmc_helper.py | import torch
import argparse
import time
import numpy as np
import pickle
import os
import pyro
import pyro.distributions as dist
from pyro.infer import HMC, MCMC, NUTS
# corresponds to pyro_tanh in models.py
def expected_nll_posterior_tanh(samples, args, X, Y):
nll = []
for r in range(args.num_samples):
... | 1,818 | 29.316667 | 90 | py |
RLCT | RLCT-master/RLCT_helper.py | from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from sklearn.linear_model import ElasticNet
from matplotlib import pyplot as plt
from statsmodels.regression.linear_model import OLS
from statsmodels.tools.tool... | 15,143 | 42.022727 | 154 | py |
RLCT | RLCT-master/utils.py | ##########################################################################
#
# Courtesy of Felix Dangel: https://github.com/f-dangel/backpack
#
##########################################################################
"""Exact computation of full Hessian using autodiff."""
from torch import cat, zeros, stack
from t... | 2,552 | 30.9125 | 74 | py |
RLCT | RLCT-master/implicit_vi.py | from __future__ import print_function
import torch.optim as optim
import copy
import itertools
from RLCT_helper import *
class Discriminator(nn.Module):
"""
input layer dim = w_dim, output layer dim = 1
first layer Linear(w_dim, n_hidden_D) followed by ReLU
num_hidden_layers_D of Linear(n_hidden_D, ... | 12,918 | 48.121673 | 201 | py |
RLCT | RLCT-master/langevin_monte_carlo.py | # implements variations of Langevin Monte Carlo
# Mandt: uses optimal constant stepsize with preconditioning for Gaussian-assumed posterior
# Simsekli: FLA uses symmetric alpha stable noise, can recover multimodal posterior more easily
import os
import numpy as np
from numpy.linalg import inv
import argparse
import co... | 24,437 | 38.736585 | 218 | py |
RLCT | RLCT-master/pyro_example.py | # code is from this mish-mash
# http://pyro.ai/numpyro/bnn.html
# http://docs.pyro.ai/en/stable/mcmc.html
import torch
import argparse
import time
import numpy as np
import pickle
import os
import pyro
import pyro.distributions as dist
from pyro.infer import HMC, MCMC, NUTS
# the non-linearity we use in our neural ... | 5,346 | 33.720779 | 144 | py |
RLCT | RLCT-master/models.py | import torch.nn as nn
import torch
import torch.nn.functional as F
import pyro
import pyro.distributions as dist
import pyro.poutine as poutine
from torch.distributions import transforms
import numpy as np
from torch.distributions.transformed_distribution import TransformedDistribution
from torch.distributions.trans... | 4,796 | 31.856164 | 114 | py |
RLCT | RLCT-master/ensembling_fisher_scoring.py | # wiseodd/natural-gradients
import torch.nn.functional as F
import numpy as np
from numpy.linalg import inv
import torch
import torch.nn as nn
from torch.utils.data import TensorDataset
from torch.distributions.multivariate_normal import MultivariateNormal
from torch.distributions.normal import Normal
from torch.dis... | 6,567 | 31.84 | 111 | py |
RLCT | RLCT-master/lastlayerbayesian.py | # wiseodd/last_layer_laplace
import matplotlib
matplotlib.use("Agg")
from torch.distributions.multivariate_normal import MultivariateNormal
import seaborn as sns
sns.set_style('white')
from torch.utils.data import TensorDataset
from main import *
from utils import exact_hessian
plt = matplotlib.pyplot
plt.rcParams... | 16,966 | 38.275463 | 230 | py |
RLCT | RLCT-master/visualize.py | import torch
from statsmodels.regression.linear_model import OLS
from statsmodels.tools.tools import add_constant
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
def main(results_path, taskid, savepath):
# load simulation resutls
args = torch.load('{}_taskid{... | 2,983 | 37.25641 | 110 | py |
RLCT | RLCT-master/explicit_vi.py | from __future__ import print_function
import torch.optim as optim
import copy
import pyvarinf
from RLCT_helper import *
def train_explicitVI(train_loader, valid_loader, args, mc, beta_index, verbose, saveimgpath):
# retrieve model
model, _ = retrieve_model(args)
# variationalize model
var_model_in... | 11,306 | 49.704036 | 165 | py |
RLCT | RLCT-master/pyvarinf/vi.py | # pylint: disable=too-many-arguments, too-many-locals
""" Variational inference """
import math
import functools
from collections import namedtuple
from collections import OrderedDict
from scipy.special import gammaln
import numpy as np
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.parameter ... | 15,598 | 37.516049 | 79 | py |
RLCT | RLCT-master/pyvarinf/ivi.py | # pylint: disable=too-many-arguments, too-many-locals
""" Variational inference """
import math
import functools
from collections import namedtuple
from collections import OrderedDict
from scipy.special import gammaln
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
from torch.autograd import Va... | 16,312 | 37.203747 | 90 | py |
RLCT | RLCT-master/pyvarinf/tests/test_var.py | # pylint:disable=no-self-use
""" Test suite pyvarinf """
from unittest import TestCase
import pyvarinf
import torch
import torch.nn as nn
from torch.autograd import Variable
class TestVar(TestCase):
""" Test suite for pyvarinf """
def test_var_lin(self):
""" Test linear model """
x = Variab... | 4,934 | 34.25 | 77 | py |
RLCT | RLCT-master/pyvarinf/tests/test_sample.py | from unittest import TestCase
import pyvarinf
import torch
import torch.nn as nn
from torch.autograd import Variable
class TestSample(TestCase):
def test_sample_diff(self):
x = Variable(torch.Tensor(1, 10).fill_(1))
model = nn.Linear(10, 10)
var_model = pyvarinf.Variationalize(model)
... | 634 | 27.863636 | 60 | py |
RLCT | RLCT-master/attic/main_ivi.py | from __future__ import print_function
import argparse
import pyvarinf
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
# Training settings
parser = argparse.ArgumentParser(description='PyTorc... | 6,025 | 37.382166 | 120 | py |
RLCT | RLCT-master/attic/main_ming.py | from __future__ import print_function
import os
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.optim.lr_scheduler import ReduceLROnPlateau
import numpy as np
from joblib import Parallel, delayed
import random
... | 51,918 | 45.943038 | 270 | py |
RLCT | RLCT-master/attic/main_pyvarinf.py | from __future__ import print_function
import argparse
import pyvarinf
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
# Training settings
parser = argparse.ArgumentParser(description='PyTorc... | 5,622 | 37.77931 | 120 | py |
RLCT | RLCT-master/ATTIC/main_ivi.py | from __future__ import print_function
import argparse
import pyvarinf
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
# Training settings
parser = argparse.ArgumentParser(description='PyTorc... | 6,025 | 37.382166 | 120 | py |
RLCT | RLCT-master/ATTIC/main_ming.py | from __future__ import print_function
import os
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.optim.lr_scheduler import ReduceLROnPlateau
import numpy as np
from joblib import Parallel, delayed
import random
... | 51,918 | 45.943038 | 270 | py |
RLCT | RLCT-master/ATTIC/main_pyvarinf.py | from __future__ import print_function
import argparse
import pyvarinf
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
# Training settings
parser = argparse.ArgumentParser(description='PyTorc... | 5,622 | 37.77931 | 120 | py |
RLCT | RLCT-master/notebooks/mcmc_symmetry_pyro.py | # code is from this mish-mash
# http://pyro.ai/numpyro/bnn.html
# http://docs.pyro.ai/en/stable/mcmc.html
import torch
import argparse
import time
import numpy as np
import pickle
import os
import math
import torch.multiprocessing
from torch.multiprocessing import Process, Manager
from functools import partial
import... | 9,356 | 35.127413 | 133 | py |
RLCT | RLCT-master/notebooks/generalization_ffrelu.py | #!/usr/bin/env python
# coding: utf-8
# # Generalisation error
#
# In this experiment we vary the architecture of a feedforward ReLU network
# and examine the (average) Bayesian generalization error as a function over the architecture.
#
# We estimate the (average) Bayesian generalisation error as
# \begin{equation}... | 6,097 | 29.954315 | 184 | py |
RLCT | RLCT-master/notebooks/mcmc_symmetry_sample.py | # The NUTS code here is modified from https://adamhaber.github.io/post/nuts/ with thanks!
import argparse
import os
import pickle
import math
import time
from datetime import datetime
from functools import partial
import collections
import numpy as np
import ray
#TraceReturns = collections.namedtuple('TraceReturns', ... | 15,380 | 43.973684 | 166 | py |
RLCT | RLCT-master/notebooks/generalization_reducedrank.py | # The setup here is similar to Table 8.1 in Watanabe textbook. I don't use his prior for A and B however. He also never specifies how he chose A_0 and B_0
from __future__ import print_function
from torch.distributions.uniform import Uniform
from torch.distributions.normal import Normal
from torch.distributions.multiv... | 4,331 | 27.88 | 154 | py |
SAN | SAN-main/main.py | import os
import pandas as pd
import numpy as np
import torch
import torch.optim as optim
import torch.utils.data as Data
import torch.nn.functional as F
import argparse
from utils import get_score_from_all_slices
from model import UNet, EMA
from loss import get_loss
from data import train_data_generator, val_data_gen... | 9,384 | 39.106838 | 135 | py |
SAN | SAN-main/loss.py | import torch
import torch.nn as nn
class get_loss(nn.Module):
def __init__(self):
super(get_loss, self).__init__()
self.epsilon = 1e-5
def forward(self, predict, target):
intersection = torch.sum(predict * target) # 利用预测值与标签相乘当作交集
union = torch.sum(predict + target)
d... | 413 | 22 | 78 | py |
SAN | SAN-main/utils.py | import numpy as np
import torch
def get_score_for_one_patient(labels, predicts, threshold=0.5):
'''
:param truths: [184, 1, 224, 192]
:param predicts: [184, 1, 224, 192]
:param threshold: threshold for computing dice score
:return: score of this patient
'''
if labels.size(0) != 184 or pred... | 2,917 | 31.065934 | 105 | py |
SAN | SAN-main/model.py | import torch
from torch import nn
import torch.nn.functional as F
class Adaptive_Normalization(nn.Module):
def __init__(self):
super(Adaptive_Normalization, self).__init__()
self.head = nn.Sequential(
conv_bn_relu(in_channels=1, out_channels=1),
nn.MaxPool2d(2),
... | 5,800 | 29.856383 | 108 | py |
DCN-T | DCN-T-main/test_gpu.py | import os
import time
import logging
import argparse
from torch.utils.data import DataLoader
import cv2
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
import torch.nn.parallel
import torch.utils.data
import torchvision.transforms.functional as T
from utils.path_util... | 14,638 | 33.607565 | 153 | py |
DCN-T | DCN-T-main/train_memory.py | import os
import argparse
import time
import apex
import logging
import torch
import time
import numpy as np
import torch.nn as nn
from tqdm import tqdm
import torch.multiprocessing
import torch.distributed as dist
from models.sync_batchnorm.replicate import patch_replication_callback
from utils.lr_scheduler import LR_... | 18,901 | 36.503968 | 162 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.