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 |
|---|---|---|---|---|---|---|
meta-sgld | meta-sgld-master/src/algo/meta_sgld.py | #!/usr/bin/env python
# -*- coding=utf8 -*-
"""
# Author: qi.chen.1@ulaval.ca
# Created Time : Sat May 15 16:54:57 2021
# File Name: meta_sgld.py
# Description:
"""
from __future__ import absolute_import,division, print_function
import torch
from torch import nn
from torch import optim
from torch.nn import fu... | 22,843 | 45.525458 | 166 | py |
meta-sgld | meta-sgld-master/src/main/omniglot_train.py | import torch, os
import numpy as np
from src.utils.omniglotNShot import OmniglotNShot
import argparse
from scipy.special import comb
from src.algo.meta_sgld import Meta
def main(args):
print(args)
config = [
('conv2d', [64, 1, 3, 3, 2, 0]),
('relu', [True]),
('bn', [64]),
... | 5,409 | 47.303571 | 169 | py |
meta-sgld | meta-sgld-master/src/main/toy_exp/toy_amit.py |
from __future__ import absolute_import, division, print_function
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.patches import Ellipse
import torch
import torch.optim as optim
def learn(data_set, complexity_type):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
... | 3,795 | 35.854369 | 112 | py |
meta-sgld | meta-sgld-master/src/main/toy_exp/toy_maml.py | #!/usr/bin/env python
# -*- coding=utf8 -*-
"""
# Author: qi.chen.1@ulaval.ca
# Created Time : Sat May 15 16:54:57 2021
# File Name: toy_maml.py
# Description:
"""
from __future__ import absolute_import,division, print_function
import torch, os
import numpy as np
import argparse
from matplotlib import pyplot as plt
... | 7,096 | 45.084416 | 197 | py |
CReFF-FL | CReFF-FL-main/main.py | from torchvision import datasets
from torchvision.transforms import ToTensor, transforms
from options import args_parser
from Dataset.long_tailed_cifar10 import train_long_tail
from Dataset.dataset import classify_label, show_clients_data_distribution, Indices2Dataset, TensorDataset, get_class_num
from Dataset.sample_d... | 17,111 | 48.6 | 141 | py |
CReFF-FL | CReFF-FL-main/Model/Resnet8.py | from torchvision.models import resnet18, resnet34, resnet50, resnet101, resnet152
from torch.nn import Module, Conv2d, Linear, MaxPool2d
import math
import torch.nn as nn
import copy
import torch
class ResNetBase(nn.Module):
def _decide_num_classes(self):
if self.dataset == "cifar10" or self.dataset == "sv... | 8,690 | 26.590476 | 109 | py |
CReFF-FL | CReFF-FL-main/Model/ResNet50.py | import torch
import torch.nn as nn
import torchvision
import numpy as np
__all__ = ['ResNet50', 'ResNet101','ResNet152']
def Conv1(in_planes, places, stride=2):
return nn.Sequential(
nn.Conv2d(in_channels=in_planes,out_channels=places,kernel_size=7,stride=stride,padding=3, bias=False),
nn.BatchNor... | 3,735 | 31.486957 | 127 | py |
CReFF-FL | CReFF-FL-main/Dataset/param_aug.py | import numpy as np
import torch
import torch.nn.functional as F
class ParamDiffAug():
def __init__(self):
self.aug_mode = 'S' #'multiple or single'
self.prob_flip = 0.5
self.ratio_scale = 1.2
self.ratio_rotate = 15.0
self.ratio_crop_pad = 0.125
self.ratio_cutout = 0... | 6,262 | 33.60221 | 110 | py |
CReFF-FL | CReFF-FL-main/Dataset/dataset.py | import numpy as np
from torch.utils.data.dataset import Dataset
import copy
def classify_label(dataset, num_classes: int):
list1 = [[] for _ in range(num_classes)]
for idx, datum in enumerate(dataset):
list1[datum[1]].append(idx)
return list1
def show_clients_data_distribution(dataset, clients... | 2,467 | 25.537634 | 80 | py |
CReFF-FL | CReFF-FL-main/Dataset/Gradient_matching_loss.py | import torch
def match_loss(gw_syn, gw_real, args):
dis = torch.tensor(0.0).to(args.device)
if args.dis_metric == 'ours':
for ig in range(len(gw_real)):
gwr = gw_real[ig]
gws = gw_syn[ig]
dis += distance_wb(gwr, gws)
elif args.dis_metric == 'mse':
gw_r... | 2,024 | 32.75 | 141 | py |
CReFF-FL | CReFF-FL-main/Dataset/ImageNet_LT.py | import torch
import random
import numpy as np
import os
import sys
from torchvision import datasets, transforms
from torch.utils.data import DataLoader, Dataset, Sampler
from PIL import Image
class LT_Dataset(Dataset):
def __init__(self, root, txt, transform=None):
self.img_path = []
self.labels =... | 3,205 | 32.747368 | 93 | py |
sota-backbones | sota-backbones-main/finetune.py | import torch
import yaml
import argparse
import time
from pathlib import Path
from rich.console import Console
from rich.table import Table
from torchvision.datasets import *
from torch.utils.data import DataLoader
from torch.optim import AdamW
from torch.optim.lr_scheduler import StepLR
from torch.cuda.amp import Grad... | 5,026 | 35.963235 | 165 | py |
sota-backbones | sota-backbones-main/infer.py | import torch
import argparse
from pathlib import Path
from torchvision import io
from torchvision import transforms as T
from models import *
from datasets import ImageNet
class ModelInference:
def __init__(self, model: str, variant: str, checkpoint: str, size: int) -> None:
self.device = torch.device('cu... | 2,192 | 35.55 | 126 | py |
sota-backbones | sota-backbones-main/convert/infer_pt.py | import torch
import time
import argparse
from torchvision import io
from torchvision import transforms as T
import sys
sys.path.insert(0, '.')
from models import *
from datasets import ImageNet
class ModelInference:
def __init__(self, model: str, variant: str, checkpoint: str, size: list, device:str) -> None:
... | 2,528 | 35.128571 | 126 | py |
sota-backbones | sota-backbones-main/convert/to_onnx.py | import torch
import onnx
import argparse
from pathlib import Path
from onnxsim import simplify
import sys
sys.path.insert(0, '.')
from models import *
def convert(model, variant, num_classes, checkpoint, size):
# create random input and initialize model
inputs = torch.randn(1, 3, *size)
pt_model = eva... | 1,570 | 29.803922 | 126 | py |
sota-backbones | sota-backbones-main/convert/to_tflite.py | import os
import torch
import onnx
import argparse
import shutil
from pathlib import Path
from onnxsim import simplify
import sys
sys.path.insert(0, '.')
from models import *
def convert(model, variant, num_classes, checkpoint, size, precision):
# create random input and initialize model
inputs = torch.randn(... | 2,637 | 32.392405 | 157 | py |
sota-backbones | sota-backbones-main/convert/to_coreml.py | import torch
import argparse
import coremltools as ct
from pathlib import Path
import sys
sys.path.insert(0, '.')
from models import *
def convert(model, variant, num_classes, checkpoint, size):
"""
Warning!!!! CoreML conversion will not work on Windows
"""
# create random input and initialize model
... | 1,476 | 31.108696 | 126 | py |
sota-backbones | sota-backbones-main/convert/to_openvino.py | import os
import torch
import onnx
import argparse
from pathlib import Path
from onnxsim import simplify
import sys
sys.path.insert(0, '.')
from models import *
def convert(model, variant, num_classes, checkpoint, size, precision):
# create random input and initialize model
inputs = torch.randn(1, 3, *size) ... | 2,068 | 30.348485 | 126 | py |
sota-backbones | sota-backbones-main/models/pvt.py | import torch
from torch import nn, Tensor
from .layers import DropPath
class DWConv(nn.Module):
def __init__(self, dim):
super().__init__()
self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, groups=dim)
def forward(self, x: Tensor, H: int, W: int) -> Tensor:
B, _, C = x.shape
x = x.tr... | 7,222 | 34.406863 | 121 | py |
sota-backbones | sota-backbones-main/models/rest.py | import torch
from torch import nn, Tensor
from .layers import MLP, DropPath, trunc_normal_
class Attention(nn.Module):
def __init__(self, dim, head, sr_ratio=1):
super().__init__()
self.head = head
self.sr_ratio = sr_ratio
self.scale = (dim // head) ** -0.5
self.q = nn.Li... | 7,307 | 32.218182 | 120 | py |
sota-backbones | sota-backbones-main/models/patchconvnet.py | import torch
from torch import nn, Tensor
from .layers import DropPath
class MLP(nn.Module):
def __init__(self, dim, hidden_dim, out_dim=None) -> None:
super().__init__()
out_dim = out_dim or dim
self.fc1 = nn.Linear(dim, hidden_dim)
self.act = nn.GELU()
self.fc2 = nn.Linea... | 7,466 | 33.410138 | 135 | py |
sota-backbones | sota-backbones-main/models/davit.py | import torch
import math
import itertools
from torch import nn, Tensor
from torch.nn import functional as F
from layers import DropPath, trunc_normal_
def window_partition(x, window_size: int):
B, H, W, C = x.shape
x = x.view(B, H//window_size, window_size, W//window_size, window_size, C)
windows = x.perm... | 10,898 | 34.045016 | 120 | py |
sota-backbones | sota-backbones-main/models/micronet.py | import torch
from torch import nn, Tensor
class HSigmoid(nn.Module):
def __init__(self):
super().__init__()
self.relu = nn.ReLU6(True)
def forward(self, x: Tensor) -> Tensor:
return self.relu(x + 3) / 6
class HSwish(nn.Module):
def __init__(self):
super().__init__()
... | 13,166 | 34.779891 | 158 | py |
sota-backbones | sota-backbones-main/models/resnet.py | import torch
import torch.nn as nn
from torch import Tensor
from typing import Type, Optional, Union
class BasicBlock(nn.Module):
expansion: int = 1
def __init__(self, in_ch: int, out_ch: int, s: int = 1, downsample: Optional[nn.Module] = None) -> None:
super().__init__()
self.conv1 = nn.Con... | 5,330 | 31.907407 | 125 | py |
sota-backbones | sota-backbones-main/models/layers.py | import torch
import math
import warnings
from torch import nn, Tensor
class MLP(nn.Module):
def __init__(self, dim, hidden_dim, out_dim=None) -> None:
super().__init__()
out_dim = out_dim or dim
self.fc1 = nn.Linear(dim, hidden_dim)
self.act = nn.GELU()
self.fc2 = nn.Linear... | 4,566 | 38.37069 | 108 | py |
sota-backbones | sota-backbones-main/models/wavemlp.py | import torch
from torch import nn, Tensor
from torch.nn import functional as F
from .layers import DropPath, trunc_normal_
class MLP(nn.Module):
def __init__(self, dim, hidden_dim, out_dim=None) -> None:
super().__init__()
out_dim = out_dim or dim
self.fc1 = nn.Conv2d(dim, hidden_dim, 1)
... | 7,170 | 34.5 | 131 | py |
sota-backbones | sota-backbones-main/models/cswin.py | import torch
import math
from torch import nn, Tensor
from einops.layers.torch import Rearrange
from einops import rearrange
from .layers import MLP, DropPath, trunc_normal_
class LePEAttention(nn.Module):
def __init__(self, dim, resolution, idx, split_size=7, head=8):
super().__init__()
self.scal... | 7,399 | 35.097561 | 126 | py |
sota-backbones | sota-backbones-main/models/focalnet.py | import torch
import math
from torch import nn, Tensor
from .layers import DropPath, trunc_normal_
class MLP(nn.Module):
def __init__(self, dim, hidden_dim, out_dim=None) -> None:
super().__init__()
out_dim = out_dim or dim
self.fc1 = nn.Linear(dim, hidden_dim)
self.act = nn.GELU()
... | 7,594 | 34.325581 | 218 | py |
sota-backbones | sota-backbones-main/models/convnext.py | import torch
from torch import nn, Tensor
from .layers import DropPath
class LayerNorm(nn.Module):
"""Channel first layer norm
"""
def __init__(self, normalized_shape, eps=1e-6) -> None:
super().__init__()
self.weight = nn.Parameter(torch.ones(normalized_shape))
self.bias = nn.Para... | 5,433 | 33.611465 | 123 | py |
sota-backbones | sota-backbones-main/models/van.py | import torch
import math
from torch import nn, Tensor
from .layers import DropPath, trunc_normal_
class DWConv(nn.Module):
def __init__(self, dim=768) -> None:
super().__init__()
self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, groups=dim)
def forward(self, x: Tensor) -> Tensor:
return self... | 6,788 | 34.731579 | 120 | py |
sota-backbones | sota-backbones-main/models/poolformer.py | import torch
from torch import nn, Tensor
from .layers import DropPath
class PatchEmbed(nn.Module):
"""Image to Patch Embedding with overlapping
"""
def __init__(self, patch_size=16, stride=16, padding=0, in_ch=3, embed_dim=768):
super().__init__()
self.proj = nn.Conv2d(in_ch, embed_dim, p... | 5,718 | 36.379085 | 129 | py |
sota-backbones | sota-backbones-main/models/uniformer.py | import torch
from torch import nn, Tensor
from .layers import MLP, DropPath
class CMLP(nn.Module):
def __init__(self, dim, hidden_dim, out_dim=None) -> None:
super().__init__()
out_dim = out_dim or dim
self.fc1 = nn.Conv2d(dim, hidden_dim, 1)
self.act = nn.GELU()
self.fc2 =... | 6,901 | 34.214286 | 129 | py |
sota-backbones | sota-backbones-main/datasets/__init__.py | import os
import torch.distributed as dist
from torch.utils.data import SequentialSampler, DistributedSampler, RandomSampler
from .imagenet import ImageNet
from torchvision import datasets, transforms as T
def get_sampler(ddp, train_dataset, val_dataset):
if not ddp:
train_sampler = RandomSampler(train_da... | 1,207 | 36.75 | 111 | py |
sota-backbones | sota-backbones-main/datasets/imagenet.py | from torchvision.datasets import ImageFolder
from typing import Optional, Callable
from pathlib import Path
class ImageNet(ImageFolder):
WNIDS = ['n01440764', 'n01443537', 'n01484850', 'n01491361', 'n01494475', 'n01496331', 'n01498041', 'n01514668', 'n01514859', 'n01518878', 'n01530575', 'n01531178', 'n... | 38,564 | 1,376.321429 | 24,689 | py |
sota-backbones | sota-backbones-main/datasets/transforms.py | import random
import torch
from torchvision import transforms as T
def get_train_transforms(size):
return T.Compose([
T.RandomResizedCrop(size),
T.RandomHorizontalFlip(),
T.ColorJitter(0.1, 0.1, 0.1),
T.AutoAugment(),
T.ToTensor(),
T.Normalize([0.485, 0.456, 0.406],... | 2,739 | 31.235294 | 103 | py |
sota-backbones | sota-backbones-main/utils/losses.py | import torch
from torch import nn, Tensor
from typing import Union
from torch.nn import CrossEntropyLoss
class LabelSmoothCrossEntropy(nn.Module):
def __init__(self, smoothing=0.1):
super().__init__()
assert smoothing < 1.0
self.smoothing = smoothing
self.confidence = 1. - smoothin... | 3,516 | 33.145631 | 150 | py |
sota-backbones | sota-backbones-main/utils/utils.py | import torch
import numpy as np
import random
import time
import os
from pathlib import Path
from torch.backends import cudnn
from torch import nn, Tensor
from torch.autograd import profiler
from typing import Union
from torch import distributed as dist
from rich.progress import Progress, BarColumn, TextColumn, TimeRem... | 3,590 | 31.351351 | 169 | py |
sota-backbones | sota-backbones-main/utils/metrics.py | import torch
class AverageMeter:
def __init__(self) -> None:
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg... | 686 | 24.444444 | 91 | py |
clutr | clutr-main/arguments.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import torch
from util import str2bool
parser = argparse.ArgumentParser(description='RL')
# PPO & o... | 18,462 | 29.316913 | 131 | py |
clutr | clutr-main/eval.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import sys
import os
import csv
import json
import argparse
import fnmatch
import re
from collections import defaultdict
... | 14,998 | 27.353497 | 112 | py |
clutr | clutr-main/train.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import sys
import os
import time
import timeit
import logging
from arguments import parser
import torch
import gym
impor... | 10,100 | 38.303502 | 119 | py |
clutr | clutr-main/envs/wrappers/car_racing_wrappers.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from collections import deque
import numpy as np
import torch
import gym
from .vec_env import VecEnvWrapper
class Car... | 4,471 | 20.708738 | 79 | py |
clutr | clutr-main/envs/wrappers/obs_wrappers.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
import gym
from .vec_env import VecEnvWrapper
class AdversarialObservationWrapper(gym.... | 17,647 | 27.931148 | 91 | py |
clutr | clutr-main/envs/multigrid/adversarial.py | # coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | 40,981 | 36.736648 | 130 | py |
clutr | clutr-main/envs/runners/adversarial_runner.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
from collections import deque, defaultdict
import numpy as np
import torch
from baselines.common.running_mean_... | 37,953 | 40.209555 | 157 | py |
clutr | clutr-main/envs/box2d/car_racing_adversarial.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import sys
import math
import random
import numpy as np
import gym
from gym.envs.box2d.car_dynamics import Car
from envs... | 15,189 | 28.043977 | 108 | py |
clutr | clutr-main/models/car_racing_models.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Bet... | 24,250 | 27.463615 | 98 | py |
clutr | clutr-main/models/distributions.py | # Copyright (c) 2017 Roberta Raileanu
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
#
# This file is a modified version of:
# https://github.com/rraileanu/auto-drac/blob/master... | 1,381 | 23.245614 | 74 | py |
clutr | clutr-main/models/multigrid_global_critic_models.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .distributions import Categor... | 7,487 | 32.428571 | 105 | py |
clutr | clutr-main/models/popart.py | # Copyright (c) 2020 Tianshou contributors
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
#
# This file is a modified version of
# https://github.com/marlbenchmark/on-policy/blob... | 3,944 | 36.932692 | 126 | py |
clutr | clutr-main/models/common.py | # Copyright (c) 2017 Ilya Kostrikov
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
#
# This file is a modified version of
# https://github.com/ikostrikov/pytorch-a2c-ppo-acktr-g... | 7,434 | 31.609649 | 100 | py |
clutr | clutr-main/models/multigrid_models.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Be... | 9,215 | 28.350318 | 96 | py |
clutr | clutr-main/algos/storage.py | # Copyright (c) 2017 Ilya Kostrikov
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
#
# This file is a heavily modified version of:
# https://github.com/ikostrikov/pytorch-a2c-pp... | 21,244 | 40.013514 | 117 | py |
clutr | clutr-main/algos/ppo.py | # Copyright (c) 2017 Ilya Kostrikov
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
#
# This file is a modified version of:
# https://github.com/ikostrikov/pytorch-a2c-ppo-acktr-... | 5,333 | 35.534247 | 103 | py |
clutr | clutr-main/util/__init__.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import glob
import os
import shutil
import collections
import timeit
import random
import numpy as np
import torch
from ... | 9,551 | 30.734219 | 133 | py |
clutr | clutr-main/task_embed/clutr_RVAE/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__':
#saved_model = 'data/final/vae-recons-79-iter-1000000-latent-64-sequential-batch-train_1000000_32_trained_RVA... | 3,321 | 38.547619 | 120 | py |
clutr | clutr-main/task_embed/clutr_RVAE/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__":
parser = argparse.ArgumentParser(description='RVAE')
parser.add_argument('--n... | 10,164 | 37.79771 | 150 | py |
clutr | clutr-main/task_embed/clutr_RVAE/selfModules/embedding.py | import numpy as np
import torch as t
import torch.nn as nn
from torch.nn import Parameter
#from clutr.task_embed.clutr_RVAE.selfModules.tdnn import TDNN
from .tdnn import TDNN
class ClutrEmbedding(nn.Module):
MINIGRID = "minigrid"
MINIHACK = "minihack"
def __init__(self, params):
super(ClutrEmbed... | 3,114 | 36.53012 | 101 | py |
clutr | clutr-main/task_embed/clutr_RVAE/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 |
clutr | clutr-main/task_embed/clutr_RVAE/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_s... | 2,618 | 37.514706 | 123 | py |
clutr | clutr-main/task_embed/clutr_RVAE/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,770 | 33.057692 | 117 | py |
clutr | clutr-main/task_embed/clutr_RVAE/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):
return True
#parameters = list(module.parameters())
#return fold(f_and, parameters, True) or not fold(f_or, pa... | 666 | 19.212121 | 78 | py |
clutr | clutr-main/task_embed/clutr_RVAE/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, ClutrEmbedding
from utils.functional import kld_coef, parameters_allocation_check, fold... | 15,098 | 40.141689 | 153 | py |
clutr | clutr-main/task_embed/clutr_RVAE/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
#from clutr.task_embed.clutr_RVAE.selfModules.highway import Highway
#from clutr.task_embed.clutr_RVAE.utils.functional import parameters_allocati... | 2,418 | 36.215385 | 115 | py |
clutr | clutr-main/task_embed/clutr_RVAE/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
#from clutr.task_embed.clutr_RVAE.utils.functional import parameters_allocation_check
class Decoder(nn.Module):
MINIGRID = "minigrid"
MINIHACK = "minihack"
def __init__(self, ... | 3,490 | 40.559524 | 116 | py |
FaceLib | FaceLib-master/facelib/Retinaface/from_camera.py | import cv2
import torch
from facelib import special_draw
from facelib import FaceDetector
class WebcamFaceDetector:
def __init__(self, device=torch.device("cuda:0" if torch.cuda.is_available() else "cpu")):
print('loading ...')
self.detector = FaceDetector(face_size=(224, 224), device=device)
... | 1,217 | 34.823529 | 128 | py |
FaceLib | FaceLib-master/facelib/Retinaface/Retinaface.py | import os
import torch
import cv2
import numpy as np
from skimage import transform
from .utils.alignment import get_reference_facial_points, FaceWarpException, alignment
from .utils.box_utils import decode, decode_landmark, prior_box, nms
from .utils.config import cfg_mnet, cfg_re50
from .models.retinaface import Reti... | 7,375 | 39.527473 | 156 | py |
FaceLib | FaceLib-master/facelib/Retinaface/models/slim.py | import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_bn(inp, oup, stride = 1):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
nn.ReLU(inplace=True)
)
def depth_conv2d(inp, oup, kernel=1, stride=1, pad=0):
return nn.S... | 4,444 | 33.192308 | 100 | py |
FaceLib | FaceLib-master/facelib/Retinaface/models/retinaface.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models._utils as _utils
from ..models.net import FPN as FPN
from ..models.net import MobileNetV1 as MobileNetV1
from ..models.net import SSH as SSH
class ClassHead(nn.Module):
def __init__(self, inchannels=512, num_anchors=3):
... | 4,329 | 35.386555 | 113 | py |
FaceLib | FaceLib-master/facelib/Retinaface/models/net.py | import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_bn(inp, oup, stride=1, leaky=0):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
nn.LeakyReLU(negative_slope=leaky, inplace=True)
)
def conv_bn_no_relu(inp, oup, stri... | 4,473 | 31.42029 | 93 | py |
FaceLib | FaceLib-master/facelib/Retinaface/models/rfb.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicConv(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True):
super(BasicConv, self).__init__()
self.out_channels = out_planes
if bn:
... | 7,697 | 37.878788 | 159 | py |
FaceLib | FaceLib-master/facelib/Retinaface/utils/box_utils.py | from itertools import product as product
from math import ceil
import torch
# Original author: Francisco Massa:
# https://github.com/fmassa/object-detection.torch
# Ported to PyTorch by Max deGroot (02/01/2017)
def prior_box(cfg, image_size=None):
steps = cfg['steps']
feature_maps = [[ceil(image_size[0] / st... | 3,548 | 33.456311 | 95 | py |
FaceLib | FaceLib-master/facelib/FacialExpression/FaceExpression.py | import torch
import os
import numpy as np
from facelib.utils import download_weight
from .models.densenet import densenet121
from .models.resnet import resnet34
labels = np.array(['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral'])
class EmotionDetector:
def __init__(self, name='densnet121', weig... | 2,465 | 40.1 | 141 | py |
FaceLib | FaceLib-master/facelib/FacialExpression/from_camera.py | from facelib import FaceDetector
from facelib import EmotionDetector
from facelib import special_draw
import torch
import cv2
class WebcamEmotionDetector:
def __init__(self, device=torch.device("cuda:0" if torch.cuda.is_available() else "cpu")):
print('loading ...')
self.face_detector = FaceDetect... | 1,294 | 38.242424 | 128 | py |
FaceLib | FaceLib-master/facelib/FacialExpression/models/resnet.py | import torch
import torch.nn as nn
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',... | 14,176 | 38.055096 | 107 | py |
FaceLib | FaceLib-master/facelib/FacialExpression/models/densenet.py | import re
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from collections import OrderedDict
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url
__all__ = ['DenseN... | 10,900 | 43.133603 | 116 | py |
FaceLib | FaceLib-master/facelib/AgeGender/from_camera.py | from facelib import FaceDetector
from facelib import AgeGenderEstimator
from facelib import special_draw
import torch
import cv2
class WebcamAgeGenderEstimator:
def __init__(self, device=torch.device("cuda:0" if torch.cuda.is_available() else "cpu")):
print('loading ...')
self.face_detector = Face... | 1,337 | 39.545455 | 132 | py |
FaceLib | FaceLib-master/facelib/AgeGender/Detector.py | from facelib.AgeGender.models.model import ShuffleneTiny, ShuffleneFull
from facelib.utils import download_weight
import torch
import os
class AgeGenderEstimator:
def __init__(self, name='full', weight_path=None, device=torch.device("cuda:0" if torch.cuda.is_available() else "cpu")):
"""
Age and g... | 2,560 | 39.650794 | 141 | py |
FaceLib | FaceLib-master/facelib/AgeGender/models/model.py | import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import time
import sys
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
sz = 112
class ShuffleneTiny(nn.Module):
def __init__(self):
super(ShuffleneTiny, self).__init__()
self.model = models.shuffle... | 4,099 | 27.275862 | 112 | py |
FaceLib | FaceLib-master/facelib/AgeGender/models/train.py | """
Sajjad Ayoubi: Age Gender Detection
I use UTKFace DataSet
from: https://susanqq.github.io/UTKFace/
download it and put it on FaceSet dir
and I create a annotation file data.npy
which there is in weights folder
"""
from PIL import Image
import numpy as np
import torch
import torch.nn.functional as F
import torch.op... | 2,512 | 28.916667 | 88 | py |
FaceLib | FaceLib-master/facelib/InsightFace/add_face.py | import os
import cv2
import torch
from facelib import FaceDetector
from pathlib import Path
def add_from_webcam(person_name='unknow', camera_index=0):
print('loading ...')
# create facebank folder if is not exists
save_path = Path(os.path.dirname(os.path.realpath(__file__)), 'models/data/facebank')
... | 2,980 | 30.378947 | 124 | py |
FaceLib | FaceLib-master/facelib/InsightFace/verifier.py | import cv2
import torch
import argparse
from facelib import get_config, special_draw
from facelib import update_facebank, load_facebank
from facelib import FaceRecognizer
from facelib import FaceDetector
class WebcamVerify:
"""
WebcamVerify: face verfication with cv2
if you add new person in to faceb... | 2,162 | 36.293103 | 137 | py |
FaceLib | FaceLib-master/facelib/InsightFace/models/utils.py | from datetime import datetime
import numpy as np
import io, cv2, os
from .model import l2_norm
import torch
import matplotlib.pyplot as plt
plt.switch_backend('agg')
def faces_preprocessing(faces, device):
faces = faces.permute(0, 3, 1, 2).float()
faces = faces.div(255).to(device)
mu = torch.as_tensor([.5... | 4,660 | 34.045113 | 114 | py |
FaceLib | FaceLib-master/facelib/InsightFace/models/model.py | from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, ReLU, Sigmoid, Dropout, \
MaxPool2d, AdaptiveAvgPool2d, Sequential, Module, Parameter
import torch
from collections import namedtuple
import math
################################## Original Arcface Model #######################################... | 12,731 | 40.070968 | 119 | py |
FaceLib | FaceLib-master/facelib/InsightFace/models/Learner.py | from .model import Backbone, Arcface, MobileFaceNet, l2_norm
from .evaluatation import evaluate
import torch
from torch import optim
import numpy as np
import os
from tqdm import tqdm
from facelib.utils import download_weight
from .utils import get_time, gen_plot, separate_bn_paras
from .utils import faces_preprocessin... | 7,533 | 43.845238 | 124 | py |
FaceLib | FaceLib-master/facelib/InsightFace/models/data/config.py | from easydict import EasyDict as edict
from pathlib import Path
import os
import torch
from torch.nn import CrossEntropyLoss
def get_config(inference=True):
conf = edict()
conf.data_path = Path(os.path.dirname(os.path.realpath(__file__)))
conf.work_path = Path('weights/')
conf.model_path = conf.work_p... | 1,705 | 35.297872 | 84 | py |
LinkDist | LinkDist-master/main.py | import sys
import time
import numpy
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
import dgl
if len(sys.argv) > 2:
g_method, g_data, g_split, *gcard = sys.argv[1:]
gcard.append('0')
else:
g_method = 'lpa'
g_data ... | 15,262 | 36.046117 | 78 | py |
LinkDist | LinkDist-master/ogbn.py | # Usage: python3 ogbn.py [arxiv|mag|products]
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from ogb.nodeproppred import Evaluator, NodePropPredDataset
g_data, *gcard = sys.argv[1:]
gcard = int((gcard or [0])[0])
run... | 5,225 | 29.923077 | 76 | py |
CRAFT-pytorch | CRAFT-pytorch-master/test.py | """
Copyright (c) 2019-present NAVER Corp.
MIT License
"""
# -*- coding: utf-8 -*-
import sys
import os
import time
import argparse
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from PIL import Image
import cv2
from skimage import io
import numpy as np... | 5,911 | 33.372093 | 156 | py |
CRAFT-pytorch | CRAFT-pytorch-master/refinenet.py | """
Copyright (c) 2019-present NAVER Corp.
MIT License
"""
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from basenet.vgg16_bn import init_weights
class RefineNet(nn.Module):
def __init__(self):
super(RefineNet, self).__in... | 2,552 | 37.681818 | 115 | py |
CRAFT-pytorch | CRAFT-pytorch-master/craft.py | """
Copyright (c) 2019-present NAVER Corp.
MIT License
"""
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
from basenet.vgg16_bn import vgg16_bn, init_weights
class double_conv(nn.Module):
def __init__(self, in_ch, mid_ch, out_ch):
super(double_conv, self).__i... | 2,753 | 31.4 | 94 | py |
CRAFT-pytorch | CRAFT-pytorch-master/basenet/vgg16_bn.py | from collections import namedtuple
import torch
import torch.nn as nn
import torch.nn.init as init
from torchvision import models
from torchvision.models.vgg import model_urls
def init_weights(modules):
for m in modules:
if isinstance(m, nn.Conv2d):
init.xavier_uniform_(m.weight.data)
... | 2,805 | 36.918919 | 99 | py |
episodic-curiosity | episodic-curiosity-master/third_party/keras_resnet/models.py | # coding=utf-8
# COPYRIGHT
#
# All contributions by Raghavendra Kotikalapudi:
# Copyright (c) 2016, Raghavendra Kotikalapudi.
# All rights reserved.
#
# All other contributions:
# Copyright (c) 2016, the respective contributors.
# All rights reserved.
#
# Copyright (c) 2018 Google LLC
# All rights reserved.
#
# Each co... | 12,574 | 33.264305 | 80 | py |
episodic-curiosity | episodic-curiosity-master/episodic_curiosity/r_network_training.py | # coding=utf-8
# Copyright 2019 Google LLC.
#
# 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 ... | 14,313 | 38.65097 | 80 | py |
episodic-curiosity | episodic-curiosity-master/episodic_curiosity/env_factory.py | # coding=utf-8
# Copyright 2019 Google LLC.
#
# 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 ... | 12,692 | 35.474138 | 80 | py |
episodic-curiosity | episodic-curiosity-master/episodic_curiosity/train_r_test.py | # coding=utf-8
# Copyright 2019 Google LLC.
#
# 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 ... | 3,043 | 33.988506 | 80 | py |
episodic-curiosity | episodic-curiosity-master/episodic_curiosity/utils.py | # coding=utf-8
# Copyright 2019 Google LLC.
#
# 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 ... | 3,072 | 28.834951 | 74 | py |
episodic-curiosity | episodic-curiosity-master/episodic_curiosity/train_r.py | # coding=utf-8
# Copyright 2019 Google LLC.
#
# 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 ... | 16,734 | 40.320988 | 80 | py |
episodic-curiosity | episodic-curiosity-master/episodic_curiosity/env_factory_test.py | # coding=utf-8
# Copyright 2019 Google LLC.
#
# 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 ... | 3,018 | 32.921348 | 80 | py |
episodic-curiosity | episodic-curiosity-master/episodic_curiosity/r_network.py | # coding=utf-8
# Copyright 2019 Google LLC.
#
# 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 ... | 3,675 | 34.346154 | 80 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.