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 |
|---|---|---|---|---|---|---|
UNIT | UNIT-master/trainer.py | """
Copyright (C) 2017 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
from networks import AdaINGen, MsImageDis, VAEGen
from utils import weights_init, get_model_list, vgg_preprocess, load_vgg16, get_scheduler
from ... | 19,914 | 51.133508 | 117 | py |
pytorch-mask-rcnn | pytorch-mask-rcnn-master/convert_from_keras.py | import argparse
import collections
import h5py
import torch
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
parser = argparse.ArgumentParser(description='Convert keras-mask-rcnn model to pytorch-mask-rcnn model')
parser.add_... | 4,860 | 43.190909 | 141 | py |
pytorch-mask-rcnn | pytorch-mask-rcnn-master/utils.py | """
Mask R-CNN
Common utility functions and classes.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
"""
import sys
import os
import math
import random
import numpy as np
import scipy.misc
import scipy.ndimage
import skimage.color
import skimage.i... | 16,796 | 35.278618 | 91 | py |
pytorch-mask-rcnn | pytorch-mask-rcnn-master/model.py | """
Mask R-CNN
The main Mask R-CNN model implemenetation.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
"""
import datetime
import math
import os
import random
import re
import numpy as np
import torch
import torch.nn as nn
import torch.nn.func... | 86,552 | 39.711665 | 254 | py |
pytorch-mask-rcnn | pytorch-mask-rcnn-master/demo.py | import os
import sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
import coco
import utils
import model as modellib
import visualize
import torch
# Root directory of the project
ROOT_DIR = os.getcwd()
# Directory to save logs and trained model
MOD... | 2,767 | 33.6 | 78 | py |
pytorch-mask-rcnn | pytorch-mask-rcnn-master/coco.py | """
Mask R-CNN
Configurations and data loading code for MS COCO.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
------------------------------------------------------------
Usage: import the module (see Jupyter notebooks for examples), or run fr... | 20,937 | 38.73055 | 124 | py |
pytorch-mask-rcnn | pytorch-mask-rcnn-master/roialign/roi_align/roi_align.py | import torch
from torch import nn
from .crop_and_resize import CropAndResizeFunction, CropAndResize
class RoIAlign(nn.Module):
def __init__(self, crop_height, crop_width, extrapolation_value=0, transform_fpcoor=True):
super(RoIAlign, self).__init__()
self.crop_height = crop_height
self.... | 1,978 | 39.387755 | 146 | py |
pytorch-mask-rcnn | pytorch-mask-rcnn-master/roialign/roi_align/crop_and_resize.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
from ._ext import crop_and_resize as _backend
class CropAndResizeFunction(Function):
def __init__(self, crop_height, crop_width, extrapolation_value=0):
self.crop_height = crop_height
... | 2,150 | 30.632353 | 120 | py |
pytorch-mask-rcnn | pytorch-mask-rcnn-master/roialign/roi_align/build.py | import os
import torch
from torch.utils.ffi import create_extension
sources = ['src/crop_and_resize.c']
headers = ['src/crop_and_resize.h']
defines = []
with_cuda = False
extra_objects = []
if torch.cuda.is_available():
print('Including CUDA code.')
sources += ['src/crop_and_resize_gpu.c']
headers += ['s... | 1,086 | 25.512195 | 75 | py |
pytorch-mask-rcnn | pytorch-mask-rcnn-master/nms/pth_nms.py | import torch
from ._ext import nms
import numpy as np
def pth_nms(dets, thresh):
"""
dets has to be a tensor
"""
if not dets.is_cuda:
x1 = dets[:, 1]
y1 = dets[:, 0]
x2 = dets[:, 3]
y2 = dets[:, 2]
scores = dets[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.sort(0, des... | 1,485 | 26.518519 | 104 | py |
pytorch-mask-rcnn | pytorch-mask-rcnn-master/nms/build.py | import os
import torch
from torch.utils.ffi import create_extension
sources = ['src/nms.c']
headers = ['src/nms.h']
defines = []
with_cuda = False
if torch.cuda.is_available():
print('Including CUDA code.')
sources += ['src/nms_cuda.c']
headers += ['src/nms_cuda.h']
defines += [('WITH_CUDA', None)]
... | 774 | 21.142857 | 75 | py |
MT3 | MT3-master/src/training.py | import os
import time
import datetime
import re
import shutil
import pickle
from collections import deque
import argparse
import numpy as np
import torch
from torch.optim import Adam
from torch.optim.lr_scheduler import ReduceLROnPlateau
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from da... | 17,679 | 51.776119 | 167 | py |
MT3 | MT3-master/src/data_generation/data_generator.py | import multiprocessing
import numpy as np
from numpy.random import SeedSequence, default_rng
import torch
from torch import Tensor
from data_generation.mot_data_generation import MotDataGenerator
from util.misc import NestedTensor
class DataGenerator:
def __init__(self, params):
self.params = params
... | 4,100 | 38.815534 | 170 | py |
MT3 | MT3-master/src/modules/contrastive_loss.py | import torch
from torch import nn, Tensor
from torch.nn import functional as F
class ContrastiveLoss(nn.Module):
def __init__(self, params):
super().__init__()
self.device = torch.device(params.training.device)
def forward(self, log_classifications, unique_ids) -> Tensor:
batch_size, ... | 1,577 | 45.411765 | 132 | py |
MT3 | MT3-master/src/modules/matcher.py | import torch
from scipy.optimize import linear_sum_assignment
from torch import nn
class HungarianMatcher(nn.Module):
"""This class computes an assignment between the targets and the predictions of the network
For efficiency reasons, the targets don't include the no_object. Because of this, in general,
th... | 2,614 | 41.868852 | 115 | py |
MT3 | MT3-master/src/modules/mlp.py | import torch
from torch import nn, Tensor
from torch.nn import functional as F
class MLP(nn.Module):
""" Very simple multi-layer perceptron (also called FFN)"""
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
super().__init__()
self.num_layers = num_layers
h = [hidde... | 615 | 35.235294 | 103 | py |
MT3 | MT3-master/src/modules/evaluation_gui.py | """tkinter app for evaluation GUI. Run evaluation.py to try it out!
"""
import matplotlib
import os
import torch
from pathlib import Path
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
from scipy.io import loadmat
impor... | 13,493 | 40.266055 | 165 | py |
MT3 | MT3-master/src/modules/loss.py | import numpy as np
import torch
from torch import nn, Tensor
import torch.nn.functional as F
from scipy.optimize import linear_sum_assignment
def check_gospa_parameters(c, p, alpha):
""" Check parameter bounds.
If the parameter values are outside the allowable range specified in the
definition of GOSPA, ... | 20,758 | 42.611345 | 212 | py |
MT3 | MT3-master/src/modules/evaluator.py | import torch
import time
import numpy as np
from util.misc import NestedTensor
#from sklearn.manifold import TSNE
#from sklearn.decomposition import PCA
def compute_losses(outputs, labels, contrastive_classifications, unique_ids, mot_loss, contrastive_loss):
c_loss = contrastive_loss.forward(contrastive_classific... | 8,156 | 44.825843 | 144 | py |
MT3 | MT3-master/src/modules/transformer.py | import torch
from torch import nn, Tensor
import torch.nn.functional as F
from torch.nn.modules import ModuleList
import copy
from typing import Optional, List
"""
MOTT Transformer class.
Copy-pasted from Facebook's DETR Transformer modules with the following modifications:
*
*
*
"""
class PreProcce... | 10,484 | 40.117647 | 98 | py |
MT3 | MT3-master/src/modules/position_encoder.py | import torch
from torch import nn, Tensor
import math
class LearnedPositionEncoder(nn.Module):
"""
Learned Position Encoder. Takes tensor of positional indicies and converts to learned embeddings
"""
def __init__(self, n_timesteps, d_model):
super().__init__()
self.embeddor = nn.E... | 1,666 | 34.468085 | 111 | py |
MT3 | MT3-master/src/modules/contrastive_classifier.py | import torch
from torch import nn, Tensor
from torch.nn import functional as F
import numpy as np
from typing import Optional
class ContrastiveClassifier(nn.Module):
def __init__(self, measurement_dim):
super().__init__()
self.measurement_dim = measurement_dim
self.device = 'cpu'
... | 1,849 | 33.90566 | 109 | py |
MT3 | MT3-master/src/modules/models/mt3/transformer.py | import torch
from torch import nn, Tensor
import torch.nn.functional as F
from torch.nn.modules import ModuleList
from util.misc import inverse_sigmoid
from modules.transformer import PreProccessor, TransformerEncoderLayer, TransformerDecoderLayer, TransformerEncoder
import copy
from typing import Optional, List
c... | 3,207 | 38.604938 | 120 | py |
MT3 | MT3-master/src/modules/models/mt3/mt3.py | import torch
from torch import nn
from modules.position_encoder import LearnedPositionEncoder
from modules.mlp import MLP
from modules.models.mt3.transformer import TransformerEncoder, TransformerDecoder, PreProccessor, TransformerEncoderLayer, TransformerDecoderLayer
from modules.contrastive_classifier import Contrast... | 12,318 | 49.904959 | 174 | py |
MT3 | MT3-master/src/util/plotting.py | import numpy as np
import torch
import matplotlib
import matplotlib.pyplot as plt
@torch.no_grad()
def output_truth_plot(ax, output, labels, matched_idx, batch, training_example_to_plot=0):
assert 'state' in output, "'state' should be in dict"
assert 'logits' in output, "'logits' should be in dict"
... | 8,416 | 42.611399 | 150 | py |
MT3 | MT3-master/src/util/misc.py | from typing import Optional, List
import math
import os
import sys
import torch
from torch import Tensor
from util.load_config_files import load_yaml_into_dotdict, dotdict
class NestedTensor(object):
def __init__(self, tensors, mask: Optional[Tensor]):
self.tensors = tensors
self.mask = mask
... | 7,244 | 33.174528 | 121 | py |
MT3 | MT3-master/src/util/generate_data_for_matlab.py | import sys
import argparse
from scipy.io import savemat
import torch
import numpy as np
from src.data_generation.data_generator import DataGenerator
from src.util.load_config_files import load_yaml_into_dotdict, dotdict
parser = argparse.ArgumentParser()
parser.add_argument('-fp', '--filepath', help='filepath to co... | 2,242 | 31.985294 | 99 | py |
MT3 | MT3-master/src/tests/test_unique_obj_ids_data_generator.py | import numpy as np
import matplotlib.pyplot as plt
import torch
from src.data_generation.data_generator import MotDataGenerator
from src.training import get_params, convert_to_dot_dict
params = get_params()
params = convert_to_dot_dict(params)
data_gen_params = params.data_generation_params
data_gen_params.sigma_y =... | 673 | 25.96 | 107 | py |
MT3 | MT3-master/src/tests/integration_test_contrastive_classifier.py | from data_generation.data_generator import DataGenerator
from util.load_config_files import dotdict
from util.plotting import contrastive_classifications_plot
from modules.loss import MotLoss
from modules.contrastive_loss import ContrastiveLoss
from modules.MOTT import MOTT
import numpy as np
import torch
from torch.op... | 5,354 | 38.087591 | 157 | py |
MT3 | MT3-master/src/tests/test_compute_contrastive_classifier_output.py | import unittest
import torch
from torch import nn
import numpy as np
from src.modules.contrastive_classifier import ContrastiveClassifier
class TestComputeContrastiveClassifierOutput(unittest.TestCase):
def test_batch_input(self):
# Input
x = [
[
[5.0, 9.0], ... | 6,060 | 34.863905 | 124 | py |
MT3 | MT3-master/src/tests/integration_test_data_generator.py | import argparse
import matplotlib.pyplot as plt
import torch
import numpy as np
from src.data_generation.data_generator import DataGenerator
from src.util.load_config_files import load_yaml_into_dotdict, dotdict
from src.util.misc import factor_int
batch_size = 4
# Load hyperparameters from yaml file specified via ... | 1,713 | 32.607843 | 120 | py |
MT3 | MT3-master/src/tests/test_contrastive_loss.py | import unittest
import torch
import numpy as np
from numpy import log
from src.modules.contrastive_loss import ContrastiveLoss
class TestContrastiveLoss(unittest.TestCase):
def test_simple_input(self):
# Input
unique_ids = \
[
[2, 0, 1, 2],
[6, 7, 6, 6... | 2,630 | 32.303797 | 119 | py |
darmonpoints | darmonpoints-master/docs/source/conf.py | # -*- coding: utf-8 -*-
#
# sample documentation build configuration file,
# inspried by slabbe configuration file created sphinx-quickstart
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
... | 11,697 | 32.13881 | 132 | py |
eli5 | eli5-master/tests/test_xgboost.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import pytest
import numpy as np
import scipy.sparse as sp
from sklearn.feature_extraction.text import CountVectorizer
pytest.importorskip('xgboost')
import xgboost
from xgboost import XGBClassifier, XGBRegressor
from sklearn.pipeline import FeatureUnion
f... | 17,971 | 35.088353 | 83 | py |
eli5 | eli5-master/tests/test_keras.py | # -*- coding: utf-8 -*-
"""Keras unit tests"""
import pytest
keras = pytest.importorskip('keras')
import keras.backend as K
from keras.models import Sequential, Model
from keras.layers import (
Dense,
Activation,
Conv2D,
GlobalAveragePooling2D,
Input,
Lambda,
)
from keras.backend import... | 5,516 | 30.346591 | 96 | py |
eli5 | eli5-master/tests/test_keras_integration.py | # -*- coding: utf-8 -*-
"""Test integration of Grad-CAM explanation and image formatter for Keras"""
from __future__ import print_function
import pytest
keras = pytest.importorskip('keras')
PIL = pytest.importorskip('PIL')
matplotlib = pytest.importorskip('matplotlib')
IPython = pytest.importorskip('IPython')
impor... | 5,448 | 32.635802 | 100 | py |
eli5 | eli5-master/tests/test_sklearn_permutation_importance.py | # -*- coding: utf-8 -*-
import pytest
import numpy as np
from sklearn.base import is_classifier, is_regressor
from sklearn.svm import SVR, SVC
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import mak... | 7,122 | 36.098958 | 94 | py |
eli5 | eli5-master/docs/source/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# ELI5 documentation build configuration file, created by
# sphinx-quickstart on Mon Nov 14 21:54:37 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autog... | 11,378 | 26.618932 | 80 | py |
eli5 | eli5-master/eli5/xgboost.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from functools import partial
import re
from typing import Any, Dict, List, Tuple, Optional, Pattern
import numpy as np
import scipy.sparse as sp
from xgboost import (
XGBClassifier,
XGBRegressor,
Booster,
DMatrix
)
from eli5.explain impor... | 15,046 | 35.170673 | 80 | py |
eli5 | eli5-master/eli5/lightgbm.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division
from collections import defaultdict
from typing import DefaultDict, Optional
import numpy as np
import lightgbm
from eli5.explain import explain_weights, explain_prediction
from eli5._feature_importances import get_feature_importance_explanation... | 9,811 | 33.918149 | 87 | py |
eli5 | eli5-master/eli5/_decision_path.py | # Method for determining feature importances follows an idea from
# http://blog.datadive.net/interpreting-random-forests/.
# Implementations are in eli5.xgboost, eli5.lightgbm and
# eli5.sklearn.explain_prediction.
from eli5._feature_weights import get_top_features_filtered
from eli5.base import Explanation, TargetExpl... | 4,447 | 37.678261 | 79 | py |
eli5 | eli5-master/eli5/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
__version__ = '0.10.1'
from .formatters import (
format_as_html,
format_html_styles,
format_as_text,
format_as_dict,
)
from .explain import explain_weights, explain_prediction
from .sklearn import explain_weights_sklearn, explain_predictio... | 2,056 | 19.777778 | 72 | py |
eli5 | eli5-master/eli5/keras/gradcam.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from typing import Union, Optional, Tuple, List
import numpy as np
import keras
import keras.backend as K
from keras.models import Model
from keras.layers import Layer
def gradcam(weights, activations):
# type: (np.ndarray, np.ndarray) -> np.ndarray
... | 7,752 | 36.454106 | 111 | py |
eli5 | eli5-master/eli5/keras/__init__.py | # -*- coding: utf-8 -*-
from .explain_prediction import explain_prediction_keras
from .gradcam import gradcam, gradcam_backend | 127 | 31 | 56 | py |
eli5 | eli5-master/eli5/keras/explain_prediction.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from typing import Union, Optional, Callable, Tuple, List, TYPE_CHECKING
if TYPE_CHECKING:
import PIL
import numpy as np
import keras
import keras.backend as K
from keras.models import Model
from keras.layers import Layer
from keras.layers import (
... | 12,562 | 35.626822 | 100 | py |
DALLE2-pytorch | DALLE2-pytorch-main/setup.py | from setuptools import setup, find_packages
exec(open('dalle2_pytorch/version.py').read())
setup(
name = 'dalle2-pytorch',
packages = find_packages(exclude=[]),
include_package_data = True,
entry_points={
'console_scripts': [
'dalle2_pytorch = dalle2_pytorch.cli:main',
'dream = dalle2_pytorch.c... | 1,500 | 24.016667 | 65 | py |
DALLE2-pytorch | DALLE2-pytorch-main/train_decoder.py | from pathlib import Path
from typing import List
from datetime import timedelta
from dalle2_pytorch.trainer import DecoderTrainer
from dalle2_pytorch.dataloaders import create_image_embedding_dataloader
from dalle2_pytorch.trackers import Tracker
from dalle2_pytorch.train_configs import DecoderConfig, TrainDecoderConf... | 33,848 | 50.915644 | 287 | py |
DALLE2-pytorch | DALLE2-pytorch-main/train_diffusion_prior.py | import click
import torch
from torch import nn
from typing import List
from accelerate import Accelerator
from accelerate.utils import set_seed
from torch.utils.data import DataLoader
from embedding_reader import EmbeddingReader
from accelerate.utils import dataclasses as accelerate_dataclasses
from dalle2_pytorch.ut... | 23,057 | 28.906615 | 175 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/vqgan_vae_trainer.py | from math import sqrt
import copy
from random import choice
from pathlib import Path
from shutil import rmtree
from PIL import Image
import torch
from torch import nn
from torch.cuda.amp import autocast, GradScaler
from torch.utils.data import Dataset, DataLoader, random_split
import torchvision.transforms as T
from ... | 8,313 | 28.799283 | 146 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/dalle2_pytorch.py | import math
import random
from tqdm.auto import tqdm
from functools import partial, wraps
from contextlib import contextmanager
from collections import namedtuple
from pathlib import Path
import torch
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
from torch import nn, einsum
import torc... | 125,196 | 36.472912 | 438 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/train_configs.py | import json
from torchvision import transforms as T
from pydantic import BaseModel, validator, model_validator
from typing import List, Optional, Union, Tuple, Dict, Any, TypeVar
from x_clip import CLIP as XCLIP
from open_clip import list_pretrained
from coca_pytorch import CoCa
from dalle2_pytorch.dalle2_pytorch imp... | 13,640 | 34.616188 | 216 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/vqgan_vae.py | import copy
import math
from math import sqrt
from functools import partial, wraps
from vector_quantize_pytorch import VectorQuantize as VQ
import torch
from torch import nn, einsum
import torch.nn.functional as F
from torch.autograd import grad as torch_grad
import torchvision
from einops import rearrange, reduce, ... | 22,049 | 27.823529 | 146 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/cli.py | import click
import torch
import torchvision.transforms as T
from functools import reduce
from pathlib import Path
from dalle2_pytorch import DALLE2, Decoder, DiffusionPrior
def safeget(dictionary, keys, default = None):
return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.sp... | 1,800 | 32.981132 | 129 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/tokenizer.py | # take from https://github.com/openai/CLIP/blob/main/clip/simple_tokenizer.py
# to give users a quick easy start to training DALL-E without doing BPE
import torch
import html
import os
import ftfy
import regex as re
from functools import lru_cache
from pathlib import Path
from dalle2_pytorch.utils import import_or_p... | 6,698 | 33.890625 | 123 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/__init__.py | import torch
from packaging import version
if version.parse(torch.__version__) >= version.parse('2.0.0'):
from einops._torch_specific import allow_ops_in_compiled_graph
allow_ops_in_compiled_graph()
from dalle2_pytorch.version import __version__
from dalle2_pytorch.dalle2_pytorch import DALLE2, DiffusionPrior... | 580 | 37.733333 | 102 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/trainer.py | import time
import copy
from pathlib import Path
from math import ceil
from functools import partial, wraps
from contextlib import nullcontext
from collections.abc import Iterable
import torch
import torch.nn.functional as F
from torch import nn
from torch.optim.lr_scheduler import LambdaLR, CosineAnnealingLR
from tor... | 26,670 | 34.896366 | 174 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/trackers.py | import urllib.request
import os
import json
from pathlib import Path
import shutil
from itertools import zip_longest
from typing import Any, Optional, List, Union
from pydantic import BaseModel
import torch
from dalle2_pytorch.dalle2_pytorch import Decoder, DiffusionPrior
from dalle2_pytorch.utils import import_or_pri... | 26,497 | 43.08985 | 280 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/optimizer.py | from torch.optim import AdamW, Adam
def separate_weight_decayable_params(params):
wd_params, no_wd_params = [], []
for param in params:
param_list = no_wd_params if param.ndim < 2 else wd_params
param_list.append(param)
return wd_params, no_wd_params
def get_optimizer(
params,
lr =... | 943 | 25.971429 | 78 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/dataloaders/prior_loader.py | from math import ceil
from clip import tokenize
from embedding_reader import EmbeddingReader
from torch import from_numpy
from torch.utils.data import IterableDataset, DataLoader
class PriorEmbeddingDataset(IterableDataset):
"""
PriorEmbeddingDataset is a wrapper of EmbeddingReader.
It enables one to sim... | 8,952 | 30.636042 | 104 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/dataloaders/decoder_loader.py | import os
import webdataset as wds
import torch
from torch.utils.data import DataLoader
import numpy as np
import fsspec
import shutil
def get_shard(filename):
"""
Filenames with shards in them have a consistent structure that we can take advantage of
Standard structure: path/to/file/prefix_string_00001.ex... | 13,714 | 50.367041 | 196 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/dataloaders/__init__.py | from dalle2_pytorch.dataloaders.decoder_loader import ImageEmbeddingDataset, create_image_embedding_dataloader
from dalle2_pytorch.dataloaders.prior_loader import make_splits, get_reader, PriorEmbeddingDataset
| 210 | 69.333333 | 110 | py |
DALLE2-pytorch | DALLE2-pytorch-main/dalle2_pytorch/dataloaders/simple_image_only_dataloader.py | from pathlib import Path
import torch
from torch.utils import data
from torchvision import transforms, utils
from PIL import Image
# helpers functions
def cycle(dl):
while True:
for data in dl:
yield data
# dataset and dataloader
class Dataset(data.Dataset):
def __init__(
self,... | 1,336 | 21.283333 | 97 | py |
sensecnn | sensecnn-master/sentiment_analysis/__main__.py | from __future__ import print_function
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Bidirectional
from keras.layers import Embedding
from keras.layers import LSTM
import pr... | 8,227 | 34.773913 | 130 | py |
sensecnn | sensecnn-master/topic_categorization/__main__.py | from __future__ import print_function
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import LSTM
import prepare_dataset a... | 8,445 | 35.882096 | 130 | py |
Adaptive-Cutsel-MILP | Adaptive-Cutsel-MILP-main/utilities.py | #! /usr/bin/env python
import os
import numpy as np
import torch
import subprocess
import shutil
import logging
import argparse
from pyscipopt import Model, quicksum, SCIP_RESULT, SCIP_PARAMSETTING, Branchrule, SCIP_PRESOLTIMING, SCIP_PROPTIMING
from ConstraintHandler.ConstraintHandler import RepeatSepaConshdlr
from Cu... | 28,174 | 41.368421 | 120 | py |
Adaptive-Cutsel-MILP | Adaptive-Cutsel-MILP-main/parameters.py | """File containing the settings for the experiments you want to perform.
Each parameter here affects different bits of the experiments. The individual comments outline how.
"""
# If you want to use the MIPLIB solution instead of one found after a 10 minute solve, set this to True
# In the paper this was set to False f... | 3,110 | 49.177419 | 117 | py |
Adaptive-Cutsel-MILP | Adaptive-Cutsel-MILP-main/Slurm/evaluate_trained_network.py | #! /usr/bin/env python
import argparse
import torch
import os
from GNN.GNN import GNNPolicy
from Slurm.train_neural_network import create_tensorboard_writer, get_standard_solve_data, \
get_rand_seeds_from_feature_generators, generate_batches, run_test_set
from utilities import remove_temp_files, str_to_bool, is_fil... | 4,398 | 48.988636 | 118 | py |
Adaptive-Cutsel-MILP | Adaptive-Cutsel-MILP-main/Slurm/train_neural_network.py | #! /usr/bin/env python
import os
import argparse
import yaml
import logging
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
import time
from datetime import datetime
from utilities import read_feature_vector_files, str_to_bool
from utilities import remove_slurm_files, remove_temp_files... | 49,087 | 55.100571 | 120 | py |
Adaptive-Cutsel-MILP | Adaptive-Cutsel-MILP-main/scripts/random_seed_finder.py | import argparse
import numpy as np
import os
import torch
from GNN.GNN import GNNPolicy
from utilities import is_dir, read_feature_vector_files, get_instances
from parameters import NUM_TORCH_SEEDS
def get_random_seeds(instance_dir):
files = os.listdir(instance_dir)
files = [file for file in files if file.end... | 2,322 | 37.716667 | 116 | py |
Adaptive-Cutsel-MILP | Adaptive-Cutsel-MILP-main/GNN/GNN.py | import torch
import torch.nn.functional as F
import torch_geometric
import numpy as np
"""
This GNN was mostly taken from an example at Ecole.ai (https://www.ecole.ai/)
The exact example can be seen here: https://github.com/ds4dm/ecole/blob/master/examples/branching-imitation.ipynb
The design comes from a paper by Gas... | 6,703 | 44.605442 | 119 | py |
PIRBN | PIRBN-main/1D_sine_function/PIRBN.py | import tensorflow as tf
from Dif_op import Dif
def PIRBN(rbn):
"""
====================================================================================================================
This function is to initialize a PIRBN.
=============================================================================... | 799 | 27.571429 | 120 | py |
PIRBN | PIRBN-main/1D_sine_function/rbn_net.py | import tensorflow as tf
import numpy as np
class RBN_Net:
def __init__(self, n_in, n_out, n_neu, b, c):
"""
================================================================================================================
This class is to build a radial basis network (RBN).
--... | 3,058 | 35.416667 | 138 | py |
PIRBN | PIRBN-main/1D_sine_function/Dif_op.py | import tensorflow as tf
class Dif(tf.keras.layers.Layer):
"""
====================================================================================================================
This is the class for calculating the differential terms of the RBN's output with respect to the RBN's input. We
adopt the ... | 2,914 | 41.246377 | 120 | py |
PIRBN | PIRBN-main/1D_sine_coupling/PIRBN.py | import tensorflow as tf
from Dif_op import Dif
def PIRBN(rbn):
"""
====================================================================================================================
This function is to initialize a PIRBN.
=============================================================================... | 799 | 27.571429 | 120 | py |
PIRBN | PIRBN-main/1D_sine_coupling/rbn_net.py | import tensorflow as tf
import numpy as np
class RBN_Net:
def __init__(self, n_in, n_out, n_neu, b, c):
"""
================================================================================================================
This class is to build a radial basis network (RBN).
--... | 3,058 | 35.416667 | 138 | py |
PIRBN | PIRBN-main/1D_sine_coupling/Dif_op.py | import tensorflow as tf
class Dif(tf.keras.layers.Layer):
"""
====================================================================================================================
This is the class for calculating the differential terms of the RBN's output with respect to the RBN's input. We
adopt the ... | 2,998 | 41.842857 | 120 | py |
PIRBN | PIRBN-main/2D_viscoelastic_Poiseuille/PIRBN.py | import tensorflow as tf
from Dif_op import Dif
def PIRBN(rbn_u, rbn_tau):
"""
====================================================================================================================
This function is to initialize a PIRBN.
==================================================================... | 1,173 | 29.102564 | 120 | py |
PIRBN | PIRBN-main/2D_viscoelastic_Poiseuille/rbf_net.py | import tensorflow as tf
import numpy as np
class RBF_Net:
def __init__(self, n_in, n_out, n_neu_x, n_neu_y, b, c_x, c_y):
"""
================================================================================================================
This class is to build a radial basis network ... | 3,607 | 36.195876 | 120 | py |
PIRBN | PIRBN-main/2D_viscoelastic_Poiseuille/Dif_op.py | import tensorflow as tf
class Dif(tf.keras.layers.Layer):
"""
====================================================================================================================
This is the class for calculating the differential terms of the RBN's output with respect to the RBN's input. We
adopt the ... | 2,642 | 41.629032 | 120 | py |
PIRBN | PIRBN-main/2D_diffusion_equation/PIRBN.py | import tensorflow as tf
from Dif_op import Dif
def PIRBN(rbn):
"""
====================================================================================================================
This function is to initialize a PIRBN.
=============================================================================... | 899 | 29 | 120 | py |
PIRBN | PIRBN-main/2D_diffusion_equation/rbf_net.py | import tensorflow as tf
import numpy as np
class RBF_Net:
def __init__(self, n_in, n_out, n_neu_x, n_neu_y, b, c_x, c_y):
"""
================================================================================================================
This class is to build a radial basis network ... | 3,607 | 36.195876 | 120 | py |
PIRBN | PIRBN-main/2D_diffusion_equation/Dif_op.py | import tensorflow as tf
class Dif(tf.keras.layers.Layer):
"""
====================================================================================================================
This is the class for calculating the differential terms of the RBN's output with respect to the RBN's input. We
adopt the ... | 2,967 | 42.647059 | 120 | py |
PIRBN | PIRBN-main/2D_wave_equation/PIRBN.py | import tensorflow as tf
from Dif_op import Dif
def PIRBN(rbn):
"""
====================================================================================================================
This function is to initialize a PIRBN.
=============================================================================... | 930 | 29.032258 | 120 | py |
PIRBN | PIRBN-main/2D_wave_equation/rbf_net.py | import tensorflow as tf
import numpy as np
class RBF_Net:
def __init__(self, n_in, n_out, n_neu_x, n_neu_y, b, c_x, c_y):
"""
================================================================================================================
This class is to build a radial basis network ... | 3,607 | 36.195876 | 120 | py |
PIRBN | PIRBN-main/2D_wave_equation/Dif_op.py | import tensorflow as tf
class Dif(tf.keras.layers.Layer):
"""
====================================================================================================================
This is the class for calculating the differential terms of the RBN's output with respect to the RBN's input. We
adopt the ... | 3,053 | 43.26087 | 120 | py |
PIRBN | PIRBN-main/1D_nonlinear_spring/PIRBN.py | import tensorflow as tf
from Dif_op import Dif
def PIRBN(rbn):
"""
====================================================================================================================
This function is to initialize a PIRBN.
=============================================================================... | 872 | 28.1 | 120 | py |
PIRBN | PIRBN-main/1D_nonlinear_spring/rbn_net.py | import tensorflow as tf
import numpy as np
class RBN_Net:
def __init__(self, n_in, n_out, n_neu, b, c):
"""
================================================================================================================
This class is to build a radial basis network (RBN).
--... | 3,058 | 35.416667 | 138 | py |
PIRBN | PIRBN-main/1D_nonlinear_spring/Dif_op.py | import tensorflow as tf
class Dif(tf.keras.layers.Layer):
"""
====================================================================================================================
This is the class for calculating the differential terms of the RBN's output with respect to the RBN's input. We
adopt the ... | 2,914 | 41.246377 | 120 | py |
c3d-pytorch | c3d-pytorch-master/C3D_model.py | import torch.nn as nn
class C3D(nn.Module):
"""
The C3D network as described in [1].
"""
def __init__(self):
super(C3D, self).__init__()
self.conv1 = nn.Conv3d(3, 64, kernel_size=(3, 3, 3), padding=(1, 1, 1))
self.pool1 = nn.MaxPool3d(kernel_size=(1, 2, 2), stride=(1, 2, 2))
... | 2,364 | 30.533333 | 93 | py |
c3d-pytorch | c3d-pytorch-master/predict.py | """ How to use C3D network. """
import numpy as np
import torch
from torch.autograd import Variable
from os.path import join
from glob import glob
import skimage.io as io
from skimage.transform import resize
from C3D_model import C3D
def get_sport_clip(clip_name, verbose=True):
"""
Loads a clip to be fed ... | 2,287 | 21.431373 | 111 | py |
spurious_feature_learning | spurious_feature_learning-main/dfr_evaluate_auroc.py | """Evaluate DFR on spurious correlations datasets."""
import torch
import numpy as np
import os
import sys
import tqdm
import json
import pickle
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import roc_auc_score
import models
import utils
f... | 14,887 | 34.702638 | 118 | py |
spurious_feature_learning | spurious_feature_learning-main/dfr_evaluate_spurious.py | """Evaluate DFR on spurious correlations datasets."""
import torch
import numpy as np
import os
import sys
import tqdm
import json
import pickle
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
import models
import utils
from utils import supervised_utils
try:
... | 14,016 | 34.666667 | 118 | py |
spurious_feature_learning | spurious_feature_learning-main/train_supervised.py | import os
import torch
import models
import optimizers
import utils
from utils import supervised_utils
try:
import wandb
has_wandb = True
except ImportError:
has_wandb = False
def get_args_parser():
parser = utils.get_default_args()
# TODO: add new supervised specific params?
return parser
de... | 4,043 | 32.983193 | 91 | py |
spurious_feature_learning | spurious_feature_learning-main/group_DRO/loss.py | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class LossComputer:
def __init__(self, criterion, is_robust, dataset, alpha=None, gamma=0.1, adj=None, min_var_weight=0, step_size=0.01, normalize_loss=False, btl=False):
self.criterion = criterion
self.... | 8,669 | 43.234694 | 154 | py |
spurious_feature_learning | spurious_feature_learning-main/group_DRO/utils.py | import sys
import os
import torch
import numpy as np
import csv
import torchvision
from torch.utils.tensorboard import SummaryWriter
import json
class Logger(object):
def __init__(self, fpath=None, mode='w'):
self.console = sys.stdout
self.file = None
if fpath is not None:
self.... | 4,282 | 26.455128 | 76 | py |
spurious_feature_learning | spurious_feature_learning-main/group_DRO/train.py | import os
import types
import gc
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader, Subset
import numpy as np
from tqdm import tqdm
from utils import AverageMeter, accuracy
from loss import LossComputer
from utils import log_to_tb
from pytorch_transfo... | 9,121 | 37.489451 | 142 | py |
spurious_feature_learning | spurious_feature_learning-main/group_DRO/run_expt.py | import os, csv
import argparse
import pandas as pd
import torch
import torch.nn as nn
import torchvision
import sys
from gdro_models import model_attributes
from gdro_data import dfr_datasets
from gdro_data.data import dataset_attributes, shift_types, prepare_data, log_data
from utils import set_seed, Logger, CSVBatch... | 9,211 | 37.705882 | 133 | py |
spurious_feature_learning | spurious_feature_learning-main/group_DRO/gdro_data/confounder_utils.py | import os
import torch
import pandas as pd
from PIL import Image
import numpy as np
import torchvision.transforms as transforms
from gdro_models import model_attributes
from torch.utils.data import Dataset, Subset
from gdro_data.celebA_dataset import CelebADataset
from gdro_data.cub_dataset import CUBDataset
from gdro_... | 1,750 | 30.267857 | 102 | py |
spurious_feature_learning | spurious_feature_learning-main/group_DRO/gdro_data/confounder_dataset.py | import os
import torch
import pandas as pd
from PIL import Image
import numpy as np
import torchvision.transforms as transforms
from gdro_models import model_attributes
from torch.utils.data import Dataset, Subset
class ConfounderDataset(Dataset):
def __init__(self, root_dir,
target_name, confound... | 2,505 | 36.969697 | 96 | py |
spurious_feature_learning | spurious_feature_learning-main/group_DRO/gdro_data/utils.py | import torch
import numpy as np
from torch.utils.data import Subset
# Train val split
def train_val_split(dataset, val_frac):
# split into train and val
indices = np.arange(len(dataset))
np.random.shuffle(indices)
val_size = int(np.round(len(dataset)*val_frac))
train_indices, val_indices = indices[... | 742 | 34.380952 | 87 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.