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 |
|---|---|---|---|---|---|---|
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/ppo/ppo_agent.py | import numpy as np
import torch
from torch import optim
from rl_utils.running_filter.running_filter import ZFilter
from models import cnn_net, mlp_net
from utils import select_actions, evaluate_actions
from datetime import datetime
import os
import copy
class ppo_agent:
def __init__(self, envs, args):
self... | 11,143 | 50.592593 | 144 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/sac/utils.py | import numpy as np
import torch
from torch.distributions.normal import Normal
from torch.distributions import Distribution
"""
the tanhnormal distributions from rlkit may not stable
"""
class tanh_normal(Distribution):
def __init__(self, normal_mean, normal_std, epsilon=1e-6, cuda=False):
self.normal_mean... | 2,841 | 34.08642 | 118 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/sac/demo.py | from arguments import get_args
import gym
import torch
import numpy as np
from models import tanh_gaussian_actor
if __name__ == '__main__':
args = get_args()
env = gym.make(args.env_name)
# get environment infos
obs_dims = env.observation_space.shape[0]
action_dims = env.action_space.shape[0]
a... | 1,433 | 35.769231 | 112 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/sac/sac_agent.py | import numpy as np
import torch
from models import flatten_mlp, tanh_gaussian_actor
from rl_utils.experience_replay.experience_replay import replay_buffer
from utils import get_action_info
from datetime import datetime
import copy
import os
import gym
"""
2019-Nov-12 - start to add the automatically tempature tuning
... | 10,871 | 49.803738 | 166 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/sac/models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
# the flatten mlp
class flatten_mlp(nn.Module):
#TODO: add the initialization method for it
def __init__(self, input_dims, hidden_size, action_dims=None):
super(flatten_mlp, self).__init__()
self.fc1 = nn.Linear(input_dims, hidd... | 1,745 | 38.681818 | 130 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_utils/seeds/seeds.py | import numpy as np
import random
import torch
# set random seeds for the pytorch, numpy and random
def set_seeds(args, rank=0):
# set seeds for the numpy
np.random.seed(args.seed + rank)
# set seeds for the random.random
random.seed(args.seed + rank)
# set seeds for the pytorch
torch.manual_see... | 407 | 26.2 | 52 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_utils/mpi_utils/utils.py | from mpi4py import MPI
import numpy as np
import torch
# sync_networks across the different cores
def sync_networks(network):
"""
netowrk is the network you want to sync
"""
comm = MPI.COMM_WORLD
flat_params = _get_flat_params_or_grads(network, mode='params')
comm.Bcast(flat_params, root=0)
... | 1,427 | 31.454545 | 119 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_utils/running_filter/running_filter.py | from collections import deque
import numpy as np
# this is from the https://github.com/ikostrikov/pytorch-trpo/blob/master/running_state.py
# from https://github.com/joschu/modular_rl
# http://www.johndcook.com/blog/standard_deviation/
class RunningStat(object):
def __init__(self, shape):
self._n = 0
... | 1,715 | 23.169014 | 90 | py |
gcn-over-pruned-trees | gcn-over-pruned-trees-master/eval.py | """
Run evaluation with saved models.
"""
import random
import argparse
from tqdm import tqdm
import torch
from data.loader import DataLoader
from model.trainer import GCNTrainer
from utils import torch_utils, scorer, constant, helper
from utils.vocab import Vocab
parser = argparse.ArgumentParser()
parser.add_argumen... | 2,130 | 30.80597 | 97 | py |
gcn-over-pruned-trees | gcn-over-pruned-trees-master/train.py | """
Train a model on TACRED.
"""
import os
import sys
from datetime import datetime
import time
import numpy as np
import random
import argparse
from shutil import copyfile
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from data.loader import DataLoader
from model.... | 8,638 | 44.708995 | 156 | py |
gcn-over-pruned-trees | gcn-over-pruned-trees-master/utils/torch_utils.py | """
Utility functions for torch.
"""
import torch
from torch import nn, optim
from torch.optim import Optimizer
### class
class MyAdagrad(Optimizer):
"""My modification of the Adagrad optimizer that allows to specify an initial
accumulater value. This mimics the behavior of the default Adagrad implementation ... | 5,681 | 33.858896 | 106 | py |
gcn-over-pruned-trees | gcn-over-pruned-trees-master/data/loader.py | """
Data loader for TACRED json files.
"""
import json
import random
import torch
import numpy as np
from utils import constant, helper, vocab
class DataLoader(object):
"""
Load data from json files, preprocess and prepare batches.
"""
def __init__(self, filename, batch_size, opt, vocab, evaluation=F... | 5,487 | 36.848276 | 121 | py |
gcn-over-pruned-trees | gcn-over-pruned-trees-master/model/gcn.py | """
GCN model for relation extraction.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from model.tree import Tree, head_to_tree, tree_to_adj
from utils import constant, torch_utils
class GCNClassifier(nn.Module):
""" A wrapper classif... | 7,886 | 39.239796 | 131 | py |
gcn-over-pruned-trees | gcn-over-pruned-trees-master/model/trainer.py | """
A trainer class.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from model.gcn import GCNClassifier
from utils import constant, torch_utils
class Trainer(object):
def __init__(self, opt, emb_matrix=None):
raise NotImplemen... | 3,659 | 32.888889 | 101 | py |
SwinMR | SwinMR-main/main_test_swinmr_CC.py | '''
# -----------------------------------------
Main Program for Testing
SwinMR for MRI_Recon
Dataset: CC
by Jiahao Huang (j.huang21@imperial.ac.uk)
# -----------------------------------------
'''
import argparse
import cv2
import csv
import sys
import numpy as np
from collections import OrderedDict
import os
import t... | 11,599 | 40.281139 | 134 | py |
SwinMR | SwinMR-main/main_train_swinmr.py | '''
# -----------------------------------------
Main Program for Training
SwinMR for MRI_Recon
by Jiahao Huang (j.huang21@imperial.ac.uk)
# -----------------------------------------
'''
import os
import sys
import math
import argparse
import random
import cv2
import numpy as np
import logging
import time
import torch... | 15,434 | 43.353448 | 176 | py |
SwinMR | SwinMR-main/models/model_base.py | import os
import torch
import torch.nn as nn
from utils.utils_bnorm import merge_bn, tidy_sequential
from torch.nn.parallel import DataParallel, DistributedDataParallel
class ModelBase():
def __init__(self, opt):
self.opt = opt # opt
self.save_dir = opt['path']['models'] #... | 7,442 | 33.299539 | 148 | py |
SwinMR | SwinMR-main/models/select_network.py | '''
# -----------------------------------------
Define Training Network
by Jiahao Huang (j.huang21@imperial.ac.uk)
# -----------------------------------------
'''
import functools
import torch
import torchvision.models
from torch.nn import init
# --------------------------------------------
# Recon Generator, netG, ... | 5,220 | 35.006897 | 113 | py |
SwinMR | SwinMR-main/models/network_swinmr.py | '''
# -----------------------------------------
Network
SwinMR m.1.3
by Jiahao Huang (j.huang21@imperial.ac.uk)
Thanks:
https://github.com/JingyunLiang/SwinIR
https://github.com/microsoft/Swin-Transformer
# -----------------------------------------
'''
import math
import torch
import torch.nn as nn
import torch.nn.fu... | 41,096 | 41.631743 | 175 | py |
SwinMR | SwinMR-main/models/loss.py | import torch
import torch.nn as nn
import torchvision
from torch.nn import functional as F
from torch import autograd as autograd
import math
"""
Sequential(
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU(inplace)
(2*): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1... | 14,821 | 37.299742 | 150 | py |
SwinMR | SwinMR-main/models/network_feature.py | import torch
import torch.nn as nn
import torchvision
"""
# --------------------------------------------
# VGG Feature Extractor
# --------------------------------------------
"""
# --------------------------------------------
# VGG features
# Assume input range is [0, 1]
# ------------------------------------------... | 1,594 | 32.93617 | 93 | py |
SwinMR | SwinMR-main/models/basicblock.py | from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
'''
# --------------------------------------------
# Advanced nn.Sequential
# https://github.com/xinntao/BasicSR
# --------------------------------------------
'''
def sequential(*args):
"""Advanced nn.Sequent... | 24,138 | 39.775338 | 160 | py |
SwinMR | SwinMR-main/models/model_swinmr_pi.py | '''
# -----------------------------------------
Model
SwinMR (PI) m.1.3
by Jiahao Huang (j.huang21@imperial.ac.uk)
Thanks:
https://github.com/JingyunLiang/SwinIR
https://github.com/microsoft/Swin-Transformer
# -----------------------------------------
'''
from collections import OrderedDict
import torch
import torch.... | 14,836 | 39.649315 | 176 | py |
SwinMR | SwinMR-main/models/model_swinmr.py | '''
# -----------------------------------------
Model
SwinMR m.1.3
by Jiahao Huang (j.huang21@imperial.ac.uk)
Thanks:
https://github.com/JingyunLiang/SwinIR
https://github.com/microsoft/Swin-Transformer
# -----------------------------------------
'''
from collections import OrderedDict
import torch
import torch.nn as... | 14,546 | 39.520891 | 176 | py |
SwinMR | SwinMR-main/utils/utils_image.py | import os
import math
import random
import numpy as np
import torch
import cv2
from numpy import Inf
from torchvision.utils import make_grid
from datetime import datetime
# import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import skimage.metrics
import S... | 38,657 | 31.595278 | 120 | py |
SwinMR | SwinMR-main/utils/utils_dist.py | # Modified from https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/dist_utils.py # noqa: E501
import functools
import os
import subprocess
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
# ----------------------------------
# init
# ----------------------------------
def init... | 5,275 | 25.118812 | 102 | py |
SwinMR | SwinMR-main/utils/utils_swinmr.py | import torch
from torch import nn
import os
import cv2
import gc
import numpy as np
from scipy.io import *
from scipy.fftpack import *
"""
# --------------------------------------------
# Jiahao Huang (j.huang21@imperial.uk.ac)
# 30/Jan/2022
# --------------------------------------------
"""
# Fourier Transform
def... | 455 | 15.888889 | 46 | py |
SwinMR | SwinMR-main/utils/utils_model.py | # -*- coding: utf-8 -*-
import numpy as np
import torch
from utils import utils_image as util
import re
import glob
import os
'''
# --------------------------------------------
# Model
# --------------------------------------------
# Kai Zhang (github: https://github.com/cszn)
# 03/Mar/2019
# ------------------------... | 9,837 | 28.902736 | 148 | py |
SwinMR | SwinMR-main/utils/utils_regularizers.py | import torch
import torch.nn as nn
'''
# --------------------------------------------
# Kai Zhang (github: https://github.com/cszn)
# 03/Mar/2019
# --------------------------------------------
'''
# --------------------------------------------
# SVD Orthogonal Regularization
# --------------------------------------... | 3,416 | 31.542857 | 87 | py |
SwinMR | SwinMR-main/utils/utils_bnorm.py | import torch
import torch.nn as nn
"""
# --------------------------------------------
# Batch Normalization
# --------------------------------------------
# Kai Zhang (cskaizhang@gmail.com)
# https://github.com/cszn
# 01/Jan/2019
# --------------------------------------------
"""
# --------------------------------... | 3,132 | 33.054348 | 187 | py |
SwinMR | SwinMR-main/data/dataset_CCsagpi.py | '''
# -----------------------------------------
Data Loader
CC-SAG-PI d.1.1
by Jiahao Huang (j.huang21@imperial.ac.uk)
# -----------------------------------------
'''
import random
import torch.utils.data as data
import utils.utils_image as util
from utils.utils_swinmr import *
from models.select_mask import define_Ma... | 5,361 | 34.045752 | 116 | py |
SwinMR | SwinMR-main/data/dataset_CCsagnpi.py | '''
# -----------------------------------------
Data Loader
CC-SAG-NPI d.1.1
by Jiahao Huang (j.huang21@imperial.ac.uk)
# -----------------------------------------
'''
import random
import torch.utils.data as data
import utils.utils_image as util
from utils.utils_swinmr import *
from models.select_mask import define_M... | 4,898 | 32.554795 | 105 | py |
ShiftCNN | ShiftCNN-master/shiftcnn_quantization.py | import sys
import os
import numpy as np
import pickle
import matplotlib.pyplot as plt
#
N = 2
B = 4
#
#model = "squeezenet_v1.1"
model = "ResNet-50"
SOURCE_PATH = os.environ["HOME"]+"/github/caffe/models/"+model+"/"
prototxt = SOURCE_PATH+"train_val.prototxt"
source = SOURCE_PATH+model+".caffemodel"
qtarget = SOURCE... | 1,514 | 28.134615 | 120 | py |
agd | agd-main/main.py | import sys
import os
import math
import argparse
import pickle
import torch
import importlib
from tqdm import tqdm
from agd import AGD
from architecture.fcn import *
from architecture.vgg import *
from architecture.resnet import *
###############################################################################... | 8,893 | 41.966184 | 122 | py |
agd | agd-main/agd.py | import math
import torch
from torch.optim.optimizer import Optimizer
from torch.nn.init import orthogonal_
def singular_value(p):
sv = math.sqrt(p.shape[0] / p.shape[1])
if p.dim() == 4:
sv /= math.sqrt(p.shape[2] * p.shape[3])
return sv
class AGD(Optimizer):
def __init__(self, net, ... | 1,412 | 26.173077 | 81 | py |
agd | agd-main/architecture/fcn.py | import math
import torch.nn as nn
import torch.nn.functional as F
class FCN(nn.Module):
def __init__(self, depth, width, input_dim, output_dim, bias=False):
super(FCN, self).__init__()
self.initial = nn.Linear(input_dim, width, bias=bias)
self.layers = nn.ModuleList([nn.Linear(widt... | 718 | 28.958333 | 97 | py |
agd | agd-main/architecture/resnet.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
from typing import Any, Callable, List, Optional, Type, Union
import torch
import torch.nn as nn
from torch import Tensor
### For CIFAR-10
def PreActResNet18(output_dim): return PreActResNet(PreActBlock, ... | 14,531 | 35.512563 | 118 | py |
agd | agd-main/architecture/vgg.py | import torch.nn as nn
def VGG11(output_dim): return VGG_CIFAR([64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], output_dim)
def VGG13(output_dim): return VGG_CIFAR([64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], output_dim)
def VGG16(output_dim): return VGG_CIFAR([64, 64, 'M'... | 1,587 | 44.371429 | 156 | py |
agd | agd-main/latex/algorithm/agd.py | import math
import torch
from torch.nn.init import orthogonal_
def singular_value(p):
sv = math.sqrt(p.shape[0] / p.shape[1])
if p.dim() == 4:
sv /= math.sqrt(p.shape[2] * p.shape[3])
return sv
class AGD:
@torch.no_grad()
def __init__(self, net, gain=1.0):
self.net = net
... | 1,174 | 26.97619 | 77 | py |
agd | agd-main/data/cifar100.py | from torchvision import datasets, transforms
def getData():
mean = (0.5071, 0.4867, 0.4408)
std = (0.2675, 0.2565, 0.2761)
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Norm... | 764 | 27.333333 | 96 | py |
agd | agd-main/data/cifar10.py | from torchvision import datasets, transforms
def getData():
mean = (0.4914, 0.4822, 0.4465)
std = (0.2023, 0.1994, 0.2010)
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Norm... | 761 | 27.222222 | 95 | py |
agd | agd-main/data/imagenet.py | import os
from torchvision import datasets, transforms
def getData():
mean = (0.485, 0.456, 0.406)
std = (0.229, 0.224, 0.225)
traindir = os.path.join(os.getenv('IMAGENET_PATH'), "train")
valdir = os.path.join(os.getenv('IMAGENET_PATH'), "val")
trainset = datasets.ImageFolder(
traindir,
... | 887 | 25.117647 | 64 | py |
agd | agd-main/data/mnist.py | from torchvision import datasets, transforms
def getData():
mean = (0.1307,)
std = (0.3081,)
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean, std)
])
trainset = datasets.MNIST('./data', train=True, download=True, transform=transform)
testset =... | 493 | 25 | 87 | py |
aldiplusplus | aldiplusplus-main/aldi_gmm_dyn_none_both.py | from scipy import stats
import math
import torch
#import stumpy
import pyscamp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns
import calmap # not working with latest pandas
import calplot
import joypy
import sys
impo... | 43,203 | 36.865031 | 135 | py |
aldiplusplus | aldiplusplus-main/vae.py | import torch
from torch import nn
from torch.utils.data import DataLoader
class VAE(nn.Module):
def __init__(self, num_input, latent_dim, hidden_size=[300, 200, 100]):
super().__init__()
self.latent_dim = latent_dim
self.num_input = num_input
self.encoder = nn.Sequential(
... | 1,984 | 30.015625 | 75 | py |
aldiplusplus | aldiplusplus-main/anomaly_detection.py | import warnings
import os
import sys
import logging
import yaml
import wandb
import torch
import pandas as pd
from sklearn.cluster import SpectralClustering, KMeans
from sklearn.metrics import silhouette_score
from datetime import timedelta
from collections import Counter
from matplotlib import pyplot as plt
from util... | 7,508 | 37.116751 | 210 | py |
pytorch_RVAE | pytorch_RVAE-master/sample.py | import argparse
import os
import numpy as np
import torch as t
from utils.batch_loader import BatchLoader
from utils.parameters import Parameters
from model.rvae import RVAE
if __name__ == '__main__':
assert os.path.exists('trained_RVAE'), \
'trained model not found'
parser = argparse.ArgumentParse... | 1,265 | 31.461538 | 78 | py |
pytorch_RVAE | pytorch_RVAE-master/train_word_embeddings.py | import argparse
import numpy as np
import torch as t
from torch.autograd import Variable
from torch.optim import SGD
from utils.batch_loader import BatchLoader
from utils.parameters import Parameters
from selfModules.neg import NEG_loss
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='wo... | 2,183 | 36.016949 | 116 | py |
pytorch_RVAE | pytorch_RVAE-master/train.py | import argparse
import os
import numpy as np
import torch as t
from torch.optim import Adam
from utils.batch_loader import BatchLoader
from utils.parameters import Parameters
from model.rvae import RVAE
if __name__ == "__main__":
if not os.path.exists('data/word_embeddings.npy'):
raise FileNotFoundError... | 4,032 | 37.04717 | 102 | py |
pytorch_RVAE | pytorch_RVAE-master/selfModules/embedding.py | import numpy as np
import torch as t
import torch.nn as nn
from torch.nn import Parameter
from .tdnn import TDNN
class Embedding(nn.Module):
def __init__(self, params, path='../../../'):
super(Embedding, self).__init__()
self.params = params
word_embed = np.load(path + 'data/word_embedd... | 2,001 | 37.5 | 98 | py |
pytorch_RVAE | pytorch_RVAE-master/selfModules/highway.py | import torch.nn as nn
import torch.nn.functional as F
class Highway(nn.Module):
def __init__(self, size, num_layers, f):
super(Highway, self).__init__()
self.num_layers = num_layers
self.nonlinear = [nn.Linear(size, size) for _ in range(num_layers)]
for i, module in enumerate(se... | 1,743 | 33.88 | 105 | py |
pytorch_RVAE | pytorch_RVAE-master/selfModules/neg.py | import torch as t
import torch.nn as nn
from torch.autograd import Variable
from torch.nn import Parameter
from utils.functional import *
class NEG_loss(nn.Module):
def __init__(self, num_classes, embed_size):
"""
:param num_classes: An int. The number of possible classes.
:param embed_si... | 2,619 | 37.529412 | 118 | py |
pytorch_RVAE | pytorch_RVAE-master/selfModules/tdnn.py | import torch as t
from torch.nn import Parameter
import torch.nn as nn
import torch.nn.functional as F
class TDNN(nn.Module):
def __init__(self, params):
super(TDNN, self).__init__()
self.params = params
self.kernels = [Parameter(t.Tensor(out_dim, self.params.char_embed_size, kW).uniform... | 1,769 | 33.038462 | 117 | py |
pytorch_RVAE | pytorch_RVAE-master/utils/functional.py | def fold(f, l, a):
return a if (len(l) == 0) else fold(f, l[1:], f(a, l[0]))
def f_and(x, y):
return x and y
def f_or(x, y):
return x or y
def parameters_allocation_check(module):
parameters = list(module.parameters())
return fold(f_and, parameters, True) or not fold(f_or, parameters, False)
... | 648 | 19.28125 | 77 | py |
pytorch_RVAE | pytorch_RVAE-master/model/rvae.py | import numpy as np
import torch as t
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from .decoder import Decoder
from .encoder import Encoder
from selfModules.embedding import Embedding
from utils.functional import kld_coef, parameters_allocation_check, fold
class RVAE(nn... | 7,319 | 38.567568 | 119 | py |
pytorch_RVAE | pytorch_RVAE-master/model/encoder.py | import torch as t
import torch.nn as nn
import torch.nn.functional as F
from selfModules.highway import Highway
from utils.functional import parameters_allocation_check
class Encoder(nn.Module):
def __init__(self, params):
super(Encoder, self).__init__()
self.params = params
self.hw1 = ... | 1,685 | 34.125 | 115 | py |
pytorch_RVAE | pytorch_RVAE-master/model/decoder.py | import torch as t
import torch.nn as nn
import torch.nn.functional as F
from utils.functional import parameters_allocation_check
class Decoder(nn.Module):
def __init__(self, params):
super(Decoder, self).__init__()
self.params = params
self.rnn = nn.LSTM(input_size=self.params.latent_va... | 2,142 | 39.433962 | 103 | py |
semantic-abstraction | semantic-abstraction-main/generate_relevancy.py | from typing import List
from pathlib import Path
import h5py
import torch
from tqdm import tqdm
import ray
from utils import write_to_hdf5
from filelock import FileLock
import numpy as np
from CLIP.clip import ClipWrapper, saliency_configs, imagenet_templates
from dataset import synonyms, deref_h5py
import typer
import... | 18,591 | 39.77193 | 88 | py |
semantic-abstraction | semantic-abstraction-main/train_vool.py | from typing import Dict, Tuple, Union
import numpy as np
from dataset import ObjectLocalizationDataset
from net import (
SemAbsVOOL,
ClipSpatialVOOL,
SemanticAwareVOOL,
)
import utils
from torch.nn.functional import binary_cross_entropy_with_logits
import torch
import pandas as pd
def get_detailed_stats(
... | 8,243 | 34.230769 | 88 | py |
semantic-abstraction | semantic-abstraction-main/utils.py | from __future__ import annotations
import os
import pickle
import signal
from typing import Optional, Tuple, Type
import numpy as np
import pandas as pd
import torch
from torch.backends import cudnn
from tqdm import tqdm
from transformers import get_scheduler
from argparse import ArgumentParser
import random
from CLIP.... | 27,394 | 35.526667 | 88 | py |
semantic-abstraction | semantic-abstraction-main/dataset.py | import numpy as np
import torch
from torch.utils.data import Dataset
from fusion import TSDFVolume
from point_cloud import (
check_pts_in_frustum,
filter_pts_bounds,
get_pointcloud,
)
from typing import List, Optional, Tuple
import h5py
from transforms3d import affines, euler
from torchtyping import TensorT... | 52,891 | 41.689266 | 138 | py |
semantic-abstraction | semantic-abstraction-main/net.py | from typing import List, Tuple
import torch
from torch.nn import (
Sequential,
LeakyReLU,
Linear,
Module,
Dropout,
ParameterDict,
)
from torch.nn.parameter import Parameter
from torch.nn.functional import grid_sample
from torch_scatter import scatter
import numpy as np
from unet3d import Residua... | 25,154 | 36.047128 | 88 | py |
semantic-abstraction | semantic-abstraction-main/eval.py | import pandas as pd
import numpy as np
from tqdm import tqdm
import torch
import os
import pickle
from dataset import ObjectLocalizationDataset, SceneCompletionDataset
from train_vool import get_losses as vool_get_losses, approach as vool_approaches
from train_ovssc import get_losses as ovssc_get_losses, approach as ov... | 3,625 | 37.574468 | 86 | py |
semantic-abstraction | semantic-abstraction-main/unet3d.py | """
Code from the 3D UNet implementation:
https://github.com/wolny/pytorch-3dunet/
"""
import importlib
import torch
import torch.nn as nn
from torch.nn import functional as F
from functools import partial
def number_of_features_per_level(init_channel_number, num_levels):
return [init_channel_number * 2**k for k ... | 25,729 | 36.289855 | 144 | py |
semantic-abstraction | semantic-abstraction-main/visualize.py | import io
import logging
from pathlib import Path
import textwrap
from typing import Any, Dict, List, Tuple
from skimage.measure import marching_cubes
import numpy as np
import torch
import os
import pickle
from net import SemAbs3D, SemAbsVOOL
from point_cloud import (
check_pts_in_frustum,
filter_pts_bounds,
... | 23,057 | 35.084507 | 110 | py |
semantic-abstraction | semantic-abstraction-main/train_ovssc.py | import numpy as np
import torch
from torch.nn.functional import binary_cross_entropy_with_logits
from net import SemAbs3D, SemanticAwareOVSSC
import utils
import pandas as pd
from dataset import SceneCompletionDataset
from typing import Dict, Tuple, Union
def get_detailed_stats(
prediction,
gt_label,
xyz_... | 6,693 | 32.808081 | 87 | py |
semantic-abstraction | semantic-abstraction-main/generate_thor_data.py | import logging
import re
from copy import deepcopy
import shutil
from argparse import ArgumentParser
from typing import List
import ray
from ai2thor.controller import Controller
from ai2thor.platform import CloudRendering
from matplotlib import pyplot as plt
import numpy as np
import torch
from transforms3d import aff... | 46,662 | 37.405761 | 91 | py |
semantic-abstraction | semantic-abstraction-main/arm/utils.py | # Adapted from: https://github.com/stepjam/ARM/blob/main/arm/utils.py
import torch
import numpy as np
from scipy.spatial.transform import Rotation
import pyrender
import trimesh
from pyrender.trackball import Trackball
def normalize_quaternion(quat):
return np.array(quat) / np.linalg.norm(quat, axis=-1, keepdim... | 7,072 | 32.842105 | 88 | py |
semantic-abstraction | semantic-abstraction-main/arm/network_utils.py | # Adapted from https://github.com/stepjam/ARM/blob/main/arm/network_utils.py
import copy
from typing import List, Union
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
LRELU_SLOPE = 0.02
def act_layer(act):
if act == "relu":
return nn.ReLU()
elif act == "lrelu"... | 23,208 | 30.363514 | 88 | py |
semantic-abstraction | semantic-abstraction-main/arm/optim/lamb.py | # From https://github.com/cybertronai/pytorch-lamb/blob/master/pytorch_lamb/lamb.py
"""Lamb optimizer."""
import collections
import math
import torch
from torch.optim import Optimizer
# def log_lamb_rs(optimizer: Optimizer, event_writer: SummaryWriter, token_count: int):
# """Log a histogram of trust ratio sca... | 5,163 | 39.34375 | 103 | py |
semantic-abstraction | semantic-abstraction-main/CLIP/clip/clip_explainability.py | # modified from: https://github.com/hila-chefer/Transformer-MM-Explainability/blob/main/CLIP/clip/clip.py
import hashlib
import os
import urllib
import warnings
from typing import Any, Union, List
from pkg_resources import packaging
import torch
from PIL import Image
from torchvision.transforms import Compose, Resize... | 9,663 | 34.270073 | 154 | py |
semantic-abstraction | semantic-abstraction-main/CLIP/clip/auxiliary.py | # adding hooks, copied from: https://github.com/hila-chefer/Transformer-MM-Explainability/blob/e63b4ab0d0722faa11ff2f7549c4f88074e7edd7/CLIP/clip/auxilary.py
import torch
import warnings
from typing import Tuple, Optional
import torch
from torch import Tensor
from torch.nn.init import xavier_uniform_
from torch.nn.ini... | 21,829 | 38.981685 | 157 | py |
semantic-abstraction | semantic-abstraction-main/CLIP/clip/clip.py | import hashlib
import os
import urllib
import warnings
from typing import Any, Union, List
import torch
from PIL import Image
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
from tqdm import tqdm
from .model import build_model
from .simple_tokenizer import SimpleTokenizer as _Token... | 9,497 | 33.791209 | 154 | py |
semantic-abstraction | semantic-abstraction-main/CLIP/clip/model.py | from collections import OrderedDict
from typing import Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from .auxiliary import interpolate_positional_emb
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1):
super(... | 20,260 | 33.457483 | 112 | py |
semantic-abstraction | semantic-abstraction-main/CLIP/clip/clip_gradcam.py | from typing import List
import torch
import torch.nn as nn
from .clip_explainability import load
from .clip import tokenize
from torch import device
import numpy as np
import torch.nn.functional as nnf
import itertools
def zeroshot_classifier(clip_model, classnames, templates, device):
with torch.no_grad():
... | 5,420 | 36.909091 | 165 | py |
semantic-abstraction | semantic-abstraction-main/CLIP/clip/__init__.py | from .clip import *
from .clip_gradcam import ClipGradcam
import torch
import numpy as np
from PIL import Image
import torchvision
from functools import reduce
def factors(n):
return set(
reduce(
list.__add__,
([i, n // i] for i in range(1, int(n**0.5) + 1) if n % i == 0),
... | 12,890 | 33.934959 | 88 | py |
semantic-abstraction | semantic-abstraction-main/CLIP/clip/model_explainability.py | # modified from: https://github.com/hila-chefer/Transformer-MM-Explainability/blob/main/CLIP/clip/model.py
from collections import OrderedDict
from typing import Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from .auxiliary import (
multi_head_attention_forward,
... | 20,409 | 32.84743 | 112 | py |
semantic-abstraction | semantic-abstraction-main/CLIP/tests/test_consistency.py | import numpy as np
import pytest
import torch
from PIL import Image
import clip
@pytest.mark.parametrize("model_name", clip.available_models())
def test_consistency(model_name):
device = "cpu"
jit_model, transform = clip.load(model_name, device=device, jit=True)
py_model, _ = clip.load(model_name, device... | 812 | 30.269231 | 73 | py |
UniVL | UniVL-main/main_task_retrieval.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import torch
from torch.utils.data import (SequentialSampler)
import numpy as np
import random
import os
from metrics import compute_metrics
import time
import argparse
f... | 24,353 | 46.28932 | 144 | py |
UniVL | UniVL-main/main_pretrain.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import torch
from torch.utils.data import (SequentialSampler)
import numpy as np
import random
import os
from collections import OrderedDict
import pickle
import time
imp... | 19,914 | 47.691932 | 140 | py |
UniVL | UniVL-main/main_task_caption.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import torch
from torch.utils.data import (SequentialSampler)
import numpy as np
import random
import os
from collections import OrderedDict
from nlgeval import NLGEval
i... | 33,617 | 47.792453 | 151 | py |
UniVL | UniVL-main/util.py | import torch
import torch.nn as nn
import threading
from torch._utils import ExceptionWrapper
import logging
def get_a_var(obj):
if isinstance(obj, torch.Tensor):
return obj
if isinstance(obj, list) or isinstance(obj, tuple):
for result in map(get_a_var, obj):
if isinstance(result,... | 2,495 | 33.191781 | 99 | py |
UniVL | UniVL-main/modules/module_visual.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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... | 19,708 | 45.374118 | 139 | py |
UniVL | UniVL-main/modules/optimization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
#
# 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/LICENS... | 7,260 | 42.220238 | 141 | py |
UniVL | UniVL-main/modules/module_decoder.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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... | 18,283 | 43.923833 | 138 | py |
UniVL | UniVL-main/modules/modeling.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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... | 22,558 | 51.707944 | 153 | py |
UniVL | UniVL-main/modules/until_module.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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... | 10,299 | 39.873016 | 114 | py |
UniVL | UniVL-main/modules/beam.py | """
Manage beam search info structure.
Heavily borrowed from OpenNMT-py.
For code in OpenNMT-py, please check the following link (maybe in oldest version):
https://github.com/OpenNMT/OpenNMT-py/blob/master/onmt/Beam.py
"""
import torch
class Constants():
def __init__(self):
self.PAD = 0
self.UNK =... | 3,840 | 31.82906 | 97 | py |
UniVL | UniVL-main/modules/module_bert.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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... | 21,157 | 46.333333 | 139 | py |
UniVL | UniVL-main/modules/module_cross.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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... | 17,516 | 43.346835 | 108 | py |
UniVL | UniVL-main/modules/file_utils.py | """
Utilities for working with the local dataset cache.
This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp
Copyright by the AllenNLP authors.
"""
import os
import logging
import shutil
import tempfile
import json
from urllib.parse import urlparse
from pathlib import Path
from typing ... | 8,021 | 32.425 | 98 | py |
UniVL | UniVL-main/modules/until_config.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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... | 5,036 | 38.97619 | 105 | py |
UniVL | UniVL-main/dataloaders/dataloader_msrvtt_caption.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import os
from torch.utils.data import Dataset
import numpy as np
import pickle
import pandas as pd
from collections import defaultdict
import json
import random
class M... | 10,371 | 44.095652 | 115 | py |
UniVL | UniVL-main/dataloaders/dataloader_youcook_retrieval.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from torch.utils.data import Dataset
import pandas as pd
import os
import numpy as np
import pickle
import random
class Youcook_DataLoader(Dataset):
"""Youcook datas... | 7,820 | 40.163158 | 113 | py |
UniVL | UniVL-main/dataloaders/dataloader_youcook_caption.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from torch.utils.data import Dataset
import pandas as pd
import os
import numpy as np
import pickle
import re
import random
import io
class Youcook_Caption_DataLoader(Da... | 9,662 | 41.756637 | 113 | py |
UniVL | UniVL-main/dataloaders/dataloader_msrvtt_retrieval.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import os
from torch.utils.data import Dataset
import numpy as np
import pickle
import pandas as pd
from collections import defaultdict
import json
import random
class M... | 15,263 | 42.240793 | 113 | py |
UniVL | UniVL-main/dataloaders/dataloader_howto100m.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from torch.utils.data import Dataset
import pandas as pd
import os
import numpy as np
import random
class Youtube_DataLoader(Dataset):
"""
Youtube dataset loader... | 15,835 | 41.8 | 127 | py |
nuts-ml | nuts-ml-master/nutsml/network.py | """
.. module:: network
:synopsis: Wrapper around other network APIs such as Lasagne, Keras and
Pytorch to enable usage within nuts-flow/ml.
For instance, with a wrapped network one can write:
samples >> build_batch >> network.train() >> log_loss >> Consume()
"""
from __futu... | 19,583 | 36.302857 | 100 | py |
nuts-ml | nuts-ml-master/nutsml/examples/pytorch_/mnist/cnn_train.py | """
.. module:: cnn_train
:synopsis: Example nuts-ml pipeline for training a CNN on MNIST
"""
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
import nutsflow as nf
import nutsml as nm
import numpy as np
from nutsml.network import PytorchNetwork
from utils import downl... | 5,025 | 30.810127 | 79 | py |
nuts-ml | nuts-ml-master/nutsml/examples/pytorch_/mnist/mlp_train.py | """
.. module:: cnn_train
:synopsis: Example nuts-ml pipeline for training a MLP on MNIST
"""
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
import nutsflow as nf
import nutsml as nm
import numpy as np
from nutsml.network import PytorchNetwork
from utils import downl... | 2,959 | 30.157895 | 76 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.