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 |
|---|---|---|---|---|---|---|
Smile-Pruning | Smile-Pruning-master/src/dataset/cifar100.py | from torchvision.datasets import CIFAR100
import torchvision.transforms as transforms
def get_dataset(data_path, batch_size):
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(... | 1,203 | 33.4 | 107 | py |
Smile-Pruning | Smile-Pruning-master/src/dataset/fmnist.py | from torchvision.datasets import FashionMNIST
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
def get_dataset(data_path, batch_size):
transform = transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize(
(... | 728 | 28.16 | 45 | py |
Smile-Pruning | Smile-Pruning-master/src/dataset/cifar10.py | from torchvision.datasets import CIFAR10
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
def get_dataset(data_path, batch_size):
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.To... | 1,406 | 37.027027 | 129 | py |
Smile-Pruning | Smile-Pruning-master/src/dataset/__init__.py |
from importlib import import_module
import os
import numpy as np
import torch
from torch.utils import data
from torch.utils.data import DataLoader
class Data(object):
def __init__(self, args):
self.args = args
dataset = import_module("dataset.%s" % args.dataset)
path = os.path.join(args.... | 1,294 | 39.46875 | 72 | py |
Smile-Pruning | Smile-Pruning-master/src/dataset/celeba.py | import numpy as np
import os
import torch
import torch.utils.data as data
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
pjoin = os.path.join
def is_img(x):
_, ext = os.path.splitext(x)
return ext.lower() in ['.jpg', '.pn... | 3,610 | 31.827273 | 80 | py |
Smile-Pruning | Smile-Pruning-master/src/dataset/tiny_imagenet.py | import numpy as np
import torch
import torch.utils.data as data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from option import args
from PIL import Image
import os
from utils import Dataset_npy_batch
# refer to: https://github.com/pytorch/exa... | 1,075 | 26.589744 | 76 | py |
Smile-Pruning | Smile-Pruning-master/src/dataset/mnist.py | from torchvision.datasets.mnist import MNIST
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
def get_dataset(data_path, batch_size):
transform = transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize(
(0... | 713 | 27.56 | 44 | py |
Smile-Pruning | Smile-Pruning-master/src/method_modules/prune.py |
from .pruner import pruner_dict
def prune(model, loader, args, logger):
# Read config file, get pruner name
pruner = pruner_dict[args.pruner].Pruner(model, loader, args, logger)
pruner.prune()
print(f'==> Prune is done.')
# -- Debug to check if the pruned weights are really zero. Confirmed!
# ... | 526 | 30 | 73 | py |
Smile-Pruning | Smile-Pruning-master/src/method_modules/train.py |
import torch
import torch.nn as nn
from utils import PresetLRScheduler, adjust_learning_rate, AverageMeter, ProgressMeter, accuracy
from utils import get_n_params, get_n_flops, get_n_params_, get_n_flops_
from utils import add_noise_to_model, compute_jacobian, _weights_init_orthogonal, get_jacobian_singular_values
fr... | 15,266 | 42.87069 | 191 | py |
Smile-Pruning | Smile-Pruning-master/src/method_modules/pruner/layer.py | import torch.nn as nn
import torch
class Layer():
'''A neat class to maintain network layer structure'''
def __init__(self, name, size, layer_index, layer_type=None, res=False, last=None):
self.name = name
self.size = []
for x in size:
self.size.append(x)
self.layer_... | 3,125 | 40.68 | 138 | py |
Smile-Pruning | Smile-Pruning-master/src/method_modules/pruner/l1_pruner.py | import torch
import torch.nn as nn
import copy
import time
import numpy as np
import torch.optim as optim
from .meta_pruner import MetaPruner
# from .reinit_model import orth_dist, deconv_orth_dist
from utils import Timer
class Pruner(MetaPruner):
def __init__(self, model, loader, args, logger):
super(Prun... | 4,717 | 43.093458 | 119 | py |
Smile-Pruning | Smile-Pruning-master/src/method_modules/pruner/reg_pruner.py | import torch
import torch.nn as nn
import torch.optim as optim
import os, copy, time, pickle, numpy as np, math
from .meta_pruner import MetaPruner
from utils import plot_weights_heatmap, Timer, AverageMeter, ProgressMeter, accuracy
import matplotlib.pyplot as plt
pjoin = os.path.join
tensor2list = lambda x: x.cpu().da... | 28,706 | 46.845 | 151 | py |
Smile-Pruning | Smile-Pruning-master/src/method_modules/pruner/l1_pruner_iterative.py | import torch
import torch.nn as nn
import copy
import time
import numpy as np
import torch.optim as optim
from .meta_pruner import MetaPruner
from utils import PresetLRScheduler, Timer
from pdb import set_trace as st
class Pruner(MetaPruner):
def __init__(self, model, loader, args, logger, passer):
super(P... | 3,360 | 39.987805 | 160 | py |
Smile-Pruning | Smile-Pruning-master/src/method_modules/pruner/feat_analyze.py |
from collections import OrderedDict
import torch.nn as nn
import numpy as np
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=':f'):
self.name = name
self.fmt = fmt
self.reset()
def reset(self):
self.val = 0
... | 2,834 | 34.886076 | 100 | py |
Smile-Pruning | Smile-Pruning-master/src/method_modules/pruner/meta_pruner.py | import torch
import torch.nn as nn
import copy
import time
import numpy as np
from math import ceil, sqrt
from collections import OrderedDict
from utils import strdict_to_dict
from .layer import register_modulename, register_hook, rm_hook, Layer
from fnmatch import fnmatch, fnmatchcase
DEVICE = torch.device("cuda" if t... | 19,181 | 45.899756 | 175 | py |
Smile-Pruning | Smile-Pruning-master/src/method_modules/reiniter/lth.py | import torch
import torch.nn as nn
class Reiniter():
def __init__(self, model, loader, args, logger):
self.model = model
self.ckpt_init = logger.passer['ckpt_init']
def reinit(self):
assert hasattr(self.model, 'mask'), "'model' should has attr 'mask'."
state_dict = torch.load(s... | 642 | 39.1875 | 97 | py |
Smile-Pruning | Smile-Pruning-master/src/method_modules/reiniter/pth_reset.py | from utils import _weights_init, _weights_init_orthogonal, orthogonalize_weights, delta_orthogonalize_weights
import torch
import torch.nn as nn
from torch.nn.init import _calculate_correct_fan, calculate_gain
import torch.nn.functional as F
import numpy as np, math
def isfloat(num):
try:
float(num)
... | 9,299 | 43.285714 | 179 | py |
Smile-Pruning | Smile-Pruning-master/src/model/mobilenetv2.py | import torch
import torch.nn as nn
from torchvision.models import alexnet
try:
from torchvision.models import mobilenet_v2
except:
pass
from model import generator as g
# modify mobilenet to my interface
class MobilenetV2(nn.Module):
def __init__(self, n_class=1000, width_mult=1.0):
super(MobilenetV2, self).... | 1,075 | 28.888889 | 66 | py |
Smile-Pruning | Smile-Pruning-master/src/model/vgg.py | # This file is referring to: [EigenDamage, ICML'19] at https://github.com/alecwangcq/EigenDamage-Pytorch.
# We modified a little to make it more neat and standard.
import math
import torch
import torch.nn as nn
import torch.nn.init as init
def _weights_init(m):
if isinstance(m, nn.Linear) or isinstance(m, nn.Conv... | 3,423 | 37.47191 | 107 | py |
Smile-Pruning | Smile-Pruning-master/src/model/lenet5.py | import torch
import torch.nn as nn
class LeNet5(nn.Module):
def __init__(self, num_classes: int = 10, num_channels: int = 1):
super(LeNet5, self).__init__()
self.conv1 = nn.Conv2d(num_channels, 6, kernel_size=(5, 5))
self.relu1 = nn.ReLU()
self.maxpool1 = nn.MaxPool2d(kernel_size=(... | 6,492 | 36.97076 | 87 | py |
Smile-Pruning | Smile-Pruning-master/src/model/mlp.py | import torch
import torch.nn as nn
import math
class FCNet(nn.Module):
def __init__(self, dim_input, num_classes, num_fc, width=0, num_params=0, branch_layer_out_dim=[], act='relu', dropout=0):
super(FCNet, self).__init__()
# activation func
if act == 'relu':
activation = nn.ReL... | 3,070 | 40.5 | 143 | py |
Smile-Pruning | Smile-Pruning-master/src/model/alexnet_celeba.py | import torch
import torch.nn as nn
from option import args
import model.generator as g
from torchvision.models import mobilenet_v2, alexnet
class AlexNet(nn.Module):
def __init__(self, drop=0.5):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=(11, 11), strid... | 4,126 | 32.827869 | 84 | py |
Smile-Pruning | Smile-Pruning-master/src/model/weight_normalization_layer.py | import torch.nn as nn
import torch
from torch.nn import functional as F
class Conv2D_WN(nn.Conv2d):
'''Conv2D with weight normalization.
'''
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
... | 1,249 | 32.783784 | 82 | py |
Smile-Pruning | Smile-Pruning-master/src/model/alexnet_cifar10.py | import torch
import torch.nn as nn
from option import args
import model.generator as g
# ref to ZSKD: https://github.com/vcl-iisc/ZSKD/blob/master/model_training/include/model_alex_full.py
class AlexNet_cifar10(nn.Module):
def __init__(self, model=None, fixed=False):
super(AlexNet_cifar10, self).__init__()
s... | 5,336 | 36.584507 | 111 | py |
Smile-Pruning | Smile-Pruning-master/src/model/resnet_cifar10.py | '''
Refer to: https://github.com/akamaster/pytorch_resnet_cifar10/blob/master/resnet.py
Properly implemented ResNet-s for CIFAR10 as described in paper [1].
The implementation and structure of this file is hugely influenced by [2]
which is implemented for ImageNet and doesn't have option A for identity.
Moreover, mos... | 6,133 | 36.631902 | 129 | py |
Smile-Pruning | Smile-Pruning-master/src/model/wrn.py | """
This code is from 2019-NIPS-ZSKT (Spotlight): https://github.com/polo5/ZeroShotKnowledgeTransfer/blob/master/models/wresnet.py
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import model.generator as g
import copy
class BasicBlock(nn.Module):
def __init__(self, in_planes, o... | 6,478 | 42.193333 | 126 | py |
couta | couta-main/main.py | """
@author: Hongzuo Xu
@comments: testbed for time series anomaly detection
"""
import argparse
import os
import time
import pickle
import numpy as np
from main_utils import prepare, run, get_data_lst
# -------------------------------- argument parser --------------------------------#
parser = argparse.ArgumentParse... | 4,848 | 39.07438 | 111 | py |
couta | couta-main/src/utils_general.py | import sys
sys.path.append('../src')
import numpy as np
import torch
import random
from matplotlib import pyplot as plt
import seaborn as sns
from src import utils_eval
def set_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backend... | 10,351 | 33.506667 | 115 | py |
couta | couta-main/src/algorithms/algorithm_utils.py | import os
import random
import numpy as np
import torch
import string
mask = ''.join(random.sample(string.ascii_letters, 8))
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, intermediate_dir,
patience=7, verbose=... | 3,512 | 39.848837 | 116 | py |
couta | couta-main/src/algorithms/couta_algo.py | """
Calibrated One-class classifier for Unsupervised Time series Anomaly detection (COUTA)
@author: Hongzuo Xu (hongzuo.xu@gmail.com)
"""
import os
import random
import pandas as pd
import numpy as np
import torch
from torch.utils.data import Dataset
from numpy.random import RandomState
from torch.utils.data import Da... | 18,097 | 34.278752 | 113 | py |
couta | couta-main/src/algorithms/net.py | import torch
import torch.nn as nn
from torch.nn.utils import weight_norm
class Chomp1d(nn.Module):
def __init__(self, chomp_size):
super(Chomp1d, self).__init__()
self.chomp_size = chomp_size
def forward(self, x):
return x[:, :, :-self.chomp_size].contiguous()
class TemporalBlock(n... | 4,435 | 35.360656 | 94 | py |
couta | couta-main/src/algorithms/canonical_oc_algo.py | import pandas as pd
import numpy as np
import torch
import random
import os
from numpy.random import RandomState
from torch.utils.data import DataLoader, Dataset
from .algorithm_utils import get_sub_seqs, EarlyStopping
from src.algorithms.net import NetModule
class Canonical:
def __init__(self, sequence_length=10... | 8,553 | 33.914286 | 113 | py |
Elektrum | Elektrum-main/src/runAmber_kinn.py | #!/usr/bin/env python
# coding: utf-8
# # Probablistic model building genetic algorithm
from silence_tensorflow import silence_tensorflow
silence_tensorflow()
from src.kinetic_model import KineticModel, modelSpace_to_modelParams
from src.neural_network_builder import KineticNeuralNetworkBuilder, KineticEigenModelBuild... | 5,631 | 39.517986 | 174 | py |
Elektrum | Elektrum-main/src/neural_search.py | from src.kinetic_model import KineticModel, modelSpace_to_modelParams
from src.neural_network_builder import KineticNeuralNetworkBuilder, KineticEigenModelBuilder
import tensorflow.compat.v1 as tf1
import tensorflow as tf
from tensorflow.keras.optimizers import SGD, Adam
from tensorflow.keras.callbacks import ModelChec... | 9,180 | 43.139423 | 201 | py |
Elektrum | Elektrum-main/src/transfer_learn.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""AMBER NAS for incorporating KINN of different state numbers, and sequence context-specific effects
"""
# FZZ, 2022/10/16
import tensorflow as tf
import numpy as np
import os
import pickle
import h5py
from src.neural_network_builder import KineticNeuralNetworkBuilder
... | 24,213 | 33.690544 | 185 | py |
Elektrum | Elektrum-main/src/neural_network_builder.py | """class for converting a kinetic model hypothesis to a keras neural network
"""
from amber.utils import corrected_tf as tf
import tensorflow as tf2
from tensorflow.keras.layers import Input, Conv1D, Dense, Concatenate, Lambda, Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import S... | 17,038 | 40.96798 | 138 | py |
Elektrum | Elektrum-main/src/runAmber_cnn.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Example wrapper `Amber` use for searching cas9 off-target kinetic prediction
FZZ, Jan 28, 2022
"""
from amber import Amber
from amber.utils import run_from_ipython, get_available_gpus
from amber.architect import ModelSpace, Operation
import sys
import os
import pickl... | 9,410 | 35.196154 | 132 | py |
Elektrum | Elektrum-main/src/reload.py | from src.kinetic_model import KineticModel
from src.neural_network_builder import KineticNeuralNetworkBuilder, KineticEigenModelBuilder
import sys
import time
import pickle
import os
from amber.utils import corrected_tf as tf
import numpy as np
from amber.utils import run_from_ipython
import copy
def reload_from_dir(w... | 4,152 | 41.814433 | 188 | py |
Elektrum | Elektrum-main/src/runAmber_simkinn.py | #!/usr/bin/env python
# coding: utf-8
# # Probablistic model building genetic algorithm
from silence_tensorflow import silence_tensorflow
silence_tensorflow()
from src.kinetic_model import KineticModel, modelSpace_to_modelParams
from src.neural_network_builder import KineticNeuralNetworkBuilder, KineticEigenModelBuild... | 11,053 | 38.906137 | 174 | py |
Elektrum | Elektrum-main/src/crispr_kinn_predict.py | """a script that wraps up the calling and parsing of CRISPR-OffTarget predictions
FZZ, 2022.03.15
"""
import numpy as np
import pandas as pd
import warnings
from src.reload import reload_from_dir
from src.neural_network_builder import KineticNeuralNetworkBuilder, KineticEigenModelBuilder
#import tensorflow as tf
from... | 5,888 | 41.366906 | 159 | py |
Elektrum | Elektrum-main/src/tests/test_transfer_learn.py |
from distutils.sysconfig import customize_compiler
import tensorflow as tf
import numpy as np
import os
from src.data import load_finkelstein_data as get_data
from src.transfer_learn import KinnLayer
from src.reload import reload_from_dir
# test
include_ref = True
seq = tf.keras.layers.Input((25,13), name='seq')
x = ... | 2,094 | 34.508475 | 117 | py |
MSVoxelDNN | MSVoxelDNN-master/training/ms_voxel_cnn_training.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset
import numpy as np
import matplotlib.pyplot as plt
import random as rn
import os
import time
from torchvision import datasets, transforms
import argparse
from torchsummary import summary
from pyntcloud import PyntClo... | 20,975 | 42.428571 | 233 | py |
MSVoxelDNN | MSVoxelDNN-master/training/voxel_dnn_training_torch.py | # VoxelCNN
import random as rn
import numpy as np
from utils.inout import input_fn_voxel_dnn, get_shape_data, get_files, load_points
import os
import sys
import argparse
import datetime
from utils.training_tools import save_ckp,load_ckp,compute_metric, Rotation, Random_sampling
import datetime
from torchvision.transfo... | 15,785 | 44.756522 | 448 | py |
MSVoxelDNN | MSVoxelDNN-master/ms_voxel_dnn_coder/ms_voxel_dnn_encoder.py | import numpy as np
import os
import argparse
import time
from utils.inout import occupancy_map_explore, pmf_to_cdf
from utils.metadata_endec import save_compressed_file
import gzip
import pickle
from training.voxel_dnn_training_torch import VoxelDNN
import torchac
import torch
import torch.nn as nn
from training.ms_vox... | 8,518 | 41.383085 | 232 | py |
MSVoxelDNN | MSVoxelDNN-master/utils/inout.py | import numpy as np
from utils.octree_partition import partition_octree
import time
from glob import glob
import tensorflow as tf
import multiprocessing
from tqdm import tqdm
from pyntcloud import PyntCloud
import pandas as pd
import torch
#import open3d as o3d
#VOXEL-OCTREE
def timing(f):
def wrap(*args, **kwargs):... | 18,459 | 38.027484 | 242 | py |
MSVoxelDNN | MSVoxelDNN-master/utils/training_tools.py |
import torch
import shutil
import numpy as np
import math as m
def compute_metric(predict, target,writer, step):
pred_label = torch.argmax(predict, dim=1)
tp = torch.count_nonzero(pred_label * target)
fp = torch.count_nonzero(pred_label * (target - 1))
tn = torch.count_nonzero((pred_label - 1) * (targe... | 4,259 | 35.724138 | 134 | py |
ByteTransformer | ByteTransformer-main/unit_test/python_scripts/bert_transformer_test.py | # Copyright 2023 Bytedance Ltd. and/or its affiliates.
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apa... | 10,261 | 48.100478 | 145 | py |
dytox | dytox-main/main.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
# Modified for DyTox by Arthur Douillard
import argparse
import copy
import datetime
import json
import os
import statistics
import time
import warnings
from pathlib import Path
import yaml
from continual.pod import _local_pod
import numpy as np
impo... | 41,049 | 49.244798 | 147 | py |
dytox | dytox-main/continual/scaler.py | import torch
from timm.utils import dispatch_clip_grad
class ContinualScaler:
state_dict_key = "amp_scaler"
def __init__(self, disable_amp):
self._scaler = torch.cuda.amp.GradScaler(enabled=not disable_amp)
def __call__(
self, loss, optimizer, model_without_ddp, clip_grad=None, clip_mod... | 1,563 | 33 | 111 | py |
dytox | dytox-main/continual/losses.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Implements the knowledge distillation loss
"""
import torch
from torch import nn
from torch.nn import functional as F
class DistillationLoss(torch.nn.Module):
"""
This module wraps a standard criterion and adds an extra knowledge distilla... | 6,637 | 34.308511 | 114 | py |
dytox | dytox-main/continual/engine.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Train and eval functions used in main.py
"""
import json
import os
import math
from typing import Iterable, Optional
import torch
from timm.data import Mixup
from timm.utils import accuracy
from timm.loss import SoftTargetCrossEntropy
from torch.n... | 15,851 | 40.389034 | 114 | py |
dytox | dytox-main/continual/convit.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the CC-by-NC license found in the
# LICENSE file in the root directory of this source tree.
#
'''These modules are adapted from those of timm, see
https://github.com/rwightman/pytorch-image-models/blob/master/tim... | 26,161 | 35.692847 | 152 | py |
dytox | dytox-main/continual/utils.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Misc functions, including distributed helpers.
Mostly copy-paste from torchvision references.
"""
import io
import os
import time
from collections import defaultdict, deque
import datetime
import warnings
import torch
from torch import nn
import ... | 9,641 | 30.103226 | 110 | py |
dytox | dytox-main/continual/classifier.py | import torch
from torch import nn
from torch.nn import functional as F
class Classifier(nn.Module):
def __init__(self, embed_dim, nb_total_classes, nb_base_classes, increment, nb_tasks, bias=True, complete=True, cosine=False, norm=True):
super().__init__()
self.embed_dim = embed_dim
self.... | 2,422 | 31.743243 | 141 | py |
dytox | dytox-main/continual/mixup.py | """ Mixup and Cutmix
Papers:
mixup: Beyond Empirical Risk Minimization (https://arxiv.org/abs/1710.09412)
CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features (https://arxiv.org/abs/1905.04899)
Code Reference:
CutMix: https://github.com/clovaai/CutMix-PyTorch
Hacked together by / Co... | 15,826 | 45.277778 | 120 | py |
dytox | dytox-main/continual/vit.py | """ Vision Transformer (ViT) in PyTorch
A PyTorch implement of Vision Transformers as described in
'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929
The official jax code is released and available at https://github.com/google-research/vision_transformer
... | 32,176 | 45.565847 | 137 | py |
dytox | dytox-main/continual/rehearsal.py | import copy
import numpy as np
import torch
class Memory:
def __init__(self, memory_size, nb_total_classes, rehearsal, fixed=True, modes=1):
self.memory_size = memory_size
self.nb_total_classes = nb_total_classes
self.rehearsal = rehearsal
self.fixed = fixed
self.modes = m... | 9,073 | 31.291815 | 113 | py |
dytox | dytox-main/continual/datasets.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import json
import os
import warnings
from continuum import ClassIncremental
from continuum.datasets import CIFAR100, ImageNet100, ImageFolderDataset
from timm.data import create_transform
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENE... | 5,681 | 34.962025 | 115 | py |
dytox | dytox-main/continual/factory.py | import torch
from continual import convit, dytox, samplers, vit
from continual.cnn import (InceptionV3, resnet18, resnet34, resnet50,
resnext50_32x4d, seresnet18, vgg16, vgg16_bn,
wide_resnet50_2, resnet18_scs, resnet18_scs_max, resnet18_scs_avg, resnet_rebuffi)
... | 4,398 | 32.838462 | 109 | py |
dytox | dytox-main/continual/sam.py | import torch
class SAM:
"""SAM, ASAM, and Look-SAM
Modified version of: https://github.com/davda54/sam
Only Look-SAM has been added.
It speeds up SAM quite a lot but the alpha needs to be tuned to reach same performance.
"""
def __init__(self, base_optimizer, model_without_ddp, rho=0.05, ada... | 3,350 | 35.032258 | 141 | py |
dytox | dytox-main/continual/pod.py | import torch
from torch.nn import functional as F
def pod_loss(feats, old_feats, scales=[1], normalize=True):
loss = 0.
assert len(feats) == len(old_feats)
for feat, old_feat in zip(feats, old_feats):
emb = _local_pod(feat, scales)
old_emb = _local_pod(old_feat, scales)
if norma... | 1,061 | 25.55 | 69 | py |
dytox | dytox-main/continual/dytox.py | import copy
import torch
from timm.models.layers import trunc_normal_
from torch import nn
from continual.cnn import resnet18
import continual.utils as cutils
from continual.convit import ClassAttention, Block
class ContinualClassifier(nn.Module):
"""Your good old classifier to do continual."""
def __init__... | 15,824 | 36.768496 | 109 | py |
dytox | dytox-main/continual/samplers.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import torch
import torch.distributed as dist
import math
import continual.utils as utils
class RASampler(torch.utils.data.Sampler):
"""Sampler that restricts data loading to a subset of the dataset for distributed,
with repeated augmentatio... | 5,913 | 37.653595 | 119 | py |
dytox | dytox-main/continual/cnn/inception.py | """ inceptionv3 in pytorch
[1] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, Zbigniew Wojna
Rethinking the Inception Architecture for Computer Vision
https://arxiv.org/abs/1512.00567v3
"""
import torch
import torch.nn as nn
from continual.cnn import AbstractCNN
class BasicConv2d(n... | 10,916 | 31.108824 | 90 | py |
dytox | dytox-main/continual/cnn/resnet.py | #from .utils import load_state_dict_from_url
from typing import Any, Callable, List, Optional, Type, Union
import torch
import torch.nn as nn
from torch.nn import functional as F
from continual.cnn import AbstractCNN
from torch import Tensor
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
... | 17,344 | 38.331066 | 111 | py |
dytox | dytox-main/continual/cnn/vgg.py | import torch
import torch.nn as nn
#from .utils import load_state_dict_from_url
from typing import Union, List, Dict, Any, cast
from continual.cnn import AbstractCNN
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
'vgg19_bn', 'vgg19',
]
model_urls = {
'vgg11': 'https://... | 7,858 | 39.302564 | 114 | py |
dytox | dytox-main/continual/cnn/senet.py |
from continual.cnn import AbstractCNN
"""
SEResNet implementation from Cadene's pretrained models
https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/senet.py
Additional credit to https://github.com/creafz
Original model: https://github.com/hujie-frank/SENet
ResNet code gently b... | 17,758 | 36.545455 | 127 | py |
dytox | dytox-main/continual/cnn/resnet_scs.py | #from .utils import load_state_dict_from_url
from typing import Any, Callable, List, Optional, Type, Union
import torch
import torch.nn as nn
from torch.nn import functional as F
from continual.cnn import AbstractCNN
from torch import Tensor
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
... | 21,904 | 37.029514 | 111 | py |
dytox | dytox-main/continual/cnn/abstract.py | from torch import nn
import continual.utils as cutils
class AbstractCNN(nn.Module):
def reset_classifier(self):
self.head.reset_parameters()
def get_internal_losses(self, clf_loss):
return {}
def end_finetuning(self):
pass
def begin_finetuning(self):
pass
def e... | 1,063 | 24.333333 | 82 | py |
dytox | dytox-main/continual/cnn/resnet_rebuffi.py | """Pytorch port of the resnet used for CIFAR100 by iCaRL.
https://github.com/srebuffi/iCaRL/blob/master/iCaRL-TheanoLasagne/utils_cifar100.py
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
from continual.cnn import AbstractCNN
class DownsampleStride(nn.Module):
... | 7,575 | 25.960854 | 97 | py |
2020-CBMS-DoubleU-Net | 2020-CBMS-DoubleU-Net-master/doubleunet_pytorch.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import vgg19
class Conv2D(nn.Module):
def __init__(self, in_c, out_c, kernel_size=3, padding=1, dilation=1, bias=False, act=True):
super().__init__()
self.act = act
self.conv = nn.Sequential(
... | 6,190 | 24.903766 | 96 | py |
2020-CBMS-DoubleU-Net | 2020-CBMS-DoubleU-Net-master/utils.py |
import os
import numpy as np
import cv2
import json
from glob import glob
from metrics import *
from sklearn.utils import shuffle
from tensorflow.keras.utils import CustomObjectScope
from tensorflow.keras.models import load_model
from model import build_model, Upsample, ASPP
def create_dir(path):
""" Create a dir... | 1,566 | 24.688525 | 60 | py |
2020-CBMS-DoubleU-Net | 2020-CBMS-DoubleU-Net-master/model.py |
import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model
from tensorflow.keras.applications import *
def squeeze_excite_block(inputs, ratio=8):
init = inputs
channel_axis = -1
filters = init.shape[channel_axis]
se_shape = (1, 1, filters)
se = GlobalA... | 4,571 | 27.397516 | 103 | py |
2020-CBMS-DoubleU-Net | 2020-CBMS-DoubleU-Net-master/metrics.py | import os
import numpy as np
import cv2
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.losses import binary_crossentropy
smooth = 1e-15
def dice_coef(y_true, y_pred):
y_true = tf.keras.layers.Flatten()(y_true)
y_pred = tf.keras.layers.Flatten()(y_pred)
intersection ... | 1,661 | 37.651163 | 121 | py |
2020-CBMS-DoubleU-Net | 2020-CBMS-DoubleU-Net-master/predict.py |
import os
import numpy as np
import cv2
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.utils import CustomObjectScope
from glob import glob
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from utils import *
from train import tf_dataset
def read... | 2,753 | 28.297872 | 102 | py |
2020-CBMS-DoubleU-Net | 2020-CBMS-DoubleU-Net-master/train.py |
import os
import numpy as np
import cv2
import tensorflow as tf
from tensorflow.keras.callbacks import *
from tensorflow.keras.optimizers import Adam, Nadam
from tensorflow.keras.metrics import *
from glob import glob
from sklearn.model_selection import train_test_split
from model import build_model
from utils import ... | 3,101 | 26.451327 | 82 | py |
UADAD | UADAD-main/utils.py | from math import ceil
import pandas as pd
import os
import sys
import numpy as np
import torch
import qgel
from sklearn import preprocessing
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score
from sklearn.metrics import confusion_matrix
from... | 5,431 | 34.045161 | 108 | py |
UADAD | UADAD-main/train_som.py | import os
import pickle
import gc
import sys
import argparse
import torch
from utils import *
import pandas as pd
from torch import optim
from torch.utils.data import DataLoader
from Code.datasets.car_insurance import Car_insurance
from Code.datasets.vehicle_claims import Vehicle_Claims
from Code.datasets.vehicle_in... | 9,368 | 44.26087 | 143 | py |
UADAD | UADAD-main/eval.py | import os
import argparse
import numpy as np
import pandas as pd
import torch
from utils import *
from torch.utils.data import DataLoader
from Code.unsupervised_methods.som_dagmm.model import DAGMM, SOM_DAGMM
from Code.unsupervised_methods.som_dagmm.compression_network import CompressionNetwork
from Code.unsupervis... | 8,306 | 42.265625 | 117 | py |
UADAD | UADAD-main/train.py | import os
import pickle
import gc
import sys
import argparse
import torch
from Code.datasets.vehicle_claims import Vehicle_Claims
from utils import *
from torch import optim
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from Code.unsupervised_methods.rsrae.rsrae import RS... | 8,837 | 42.752475 | 120 | py |
UADAD | UADAD-main/Code/unsupervised_methods/rsrae/rsrae.py | import torch
from torch import nn
import torch.nn.functional as F
from fastai.layers import Embedding
from fastai.torch_core import Module
from typing import List, Tuple
class RSRLayer(nn.Module):
def __init__(self, d, D):
super().__init__()
self.d = d
self.D = D
self.A = nn.Paramet... | 2,646 | 29.77907 | 102 | py |
UADAD | UADAD-main/Code/unsupervised_methods/som_dagmm/estimation_network.py | import torch
from torch import nn
class EstimationNetwork(nn.Module):
"""Defines a estimation network."""
def __init__(self, dim_embed, num_mixtures):
super().__init__()
self.net = nn.Sequential(nn.Linear(dim_embed, 10),
nn.Tanh(),
... | 518 | 31.4375 | 61 | py |
UADAD | UADAD-main/Code/unsupervised_methods/som_dagmm/model.py | """Implements all the components of the DAGMM model."""
from pandas import NA
import torch
import numpy as np
from torch import nn
import pickle
from minisom import MiniSom
from Code.classic_ML.SOM import som_train
from fastai.layers import Embedding
from fastai.torch_core import Module
from typing import List, Tuple
... | 4,471 | 36.266667 | 115 | py |
UADAD | UADAD-main/Code/unsupervised_methods/som_dagmm/gmm.py | """Implements a GMM model."""
import torch
import numpy as np
from torch import nn
class GMM(nn.Module):
"""Implements a Gaussian Mixture Model."""
def __init__(self, num_mixtures, dimension_embedding):
"""Creates a Gaussian Mixture Model.
Args:
num_mixtures (int): the number of ... | 5,867 | 36.375796 | 84 | py |
UADAD | UADAD-main/Code/unsupervised_methods/som_dagmm/compression_network.py | """Defines the compression network."""
import torch
from torch import nn
from fastai.layers import Embedding
from fastai.torch_core import Module
from typing import List, Tuple
class EmbeddingLayer(Module):
def __init__(self, emb_szs: List[Tuple[int, int]]):
self.embeddings = torch.nn.ModuleList([Embeddin... | 2,267 | 32.352941 | 102 | py |
UADAD | UADAD-main/Code/unsupervised_methods/dagmm_self/estimation_network.py | import torch
from torch import nn
class EstimationNetwork(nn.Module):
"""Defines a estimation network."""
def __init__(self, dim_embed, num_mixtures):
super().__init__()
self.net = nn.Sequential(nn.Linear(dim_embed, 10),
nn.Tanh(),
... | 518 | 31.4375 | 61 | py |
UADAD | UADAD-main/Code/unsupervised_methods/dagmm_self/model.py | """Implements all the components of the DAGMM model."""
import torch
import numpy as np
from torch import nn
eps = torch.autograd.Variable(torch.FloatTensor([1.e-8]), requires_grad=False)
class DAGMM(nn.Module):
def __init__(self, compression_module, estimation_module, gmm_module):
"""
Args:
... | 2,870 | 39.43662 | 78 | py |
UADAD | UADAD-main/Code/unsupervised_methods/dagmm_self/gmm.py | """Implements a GMM model."""
import torch
import numpy as np
from torch import nn
class GMM(nn.Module):
"""Implements a Gaussian Mixture Model."""
def __init__(self, num_mixtures, dimension_embedding):
"""Creates a Gaussian Mixture Model.
Args:
num_mixtures (int): the number of ... | 5,845 | 36 | 84 | py |
UADAD | UADAD-main/Code/unsupervised_methods/dagmm_self/compression_network.py | """Defines the compression network."""
import torch
from torch import nn
from fastai.layers import Embedding
from fastai.torch_core import Module
from typing import List, Tuple
class EmbeddingLayer(Module):
def __init__(self, emb_szs: List[Tuple[int, int]]):
self.embeddings = torch.nn.ModuleList([Embeddin... | 2,337 | 31.929577 | 102 | py |
UADAD | UADAD-main/Code/datasets/utils.py | from math import ceil
import pandas as pd
import os
import sys
import numpy as np
import torch
import qGEL
from sklearn import preprocessing
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import precision_score, recall_score, f1_score
from sklearn.metrics import confusion_matrix
from sklearn import... | 5,507 | 34.307692 | 109 | py |
UADAD | UADAD-main/Code/datasets/vehicle_claims.py | import os
import pandas as pd
from torch.utils.data import Dataset
import torch
import numpy as np
from utils import *
class Vehicle_Claims(Dataset):
def __init__(self, path, encoding = "label_encode", embedding_layer = False, label_file="train_Y.csv"):
path = path
categorical_cols = ['Maker','Reg... | 2,739 | 46.241379 | 131 | py |
UADAD | UADAD-main/Code/datasets/vehicle_insurance.py | import os
import pandas as pd
from torch.utils.data import Dataset
import torch
import numpy as np
from utils import *
class Vehicle_Insurance(Dataset):
def __init__(self, path, encoding = "label_encode", embedding_layer = False, label_file="train_Y.csv"):
path = path
categorical_cols = ['Make', '... | 2,885 | 53.45283 | 125 | py |
UADAD | UADAD-main/Code/datasets/car_insurance.py | import os
import pandas as pd
from torch.utils.data import Dataset
import torch
import numpy as np
from utils import *
class Car_insurance(Dataset):
def __init__(self, path, encoding = "label_encode", embedding_layer = False, label_file="train_Y.csv"):
path = path
categorical_cols = ['policy_state... | 3,026 | 54.036364 | 137 | py |
UADAD | UADAD-main/Code/classic_ML/SOM.py | import numpy as np
from minisom import MiniSom
import torch
import numpy as np
from torch import nn
from fastai.layers import Embedding
from fastai.torch_core import Module
from typing import List, Tuple
class EmbeddingLayer(Module):
def __init__(self, emb_szs: List[Tuple[int, int]]):
self.embeddings = t... | 1,480 | 28.62 | 102 | py |
CRB-active-3Ddet | CRB-active-3Ddet-main/setup.py | import os
import subprocess
from setuptools import find_packages, setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
def get_git_commit_number():
if not os.path.exists('.git'):
return '0000000'
cmd_out = subprocess.run(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE)
... | 3,960 | 31.467213 | 95 | py |
CRB-active-3Ddet | CRB-active-3Ddet-main/tools/test.py | import _init_path
import argparse
import datetime
import glob
import os
import re
import time
from pathlib import Path
import numpy as np
import torch
from tensorboardX import SummaryWriter
from eval_utils import eval_utils
from pcdet.config import cfg, cfg_from_list, cfg_from_yaml_file, log_config_to_file
from pcdet... | 10,291 | 43.747826 | 305 | py |
CRB-active-3Ddet | CRB-active-3Ddet-main/tools/demo.py | import argparse
import glob
from pathlib import Path
try:
import open3d
from visual_utils import open3d_vis_utils as V
OPEN3D_FLAG = True
except:
import mayavi.mlab as mlab
from visual_utils import visualize_utils as V
OPEN3D_FLAG = False
import numpy as np
import torch
from pcdet.config impo... | 3,750 | 32.19469 | 118 | py |
CRB-active-3Ddet | CRB-active-3Ddet-main/tools/train.py | import _init_path
import argparse
import datetime
import glob
import os
from pathlib import Path
import torch
import torch.nn as nn
from tensorboardX import SummaryWriter
import wandb
from pcdet.config import cfg, cfg_from_list, cfg_from_yaml_file, log_config_to_file
from pcdet.datasets import build_dataloader, buil... | 13,701 | 42.636943 | 195 | py |
CRB-active-3Ddet | CRB-active-3Ddet-main/tools/visualize.py | import _init_path
import argparse
import datetime
import glob
import os
import re
import time
from pathlib import Path
import pickle
import numpy as np
import torch
from tensorboardX import SummaryWriter
from eval_utils import eval_utils
from pcdet.config import cfg, cfg_from_list, cfg_from_yaml_file, log_config_to_fi... | 10,415 | 43.323404 | 305 | py |
CRB-active-3Ddet | CRB-active-3Ddet-main/tools/eval_utils/eval_utils.py | import pickle
import time
import numpy as np
import torch
import tqdm
from pcdet.models import load_data_to_gpu
from pcdet.utils import common_utils
def statistics_info(cfg, ret_dict, metric, disp_dict):
for cur_thresh in cfg.MODEL.POST_PROCESSING.RECALL_THRESH_LIST:
metric['recall_roi_%s' % str(cur_thr... | 10,481 | 39.16092 | 222 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.