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 |
|---|---|---|---|---|---|---|
torch-adaptive-imle | torch-adaptive-imle-main/tests/nri/test_mst.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import torch
from torch import Tensor
import numpy as np
from nri.utils import maybe_make_logits_symmetric, map_estimator
from imle.aimle import aimle
from imle.ste import ste
from imle.target import TargetDistribution, AdaptiveTargetDistribution
... | 2,602 | 25.561224 | 106 | py |
torch-adaptive-imle | torch-adaptive-imle-main/imle/target.py | # -*- coding: utf-8 -*-
import torch
from torch import Tensor
from abc import ABC, abstractmethod
from typing import Optional
import logging
logger = logging.getLogger(__name__)
class BaseTargetDistribution(ABC):
def __init__(self):
super().__init__()
@abstractmethod
def params(self,
... | 5,674 | 35.612903 | 113 | py |
torch-adaptive-imle | torch-adaptive-imle-main/imle/aimle.py | # -*- coding: utf-8 -*-
import functools
import torch
from torch import Tensor
from imle.noise import BaseNoiseDistribution
from imle.target import BaseTargetDistribution, TargetDistribution
from typing import Callable, Optional
import logging
logger = logging.getLogger(__name__)
def aimle(function: Optional[Ca... | 9,870 | 45.126168 | 125 | py |
torch-adaptive-imle | torch-adaptive-imle-main/imle/sfe.py | # -*- coding: utf-8 -*-
import functools
import torch
from torch import Tensor
from imle.noise import BaseNoiseDistribution
from typing import Optional, Callable
import logging
logger = logging.getLogger(__name__)
def sfe(function: Optional[Callable[[Tensor], Tensor]] = None,
noise_distribution: Optiona... | 1,712 | 27.55 | 101 | py |
torch-adaptive-imle | torch-adaptive-imle-main/imle/imle.py | # -*- coding: utf-8 -*-
import functools
import torch
from torch import Tensor
from imle.noise import BaseNoiseDistribution
from imle.target import BaseTargetDistribution, TargetDistribution
from typing import Optional, Callable
import logging
logger = logging.getLogger(__name__)
def imle(function: Optional[Cal... | 9,141 | 43.595122 | 125 | py |
torch-adaptive-imle | torch-adaptive-imle-main/imle/noise.py | # -*- coding: utf-8 -*-
import math
import torch
from torch import Tensor, Size
from torch.distributions.gamma import Gamma
from torch.distributions.gumbel import Gumbel
from abc import ABC, abstractmethod
from typing import Optional
import logging
logger = logging.getLogger(__name__)
class BaseNoiseDistributio... | 2,899 | 31.954545 | 109 | py |
torch-adaptive-imle | torch-adaptive-imle-main/imle/solvers.py | # -*- coding: utf-8 -*-
import torch
from torch import Tensor
import logging
logger = logging.getLogger(__name__)
def select_k(logits: Tensor, k: int) -> Tensor:
scores, indices = torch.topk(logits, k, sorted=True)
mask = torch.zeros_like(logits, device=logits.device).scatter_(-1, indices, 1.0)
return ... | 517 | 23.666667 | 84 | py |
torch-adaptive-imle | torch-adaptive-imle-main/imle/ste.py | # -*- coding: utf-8 -*-
import functools
import torch
from torch import Tensor
from imle.noise import BaseNoiseDistribution
from typing import Optional, Callable
import logging
logger = logging.getLogger(__name__)
def ste(function: Optional[Callable[[Tensor], Tensor]] = None,
noise_distribution: Optiona... | 4,385 | 34.95082 | 119 | py |
torch-adaptive-imle | torch-adaptive-imle-main/experiments/generate_nri_aimle_cmd.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
import os
import os.path
import sys
import logging
def cartesian_product(dicts):
return (dict(zip(dicts, x)) for x in itertools.product(*dicts.values()))
def summary(configuration):
res = configuration['ckp'].split('/')[-1] + '_' + str(config... | 7,054 | 38.413408 | 220 | py |
torch-adaptive-imle | torch-adaptive-imle-main/nri/modules.py | # MIT License
# Copyright (c) 2018 Ethan Fetaya, Thomas Kipf
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, mod... | 10,790 | 38.24 | 134 | py |
torch-adaptive-imle | torch-adaptive-imle-main/nri/utils.py | import time
import numpy as np
import torch
from torch import Tensor
from torch.utils.data.dataset import TensorDataset
from torch.utils.data import DataLoader
from nri.core.spanning_tree import sample_tree_from_logits
from nri.core.topk import sample_topk_from_logits
torch.set_printoptions(precision=32)
EPS = torc... | 15,055 | 40.136612 | 94 | py |
torch-adaptive-imle | torch-adaptive-imle-main/nri/core/topk.py | import torch
from torch.autograd import Function
import numpy as np
import numpy.random as npr
import scipy.special as spec
EPS = torch.finfo(torch.float32).tiny
INF = np.finfo(np.float32).max
def softtopk_forward_np(logits, k):
batchsize, n = logits.shape
messages = -INF * np.ones((batchsize, n, k + 1))
... | 6,197 | 37.02454 | 88 | py |
torch-adaptive-imle | torch-adaptive-imle-main/nri/core/spanning_tree.py | import time
from itertools import chain, combinations, permutations
import numpy as np
import torch
torch.set_printoptions(precision=32)
import cvxpy as cp
from cvxpylayers.torch import CvxpyLayer
from nri.core.kruskals.kruskals import get_tree
from nri.core.kruskals.kruskals import kruskals_pytorch_batched
EPS = t... | 8,903 | 37.051282 | 94 | py |
torch-adaptive-imle | torch-adaptive-imle-main/nri/core/edmonds/time_edmonds.py | import argparse
import time
import torch
from edmonds import edmonds_python, edmonds_cpp_pytorch
parser = argparse.ArgumentParser()
parser.add_argument("--n", type=int, default=4, help="Number of nodes.")
parser.add_argument("--batch_size", type=int, default=128, help="Batch size.")
parser.add_argument("--num_steps",... | 1,199 | 28.268293 | 78 | py |
torch-adaptive-imle | torch-adaptive-imle-main/nri/core/edmonds/edmonds.py | from functools import partial
import networkx as nx
import numpy as np
import torch
import edmonds_cpp
def edmonds_python(adjs, n):
"""
Gets the maximum spanning arborescence given weights of edges.
We assume the root is node (idx) 0.
Args:
adjs: shape (batch_size, n, n), where
a... | 2,430 | 30.571429 | 86 | py |
torch-adaptive-imle | torch-adaptive-imle-main/nri/core/edmonds/setup_edmonds.py | from setuptools import setup, Extension
from torch.utils import cpp_extension
setup(name='edmonds_cpp',
ext_modules=[cpp_extension.CppExtension('edmonds_cpp', ['chuliu_edmonds.cpp'])],
cmdclass={'build_ext': cpp_extension.BuildExtension}) | 251 | 41 | 86 | py |
torch-adaptive-imle | torch-adaptive-imle-main/nri/core/kruskals/time_kruskals.py | import argparse
import time
import torch
from kruskals import kruskals_pytorch, kruskals_pytorch_batched
from kruskals import kruskals_cpp_pytorch, kruskals_cpp_pytorch2
parser = argparse.ArgumentParser()
parser.add_argument("--n", type=int, default=30, help="Number of nodes.")
parser.add_argument("--batch_size", typ... | 2,393 | 34.205882 | 81 | py |
torch-adaptive-imle | torch-adaptive-imle-main/nri/core/kruskals/kruskals.py | from functools import partial
import numpy as np
import torch
def get_root_pytorch(parents, node):
# find path of objects leading to the root
path = [node]
root = parents[node]
while root != path[-1]:
path.append(root)
root = parents[root]
# compress the path and return
for ances... | 9,059 | 35.24 | 85 | py |
torch-adaptive-imle | torch-adaptive-imle-main/nri/core/kruskals/setup_kruskals.py | from setuptools import setup, Extension
from torch.utils import cpp_extension
setup(name="kruskals_cpp",
ext_modules=[cpp_extension.CppExtension("kruskals_cpp", ["kruskals.cpp"])],
cmdclass={"build_ext": cpp_extension.BuildExtension})
| 248 | 34.571429 | 81 | py |
IO-GEN | IO-GEN-master/test.py | import argparse
import os
import tensorflow as tf
import numpy as np
import tensorflow.keras as keras
from utils import load_of_data
from metrics import euclidean_distance_square_loss, smooth_accuracy, score
from sklearn.metrics import roc_curve, auc
# parse arguments
parser = argparse.ArgumentParser()
parser.add_a... | 5,494 | 46.37069 | 122 | py |
IO-GEN | IO-GEN-master/synthesize.py | import argparse
import os
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from utils import load_of_data
from models import build_DCAE, build_IO_GEN, build_classifier
from metrics import feat_matching_loss
# parse argu... | 2,854 | 32.197674 | 131 | py |
IO-GEN | IO-GEN-master/models.py | import tensorflow.keras as keras
import tensorflow.keras.layers as layers
from metrics import smooth_accuracy, feat_matching_loss
import numpy as np
def build_classifier(dsvdd):
filter_size = 3
n_filters_factor = 2
dsvdd.trainable = False
c_x = keras.Input(shape=dsvdd.input.shape[1:], name='c_x')
... | 5,430 | 35.206667 | 110 | py |
IO-GEN | IO-GEN-master/metrics.py | import tensorflow.keras as keras
import numpy as np
def smooth_accuracy(y_true, y_pred):
y_true = keras.backend.round(y_true)
y_pred = keras.backend.round(y_pred)
correct = keras.backend.cast(keras.backend.equal(y_true, y_pred), dtype='float32')
return keras.backend.mean(correct)
def feat_matching_l... | 889 | 27.709677 | 86 | py |
IO-GEN | IO-GEN-master/train.py | import argparse
import os
import tensorflow as tf
import numpy as np
import tensorflow.keras as keras
from utils import load_of_data
from models import build_DCAE, build_IO_GEN, build_classifier
from metrics import euclidean_distance_square_loss, smooth_accuracy, feat_matching_loss
# parse arguments
parser = argpars... | 10,210 | 38.731518 | 119 | py |
Multi-Fidelity-Deep-Active-Learning | Multi-Fidelity-Deep-Active-Learning-main/dmfdal_2f/train.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import yaml
from lib import utils
from model.pytorch.supervisor import Supervisor
import random
import numpy as np
import os
import pickle
def main(args):
with open(args.config_filename) ... | 4,267 | 36.769912 | 236 | py |
Multi-Fidelity-Deep-Active-Learning | Multi-Fidelity-Deep-Active-Learning-main/dmfdal_2f/model/pytorch/loss.py | import torch
import torch.nn as nn
from scipy.stats import multivariate_normal
import numpy as np
def nll_loss(pred_mu, pred_cov, y):
pred_std = torch.sqrt(pred_cov)
gaussian = torch.distributions.Normal(pred_mu, pred_std)
nll = -gaussian.log_prob(y)
nll = torch.mean(nll)
retu... | 1,747 | 33.27451 | 100 | py |
Multi-Fidelity-Deep-Active-Learning | Multi-Fidelity-Deep-Active-Learning-main/dmfdal_2f/model/pytorch/model.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# device = torch.device("cuda:5")
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
class MLP_Encoder(nn.Module):
def __init__(self,
in_dim,
out_di... | 11,573 | 43.860465 | 249 | py |
Multi-Fidelity-Deep-Active-Learning | Multi-Fidelity-Deep-Active-Learning-main/dmfdal_2f/model/pytorch/supervisor.py | import os
import time
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
from lib import utils
from model.pytorch.model import Model
from model.pytorch.loss import nll_loss
from model.pytorch.loss import nll_metric
from model.pytorch.loss import rmse_metric
# from model.pytorch.loss imp... | 38,096 | 43.453909 | 313 | py |
Multi-Fidelity-Deep-Active-Learning | Multi-Fidelity-Deep-Active-Learning-main/dmfdal_3f/train.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import yaml
from lib import utils
from model.pytorch.supervisor import Supervisor
import random
import numpy as np
import os
import pickle
def main(args):
with open(args.config_filename) ... | 4,347 | 38.171171 | 236 | py |
Multi-Fidelity-Deep-Active-Learning | Multi-Fidelity-Deep-Active-Learning-main/dmfdal_3f/model/pytorch/loss.py | import torch
import torch.nn as nn
from scipy.stats import multivariate_normal
import numpy as np
def nll_loss(pred_mu, pred_cov, y):
pred_std = torch.sqrt(pred_cov)
gaussian = torch.distributions.Normal(pred_mu, pred_std)
nll = -gaussian.log_prob(y)
nll = torch.mean(nll)
retu... | 1,747 | 33.27451 | 100 | py |
Multi-Fidelity-Deep-Active-Learning | Multi-Fidelity-Deep-Active-Learning-main/dmfdal_3f/model/pytorch/model.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# device = torch.device("cuda:5")
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
class MLP_Encoder(nn.Module):
def __init__(self,
in_dim,
out_di... | 13,303 | 47.202899 | 365 | py |
Multi-Fidelity-Deep-Active-Learning | Multi-Fidelity-Deep-Active-Learning-main/dmfdal_3f/model/pytorch/supervisor.py | import os
import time
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
from lib import utils
from model.pytorch.model import Model
from model.pytorch.loss import nll_loss
from model.pytorch.loss import nll_metric
from model.pytorch.loss import rmse_metric
# from model.pytorch.loss imp... | 44,457 | 45.748686 | 451 | py |
RCIG | RCIG-master/tinyimagenet.py | """
TF: https://github.com/ksachdeva/tiny-imagenet-tfds/blob/master/tiny_imagenet/_imagenet.py
PyTorch: https://gist.github.com/lromor/bcfc69dcf31b2f3244358aea10b7a11b
"""
import os
import tensorflow as tf
import tensorflow_datasets.public_api as tfds
_URL = "http://cs231n.stanford.edu/tiny-imagenet-200.zip"
_EXTRAC... | 7,513 | 46.859873 | 120 | py |
RCIG | RCIG-master/dataloader.py | #A lot of this code is reused from https://github.com/yongchao97/FRePo
from absl import logging
import os
import numpy as np
import jax.numpy as jnp
import tensorflow as tf
import tensorflow_datasets as tfds
from imagewoof import ImagewoofV2
from imagenette import ImagenetteV2
from tinyimagenet import TinyImagenetV2... | 8,694 | 42.914141 | 119 | py |
RCIG | RCIG-master/utils.py | import functools
import jax
import operator
import numpy as np
import jax.numpy as jnp
class bind(functools.partial):
"""
An improved version of partial which accepts Ellipsis (...) as a placeholder
"""
def __call__(self, *args, **keywords):
keywords = {**self.keywords, **keywords}
iarg... | 1,404 | 27.673469 | 120 | py |
RCIG | RCIG-master/imagenette.py | """Imagenette: a subset of 10 easily classified classes from Imagenet.
(tench, English springer, cassette player, chain saw, church, French horn,
garbage truck, gas pump, golf ball, parachute)
"""
import os
import tensorflow as tf
import tensorflow_datasets.public_api as tfds
_IMAGENETTE_URL = "https://s3.amazonaws... | 3,401 | 35.580645 | 112 | py |
RCIG | RCIG-master/eval.py | import sys
# sys.path.append("..")
import os
import fire
import ml_collections
from functools import partial
# from jax.config import config
# config.update("jax_enable_x64", True)
import jax
from absl import logging
import absl
import tensorflow as tf
tf.config.set_visible_devices([], 'GPU')
from dataloader imp... | 12,140 | 41.6 | 364 | py |
RCIG | RCIG-master/imagewoof.py | import os
import tensorflow as tf
import tensorflow_datasets.public_api as tfds
_IMAGEWOOF_URL = "https://s3.amazonaws.com/fast-ai-imageclas/imagewoof2-160.tgz"
_CITATION = """
@misc{imagewoof,
author = "Jeremy Howard",
title = "Imagewoof",
url = "https://github.com/fastai/imagenette/"
}
"""
_DESC... | 3,072 | 36.024096 | 116 | py |
RCIG | RCIG-master/models.py | #A lot of this code is reused from https://github.com/yongchao97/FRePo
from functools import partial
from typing import Any, Callable, Sequence, Tuple
from flax import linen as nn
import jax.numpy as jnp
import jax
import functools
ModuleDef = Any
class KIP_ConvNet(nn.Module):
depth: int = 3
width: int = 12... | 22,826 | 36.60626 | 144 | py |
RCIG | RCIG-master/ops.py | #A lot of this code is reused from https://github.com/yongchao97/FRePo
import tqdm
import functools
from absl import logging
import jax
import jax.numpy as jnp
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
def blockshaped(arr, h, w, c, nrows, ncols, is_tf=False):
"""
Return a... | 18,070 | 39.337054 | 122 | py |
RCIG | RCIG-master/algorithms.py | # import eqm_prop_crap
import torch
import jax
import jax.numpy as jnp
import numpy as np
from flax.training import train_state, checkpoints
import ml_collections
import flax.linen as nn
from typing import Any, Callable, Sequence, Tuple
import jax.scipy as jsp
import functools
import flax
import optax
import utils
im... | 53,189 | 50.242775 | 477 | py |
RCIG | RCIG-master/distill_dataset.py | import sys
# sys.path.append("..")
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import fire
import ml_collections
from functools import partial
# from jax.config import config
# config.update("jax_enable_x64", True)
import jax
from absl import logging
import absl
import tensorflow as tf
tf.config.set_visi... | 9,838 | 33.766784 | 332 | py |
RCIG | RCIG-master/augmax/base.py | # Copyright 2021 Konrad Heidler
#
# 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 wri... | 3,662 | 37.968085 | 143 | py |
RCIG | RCIG-master/augmax/export.py | import jax
from .geometric import RandomSizedCrop, Rotate, HorizontalFlip, RandomTranslate
from .imagelevel import NormalizedColorJitter, Cutout
def get_vmap_transform(transform, use_siamese=False):
if use_siamese:
vmap_transform = jax.vmap(transform, in_axes=[None, 0])
else:
transform = jax.... | 1,858 | 35.45098 | 116 | py |
RCIG | RCIG-master/augmax/geometric.py | # Copyright 2021 Konrad Heidler
#
# 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 wri... | 20,941 | 33.729685 | 118 | py |
RCIG | RCIG-master/augmax/utils.py | # Copyright 2021 Konrad Heidler
#
# 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 wri... | 3,946 | 35.546296 | 119 | py |
RCIG | RCIG-master/augmax/colorspace.py | # Copyright 2021 Konrad Heidler
#
# 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 wri... | 14,012 | 35.023136 | 118 | py |
RCIG | RCIG-master/augmax/imagelevel.py | # Copyright 2021 Konrad Heidler
#
# 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 wri... | 10,960 | 39.297794 | 119 | py |
RCIG | RCIG-master/augmax/functional/dropout.py | from typing import List, Tuple, Union, Iterable
from functools import wraps
import jax.numpy as jnp
import numpy as np
from jax import lax
__all__ = ["cutout", "channel_dropout"]
def preserve_shape(func):
"""
Preserve shape of the image
"""
@wraps(func)
def wrapped_function(img, *args, **kwargs... | 1,423 | 25.867925 | 120 | py |
RCIG | RCIG-master/augmax/functional/colorspace.py | import jax
import jax.numpy as jnp
def identity(value):
return value
def to_grayscale(pixel):
pixel = jnp.broadcast_to(pixel.mean(axis=-1, keepdims=True), pixel.shape)
return pixel
def adjust_brightness(value, brightness, invert=False):
# Invertible brightness transform
# Works for float image [0... | 1,260 | 28.325581 | 77 | py |
SOPE | SOPE-master/ope/base_policy_methods/beat_mountain_car.py | # from pyvirtualdisplay import Display
# display = Display(visible=0, size=(1000, 1000))
# display.start()
# import pdb; pdb.set_trace()
import os
import gym
import matplotlib
matplotlib.use('agg')
from envs.modified_mountain_car import ModifiedMountainCarEnv
import random
import numpy as np
import keras
from keras.mod... | 11,704 | 32.927536 | 149 | py |
SOPE | SOPE-master/ope/base_policy_methods/beat_mountain_car_pixel.py | from pyvirtualdisplay import Display
display = Display(visible=0, size=(1000, 1000))
display.start()
import pdb; pdb.set_trace()
import os
import gym
import matplotlib
matplotlib.use('agg')
from envs.modified_mountain_car import ModifiedMountainCarEnv
import random
import numpy as np
import keras
from keras.models ... | 14,209 | 32.200935 | 151 | py |
SOPE | SOPE-master/ope/models/approximate_model.py | import numpy as np
import scipy.signal as signal
import keras
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, MaxPool2D, concatenate, UpSampling2D, Reshape, Lambda, Conv2DTranspose
from keras.optimizers import Adam
from keras import backend as K
import tensorflow as tf
from ... | 26,700 | 45.598604 | 259 | py |
SOPE | SOPE-master/ope/models/conv.py | import torch
import torch.nn as nn
import numpy as np
class defaultCNN(nn.Module):
def __init__(self, shape, action_space_dim):
super(defaultCNN, self).__init__()
self.c, self.h, self.w = shape
self.net = nn.Sequential(
nn.Conv2d(self.c, 16, (2,2)),
nn.ELU(),
... | 2,714 | 32.9375 | 147 | py |
SOPE | SOPE-master/ope/algos/fqe.py | import sys
import numpy as np
import pandas as pd
from copy import deepcopy
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
import keras
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, MaxPool2D, concatenate, UpSampling2D, Reshape, Lambda
from k... | 28,849 | 48.655766 | 218 | py |
SOPE | SOPE-master/ope/algos/dm_regression.py |
import sys
import numpy as np
import pandas as pd
sys.path.append("..")
from copy import deepcopy
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
import keras
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, MaxPool2D, concatenate, UpSampling2D,... | 20,324 | 40.64959 | 218 | py |
SOPE | SOPE-master/ope/algos/infinite_horizon.py | import numpy as np
import tensorflow as tf
from time import sleep
import sys
import os
from tqdm import tqdm
from tensorflow.python import debug as tf_debug
import json
from scipy.optimize import linprog
from scipy.optimize import minimize
import quadprog
import keras
from keras.layers import Dense, Conv2D, Flatt... | 22,869 | 43.755382 | 167 | py |
SOPE | SOPE-master/ope/algos/retrace_lambda.py | import sys
import numpy as np
import pandas as pd
from copy import deepcopy
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
import keras
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, MaxPool2D, concatenate, UpSampling2D, Reshape, Lambda
from k... | 20,225 | 45.283753 | 262 | py |
SOPE | SOPE-master/ope/algos/approximate_model.py |
from ope.algos.direct_method import DirectMethodModelBased
import numpy as np
import scipy.signal as signal
from ope.utls.thread_safe import threadsafe_generator
import os
import time
from copy import deepcopy
from sklearn.linear_model import LinearRegression, LogisticRegression
from tqdm import tqdm
import torch
tor... | 21,915 | 41.55534 | 136 | py |
SOPE | SOPE-master/ope/algos/event_is.py | # Interpolation via n-step interpolation implemented.
import numpy as np
import tensorflow as tf
from time import sleep
import sys
import os
from tqdm import tqdm
from tensorflow.python import debug as tf_debug
import json
from scipy.optimize import linprog
from scipy.optimize import minimize
import quadprog
import... | 25,476 | 43.462478 | 188 | py |
SOPE | SOPE-master/ope/algos/more_robust_doubly_robust.py | import sys
import numpy as np
import pandas as pd
from copy import deepcopy
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
import keras
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, MaxPool2D, concatenate, UpSampling2D, Reshape, Lambda
from k... | 51,705 | 44.276708 | 370 | py |
SOPE | SOPE-master/ope/utls/agent.py | import gym
import random
import numpy as np
import tensorflow as tf
from skimage.color import rgb2gray
from skimage.transform import resize
from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.layers.convolutional import Conv2D
from keras import backend as K
EPISODES = 50000
class Te... | 1,674 | 29.454545 | 72 | py |
SOPE | SOPE-master/ope/utls/rollout.py |
from tqdm import tqdm
import numpy as np
import os
import json
import pandas as pd
from collections import Counter
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
import keras
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, MaxPool2D, concatena... | 23,124 | 44.882937 | 218 | py |
SOPE | SOPE-master/ope/experiment_tools/experiment.py | import json
import argparse
import matplotlib as mpl
import matplotlib.pyplot as plt
import scipy.signal as signal
import os
from skimage.transform import rescale, resize, downscale_local_mean
import json
from collections import OrderedDict, Counter
import tensorflow as tf
from keras.models import load_model, model_fro... | 23,553 | 47.86722 | 254 | py |
SafeNLP | SafeNLP-main/safety_score.py | """
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
This scripts mesaure the safety score for a given model
"""
import os
import sys
import json
import argparse
import logging
import torch
import math
import numpy as np
from scipy import stats
from tqdm import tqdm
from collections import def... | 5,568 | 36.884354 | 119 | py |
SafeNLP | SafeNLP-main/utils.py | """
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Utility fuctions
"""
import argparse
import torch
from transformers import AutoConfig, AutoModelForMaskedLM, AutoModelForCausalLM, AutoTokenizer
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--data', t... | 1,983 | 35.072727 | 98 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/test.py | """General-purpose test script for image-to-image translation.
Once you have trained your model with train.py, you can use this script to test the model.
It will load a saved model from --checkpoints_dir and save the results to --results_dir.
It first creates model and dataset given the option. It will hard-code some... | 3,935 | 54.43662 | 123 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/train.py | import time
import torch
from options.train_options import TrainOptions
from data import create_dataset
from models import create_model
from util.visualizer import Visualizer
if __name__ == '__main__':
opt = TrainOptions().parse() # get training options
dataset = create_dataset(opt) # create a dataset give... | 4,358 | 54.884615 | 186 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/options/base_options.py | import argparse
import os
from util import util
import torch
import models
import data
class BaseOptions():
"""This class defines options used during both training and test time.
It also implements several helper functions such as parsing, printing, and saving the options.
It also gathers additional opti... | 9,720 | 57.915152 | 287 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/models/base_model.py | import os
import torch
from collections import OrderedDict
from abc import ABC, abstractmethod
from . import networks
class BaseModel(ABC):
"""This class is an abstract base class (ABC) for models.
To create a subclass, you need to implement the following five functions:
-- <__init__>: ... | 11,223 | 42.335907 | 260 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/models/stylegan_networks.py | """
The network architectures is based on PyTorch implemenation of StyleGAN2Encoder.
Original PyTorch repo: https://github.com/rosinality/style-based-gan-pytorch
Origianl StyelGAN2 paper: https://github.com/NVlabs/stylegan2
We use the network architeture for our single-image traning setting.
"""
import math
import num... | 27,899 | 29.491803 | 137 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/models/patchnce.py | from packaging import version
import torch
from torch import nn
class PatchNCELoss(nn.Module):
def __init__(self, opt):
super().__init__()
self.opt = opt
self.cross_entropy_loss = torch.nn.CrossEntropyLoss(reduction='none')
self.mask_dtype = torch.uint8 if version.parse(torch.__ver... | 2,319 | 40.428571 | 114 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/models/cut_model.py | import numpy as np
import torch
from .base_model import BaseModel
from . import networks
from .patchnce import PatchNCELoss
import util.util as util
class CUTModel(BaseModel):
""" This class implements CUT and FastCUT model, described in the paper
Contrastive Learning for Unpaired Image-to-Image Translation
... | 10,226 | 46.567442 | 227 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/models/sincut_model.py | import torch
from .cut_model import CUTModel
class SinCUTModel(CUTModel):
""" This class implements the single image translation model (Fig 9) of
Contrastive Learning for Unpaired Image-to-Image Translation
Taesung Park, Alexei A. Efros, Richard Zhang, Jun-Yan Zhu
ECCV, 2020
"""
@staticmethod... | 3,168 | 38.6125 | 120 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/models/networks.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
import functools
from torch.optim import lr_scheduler
import numpy as np
from .stylegan_networks import StyleGAN2Discriminator, StyleGAN2Generator, TileStyleGAN2Discriminator
###################################################... | 60,634 | 42.187322 | 187 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/models/template_model.py | """Model class template
This module provides a template for users to implement custom models.
You can specify '--model template' to use this model.
The class name should be consistent with both the filename and its model option.
The filename should be <model>_dataset.py
The class name should be <Model>Dataset.py
It im... | 5,951 | 58.52 | 177 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/models/cycle_gan_model.py | import torch
import itertools
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
try:
from apex import amp
except ImportError as error:
print(error)
class CycleGANModel(BaseModel):
"""
This class implements the CycleGAN model, for learning image-to-image tra... | 11,700 | 51.470852 | 362 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/util/image_pool.py | import random
import torch
class ImagePool():
"""This class implements an image buffer that stores previously generated images.
This buffer enables us to update discriminators using a history of generated images
rather than the ones produced by the latest generators.
"""
def __init__(self, pool_... | 2,226 | 39.490909 | 140 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/util/util.py | """This module contains simple helper functions """
from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import os
import importlib
import argparse
from argparse import Namespace
import torchvision
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in... | 5,135 | 29.754491 | 145 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/data/base_dataset.py | """This module implements an abstract base class (ABC) 'BaseDataset' for datasets.
It also includes common transformation functions (e.g., get_transform, __scale_width), which can be later used in subclasses.
"""
import random
import numpy as np
import torch.utils.data as data
from PIL import Image
import torchvision.... | 8,026 | 33.748918 | 153 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/data/image_folder.py | """A modified image folder class
We modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py)
so that this class can load images from both current directory and its subdirectories.
"""
import torch.utils.data as data
from PIL import Image
import os
import... | 1,941 | 27.985075 | 122 | py |
contrastive-unpaired-translation | contrastive-unpaired-translation-master/data/__init__.py | """This package includes all the modules related to data loading and preprocessing
To add a custom dataset class called 'dummy', you need to add a file called 'dummy_dataset.py' and define a subclass 'DummyDataset' inherited from BaseDataset.
You need to implement four functions:
-- <__init__>: ... | 3,694 | 36.323232 | 176 | py |
MultilayerBlockModels | MultilayerBlockModels-main/code/run_experiment.py | import argparse
import json
import os
import time
from collections import defaultdict
import numpy as np
import pandas as pd
from model import fit_mlplbm
parser = argparse.ArgumentParser()
parser.add_argument(
'--input_file',
required=True,
help='Path to the input CSV file. '
'Each line of the file represe... | 3,647 | 20.209302 | 67 | py |
MultilayerBlockModels | MultilayerBlockModels-main/code/utils.py | import numpy as np
try:
import torch
except ModuleNotFoundError:
print('Torch backend unavailable (missing dependencies)')
from scipy.sparse import csr_matrix
MARGIN = 1e-10
def round_prob(C):
'''
Infers the most likely clusters from an array of soft cluster
assignments and returns them as a list of lists.
... | 2,083 | 16.965517 | 66 | py |
MultilayerBlockModels | MultilayerBlockModels-main/code/model.py | import time
import numpy as np
try:
import torch
from torch_sparse import transpose, spmm
except ModuleNotFoundError:
print('Torch backend unavailable (missing dependencies)')
from scipy.sparse import csr_matrix
from scipy.stats import entropy
from sklearn.base import BaseEstimator
from sklearn.preprocessing imp... | 28,746 | 24.040941 | 67 | py |
CentSmoothieCode | CentSmoothieCode-master/models/weightCentSmooth.py | import torch
import torch.nn.functional as F
import numpy as np
import params
from torch_scatter.scatter import scatter_add
class WHGNN(torch.nn.Module):
def __init__(self, featureSize, embeddingSize, nSe, nD, nLayer=params.N_LAYER, device=torch.device('cpu')):
super(WHGNN, self).__init__()
self.... | 10,465 | 33.541254 | 122 | py |
CentSmoothieCode | CentSmoothieCode-master/models/trainWeightCentL.py | from models.weightCentSmooth import WHGNN
import torch
import numpy as np
import inspect
import params
from sklearn.metrics import roc_auc_score, average_precision_score, f1_score
from utils import utils
import time
def getMSE(a1, a2):
v = a1 - a2
v = np.multiply(v, v)
return np.sqrt(np.sum(v) / (v.shape... | 14,080 | 35.669271 | 117 | py |
CentSmoothieCode | CentSmoothieCode-master/models/runner.py | from utils import utils
from utils.logger.logger2 import MyLogger
from models.trainWeightCentL import WrapperWeightCentSmooth
from dataFactory.datawrapper import Wrapper
import params
import numpy as np
import random
import torch
class Runner:
def __init__(self):
resetRandomSeed()
self.data = N... | 3,053 | 28.085714 | 113 | py |
CentSmoothieCode | CentSmoothieCode-master/dataFactory/MoleculeFactory2.py | from torch_geometric.data import Data, Batch
from utils import utils
import torch
import numpy as np
import params
class ModeculeFactory2:
def __init__(self):
self.__atomElement2Id = dict()
self.moleculeList = list()
self.smile2Graph = utils.load_obj(params.SMILE2GRAPH)
def getAtomIdF... | 2,971 | 30.284211 | 91 | py |
CentSmoothieCode | CentSmoothieCode-master/dataFactory/datawrapper.py | import numpy as np
from utils import utils
import params
import torch
class Wrapper:
def __init__(self):
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
pass
def loadData(self, iFold):
self.iFold = iFold
print("Loading iFold: ", iFold)
folder... | 2,376 | 28.345679 | 83 | py |
CentSmoothieCode | CentSmoothieCode-master/dataFactory/polyADR.py | import params
from utils import utils
import random
import copy
from dataFactory import loadingMap, MoleculeFactory2
from dataFactory.lh import *
from multiprocessing import Process, Value, Queue
from dataFactory.realData import RealData, RealFoldData
import time
import numpy as np
import torch
def loadPubChem():
... | 17,613 | 28.753378 | 130 | py |
nnsvs | nnsvs-master/setup.py | from importlib.machinery import SourceFileLoader
from os.path import exists
from setuptools import find_packages, setup
version = SourceFileLoader("nnsvs.version", "nnsvs/version.py").load_module().version
packages = find_packages()
if exists("README.md"):
with open("README.md", "r", encoding="UTF-8") as fh:
... | 2,891 | 30.096774 | 86 | py |
nnsvs | nnsvs-master/recipes/_common/clean_checkpoint_state.py | import argparse
import os
import sys
import torch
def get_parser():
parser = argparse.ArgumentParser(
description="Clean checkpoint state and make a new checkpoint",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("input_file", type=str, help="input file")
... | 1,284 | 31.125 | 78 | py |
nnsvs | nnsvs-master/tests/test_wavenet.py | import torch
from nnsvs.wavenet import WaveNet
def test_wavenet():
x = torch.rand(16, 200, 206)
c = torch.rand(16, 200, 300)
model = WaveNet(in_dim=300, out_dim=206, layers=2)
y = model(c, x)
assert y.shape == x.shape
model.eval()
for T in [10, 20, x.shape[1]]:
y = model.inferen... | 383 | 20.333333 | 54 | py |
nnsvs | nnsvs-master/tests/test_diffusion.py | import pytest
import torch
from nnsvs.base import PredictionType
from nnsvs.diffsinger.denoiser import DiffNet
from nnsvs.diffsinger.diffusion import GaussianDiffusion
from nnsvs.diffsinger.fs2 import FFTBlocks, FFTBlocksEncoder
from nnsvs.model import LSTMEncoder
from nnsvs.util import init_seed
from .util import _te... | 3,725 | 26.80597 | 66 | py |
nnsvs | nnsvs-master/tests/test_postfilters.py | import pytest
import torch
from nnsvs.postfilters import Conv2dPostFilter, MovingAverage1d, MultistreamPostFilter
from nnsvs.util import init_seed
def _test_model_impl(model, in_dim):
B = 4
T = 100
init_seed(B * T)
x = torch.rand(B, T, in_dim)
lengths = torch.Tensor([T] * B).long()
# warmup f... | 2,290 | 27.283951 | 86 | py |
nnsvs | nnsvs-master/tests/test_compat.py | from os.path import dirname, join
import hydra
import torch
from nnsvs.model import MDN
from omegaconf import OmegaConf
# https://github.com/r9y9/nnsvs/pull/114#issuecomment-1156631058
def test_mdn_compat():
config = OmegaConf.load(join(dirname(__file__), "data", "mdn_test.yaml"))
model = hydra.utils.instant... | 501 | 30.375 | 77 | py |
nnsvs | nnsvs-master/tests/test_mdn.py | import unittest
import numpy as np
import torch
import torch.optim as optim
from nnsvs import mdn
from nnsvs.util import init_seed
from torch import nn
class MDN(nn.Module):
def __init__(self, in_dim, hidden_dim, out_dim, num_layers=1, num_gaussians=30):
super(MDN, self).__init__()
self.first_lin... | 4,301 | 31.590909 | 91 | py |
nnsvs | nnsvs-master/tests/util.py | import torch
from nnsvs.base import PredictionType
from nnsvs.util import init_seed
def _test_model_impl(model, in_dim, out_dim):
B = 4
T = 100
init_seed(B * T)
x = torch.rand(B, T, in_dim)
y = torch.rand(B, T, out_dim)
lengths = torch.Tensor([T] * B).long()
# warmup forward pass
with... | 1,647 | 32.632653 | 68 | py |
nnsvs | nnsvs-master/tests/test_discriminators.py | import pytest
import torch
from nnsvs.discriminators import Conv2dD
from nnsvs.util import init_seed
def _test_model_impl(model, in_dim):
B = 4
T = 100
init_seed(B * T)
x = torch.rand(B, T, in_dim)
lengths = torch.Tensor([T] * B).long()
# warmup forward pass
with torch.no_grad():
... | 923 | 24.666667 | 74 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.