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
politihop
politihop-master/Transformer-XH/transformer-xh/model/model.py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import torch import torch.nn as nn import torch.nn.functional as F import dgl from dgl import DGLGraph import dgl.function as fn from pytorch_transformers import * from pytorch_transformers.modeling_bert import BertModel, BertEncoder, BertPreTra...
8,979
35.803279
179
py
politihop
politihop-master/Transformer-XH/data/base.py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from torch.utils.data import Dataset, DataLoader from .utils import load_data class TransformerXHDataset(Dataset): def __init__(self, filename, config_model, isTrain=False, bert_tokenizer=None): self.config_model = config_model ...
574
26.380952
83
py
politihop
politihop-master/Transformer-XH/data/hotpotqa.py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # specific stuff for hotpot qa import torch from torch.utils.data import Dataset, DataLoader import dgl from dgl import DGLGraph import dgl.function as fn from .base import TransformerXHDataset from .utils import truncate_input_sequence def bat...
4,691
31.811189
207
py
politihop
politihop-master/Transformer-XH/data/fever.py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # the specific stuff of fever import torch from torch.utils.data import Dataset, DataLoader import dgl from dgl import DGLGraph import dgl.function as fn from .base import TransformerXHDataset from .utils import truncate_input_sequence def ba...
3,794
28.648438
143
py
causalpodnn
causalpodnn-main/causalPODNN.py
import warnings warnings.filterwarnings("ignore") import os import psutil import numpy as np import tensorflow as tf tf.keras.backend.set_floatx('float32') from tensorflow.keras import layers, Model import matplotlib.pyplot as plt import cv2 import podnn_tensorflow_train tf.get_logger().setLevel('INFO') from scipy.spat...
27,982
35.014157
153
py
causalpodnn
causalpodnn-main/podnn_tensorflow_train.py
""" This file provides five different classes for creating PODNN architectures in Tensorflow. The five modules are as follows: - InputLayer: Prepares data in parallel form to be consumable by the upcoming layers - ParallelLayer: creates a parallel sub-layer formed from unit it receives. - OrthogonalLayer1D: makes...
12,836
32.256477
122
py
PaddleSlim-develop
PaddleSlim-develop/demo/models/pvanet.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import paddle from paddle.nn.initializer import KaimingUniform from collections import namedtuple BLOCK_TYPE_MCRELU = 'BLOCK_TYPE_MCRELU' BLOCK_TYPE_INCEP = 'BLOCK_TYPE_INCEP' BlockConfig = namedtuple('BlockCon...
17,865
35.165992
83
py
PaddleSlim-develop
PaddleSlim-develop/docs/en/conf.py
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
5,438
30.622093
79
py
PaddleSlim-develop
PaddleSlim-develop/docs/zh_cn/conf.py
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
5,429
30.754386
79
py
PaddleSlim-develop
PaddleSlim-develop/example/post_training_quantization/pytorch_yolo_series/fine_tune.py
# Copyright (c) 2022 PaddlePaddle Authors. 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 of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
3,994
30.96
77
py
PaddleSlim-develop
PaddleSlim-develop/example/post_training_quantization/pytorch_yolo_series/post_quant.py
# Copyright (c) 2022 PaddlePaddle Authors. 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 of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
3,089
30.212121
80
py
NIPS2019DeepGamblers
NIPS2019DeepGamblers-master/main.py
from __future__ import print_function import argparse import os import shutil import time import random import math import numpy import torch import torch.nn as nn import torch.nn.parallel import torch.nn.functional as F import torch.backends.cudnn as cudnn import torch.optim as optim import torchvision.transforms as...
21,901
44.916143
235
py
NIPS2019DeepGamblers
NIPS2019DeepGamblers-master/dataset_utils.py
import os import torch from torch.utils.data import Dataset, DataLoader import torchvision.transforms.functional as F from torchvision import transforms, utils from PIL import Image class resized_dataset(Dataset): def __init__(self, dataset, transform=None, start=None, end=None, resize=None): self.data=[] ...
1,020
33.033333
105
py
NIPS2019DeepGamblers
NIPS2019DeepGamblers-master/models/cifar/preresnet.py
from __future__ import absolute_import '''Resnet for cifar dataset. Ported form https://github.com/facebook/fb.resnet.torch and https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py (c) YANG, Wei ''' import torch.nn as nn import math __all__ = ['preresnet'] def conv3x3(in_planes, out_planes, st...
4,624
28.08805
77
py
NIPS2019DeepGamblers
NIPS2019DeepGamblers-master/models/cifar/resnet.py
from __future__ import absolute_import '''Resnet for cifar dataset. Ported form https://github.com/facebook/fb.resnet.torch and https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py (c) YANG, Wei ''' import torch.nn as nn import math __all__ = ['resnet'] def conv3x3(in_planes, out_planes, strid...
4,662
28.14375
77
py
NIPS2019DeepGamblers
NIPS2019DeepGamblers-master/models/cifar/vgg.py
import torch.nn as nn import torch.utils.model_zoo as model_zoo import math __all__ = [ 'VGG', 'vgg16', 'vgg16_bn' ] class VGG(nn.Module): def __init__(self, features, num_classes=1000, input_size = 32): super(VGG, self).__init__() self.features = features if input_size == 32: ...
2,762
32.289157
133
py
NIPS2019DeepGamblers
NIPS2019DeepGamblers-master/models/cifar/densenet.py
import torch import torch.nn as nn import torch.nn.functional as F import math __all__ = ['densenet'] from torch.autograd import Variable class Bottleneck(nn.Module): def __init__(self, inplanes, expansion=4, growthRate=12, dropRate=0): super(Bottleneck, self).__init__() planes = expansion * gr...
4,724
30.711409
99
py
NIPS2019DeepGamblers
NIPS2019DeepGamblers-master/models/cifar/resnext.py
from __future__ import division """ Creates a ResNeXt Model as defined in: Xie, S., Girshick, R., Dollar, P., Tu, Z., & He, K. (2016). Aggregated residual transformations for deep neural networks. arXiv preprint arXiv:1611.05431. import from https://github.com/prlz77/ResNeXt.pytorch/blob/master/models/model.py """ i...
5,597
43.428571
144
py
NIPS2019DeepGamblers
NIPS2019DeepGamblers-master/models/cifar/__init__.py
from __future__ import absolute_import """The models subpackage contains definitions for the following model for CIFAR10/CIFAR100 architectures: - `AlexNet`_ - `VGG`_ - `ResNet`_ - `SqueezeNet`_ - `DenseNet`_ You can construct a model with random weights by calling its constructor: .. code:: python import...
2,250
30.704225
90
py
NIPS2019DeepGamblers
NIPS2019DeepGamblers-master/models/cifar/alexnet.py
'''AlexNet for CIFAR10. FC layers are removed. Paddings are adjusted. Without BN, the start learning rate should be 0.01 (c) YANG, Wei ''' import torch.nn as nn __all__ = ['alexnet'] class AlexNet(nn.Module): def __init__(self, num_classes=10): super(AlexNet, self).__init__() self.features = n...
1,359
29.222222
69
py
NIPS2019DeepGamblers
NIPS2019DeepGamblers-master/models/cifar/wrn.py
import math import torch import torch.nn as nn import torch.nn.functional as F __all__ = ['wrn'] class BasicBlock(nn.Module): def __init__(self, in_planes, out_planes, stride, dropRate=0.0): super(BasicBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.relu1 = nn.ReLU(inplac...
3,902
40.521277
116
py
NIPS2019DeepGamblers
NIPS2019DeepGamblers-master/utils/misc.py
'''Some helper functions for PyTorch, including: - get_mean_and_std: calculate the mean and std value of dataset. - msr_init: net parameter initialization. - progress_bar: progress bar mimic xlua.progress. ''' import errno import os import sys import time import math import torch.nn as nn import torch.nn.i...
2,206
28.039474
110
py
NIPS2019DeepGamblers
NIPS2019DeepGamblers-master/utils/logger.py
# A simple torch style logger # (C) Wei YANG 2017 from __future__ import absolute_import import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import os import sys import numpy as np __all__ = ['Logger', 'LoggerMonitor', 'savefig', 'closefig'] def savefig(fname, dpi=None): dpi = 150 if dpi == ...
4,482
32.207407
100
py
NIPS2019DeepGamblers
NIPS2019DeepGamblers-master/utils/visualize.py
import matplotlib.pyplot as plt import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import numpy as np from .misc import * __all__ = ['make_image', 'show_batch', 'show_mask', 'show_mask_single'] # functions to show an image def make_image(img, mean=(0,0,0), std=(1,1,1)...
3,795
33.509091
95
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/nn/mlp.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import torch.nn as nn from code.nn.utils import ReactionDiffusionParametersScaler act_dict = {"ReLU": nn.ReLU(), "Softplus": nn.Softplus(), "SELU": nn.SELU(), "ReactionDiffusionPar...
1,409
30.333333
85
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/nn/utils.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import torch import torch.nn as nn class Permute(nn.Module): def __init__(self, order): super().__init__() self.order = order def forward(self, x): return x.permute(self.order) cla...
788
25.3
65
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/nn/unet.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable from torch.utils.data import Dataset, DataLoader import torchvision class Block(nn.M...
7,275
35.38
112
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/simulators/RLCCircuit.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import torch import torch.nn as nn from torchdyn.core import NeuralODE from torchdyn import * from code.simulators.GenericSimulator import PhysicalModel import math class RLCODE(PhysicalModel): def __init__(self...
4,665
46.612245
126
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/simulators/DampedPendulum.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import torch import torch.nn as nn from torchdyn.core import NeuralODE from torchdyn import * from code.simulators.GenericSimulator import PhysicalModel import math class DampedPendulumODE(PhysicalModel): def __...
5,636
43.039063
135
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/simulators/DoublePendulum.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import torch import torch.nn as nn from torchdyn.core import NeuralODE from torchdyn import * from code.simulators.GenericSimulator import PhysicalModel import math class DoublePendulumODE(PhysicalModel): def __...
4,266
40.833333
119
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/simulators/GenericSimulator.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import torch import torch.nn as nn class PhysicalModel(nn.Module): def __init__(self, param_values, trainable_param): super(PhysicalModel, self).__init__() self._nb_parameters = len(trainable_par...
1,876
29.770492
115
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/simulators/NoSimulator.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import torch import torch.nn as nn from torchdyn.core import NeuralODE from torchdyn import * from code.simulators.GenericSimulator import PhysicalModel import math class NoSimulator(PhysicalModel): def __init__...
643
23.769231
64
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/simulators/ReactionDiffusion.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import torch import torch.nn as nn from torchdyn.core import NeuralODE from torchdyn import * from code.simulators.GenericSimulator import PhysicalModel import math import torch.nn.functional as F # This code is stro...
5,026
39.869919
115
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/scripts/run_experiments_robustness.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import shutil import torch from matplotlib import pyplot as plt from torch import nn from code.hybrid_models.APHYNITY import APHYNITYAutoencoderDoublePendulum from code.simulators import PhysicalModel from code.simu...
15,605
52.262799
132
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/scripts/run_experiments.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import shutil import torch from matplotlib import pyplot as plt from torch import nn from code.hybrid_models.APHYNITY import APHYNITYAutoencoderDoublePendulum from code.simulators import PhysicalModel from code.simu...
15,872
53.546392
125
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/hybrid_models/APHYNITY.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import math import pickle import torch.nn as nn from code.simulators import PhysicalModel, NoSimulator import torch from code.nn import MLP, ConditionalUNet, Permute, act_dict from torchdiffeq import odeint from code...
26,155
44.887719
146
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/hybrid_models/HVAE.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import math import torch.nn as nn from matplotlib import pyplot as plt from code.simulators import PhysicalModel, NoSimulator import torch from code.nn import MLP, act_dict, ConditionalUNet, ConditionalUNetReactionD...
39,125
47.007362
146
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/hybrid_models/HybridAutoencoder.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. from abc import abstractmethod import torch.nn as nn import torch class HybridAutoencoder(nn.Module): def __init__(self): super(HybridAutoencoder, self).__init__() @abstractmethod def forward(se...
884
26.65625
96
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/utils/double_pendulum.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import math import cv2 import numpy as np import pandas as pd import torch import torch.utils.data as data_utils def xy_to_theta(dx, dy): theta = np.arctan2(dy, dx) + math.pi / 2 # cond_1 = ((dy > 0) & (the...
2,883
33.333333
116
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/utils/loaders.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import torch.utils.data as data_utils import pickle def load_data(data_path, device): with open(r"%s/train.pkl" % data_path, "rb") as output_file: t_train, x_train, true_param_train = pickle.load(output_...
1,102
51.52381
154
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/utils/utils.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import torch from matplotlib import pyplot as plt from torch import nn from code.hybrid_models import HybridAutoencoder from code.hybrid_models.APHYNITY import APHYNITYAutoencoderDoublePendulum from code.hybrid_model...
5,484
45.483051
116
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/utils/plotter.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import matplotlib.pyplot as plt from textwrap import wrap import torch def plot_curves(t, x_pred, x_obs, title, labels, save_name): fig = plt.figure(figsize=(24, 12)) fig.suptitle("\n".join(wrap(title, 150)...
7,184
45.655844
120
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/data/RLC/GenerateDataset.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. from code.simulators import RLCCircuit import torch from tqdm import tqdm import os import pickle def gen_data(n=500, shifted="False"): if shifted == "small_all": distributions = { "R": lambd...
6,038
47.312
79
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/data/ReactionDiffusion/GenerateDataset.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. from code.simulators import ReactionDiffusion import torch from tqdm import tqdm import os import pickle def gen_data(n=500, shifted=""): if shifted == "small_all": distributions = { "a": lam...
3,946
40.114583
79
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/data/DampedPendulum/GenerateDataset.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. from code.simulators import DampedPendulum import torch from tqdm import tqdm import os import pickle #import turibolt as bolt import argparse def gen_data(n=500, shifted=""): if shifted == "small_all": ...
4,462
39.572727
113
py
ml-robust-expert-augmentations
ml-robust-expert-augmentations-main/code/data/DoublePendulum/GenerateDataset.py
# For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. import math import pandas as pd import code.simulators.DoublePendulum as DP import torch from torchdiffeq import odeint from tqdm import tqdm import os import pickle import argparse from code.utils.double_pendulum ...
6,221
47.609375
116
py
moment-neural-network
moment-neural-network-main/examples/mnist/mnist.py
import torch from mnn import snn, utils class MnistTrainFuncs(utils.training_tools.TrainProcessCollections): """ The general pipeline to construct MNN for training. """ def set_random_seed(self, seed): """ This function can fix all random seed (numpy, pytorch) for better reproducibility...
12,025
49.529412
229
py
moment-neural-network
moment-neural-network-main/mnn/models/mlp.py
# -*- coding: utf-8 -*- from typing import Tuple, Optional import torch from torch import Tensor from .. import mnn_core def _general_forward(inputs, feature_extractor: torch.nn.ModuleList, decoder: Optional[torch.nn.Module] = None): u, cov = inputs for module in feature_extractor: u, cov = module(u,...
5,606
41.157895
156
py
moment-neural-network
moment-neural-network-main/mnn/mnn_core/mnn_utils.py
# -*- coding: utf-8 -*- import numpy as np from . import fast_dawson import torch from torch import Tensor from typing import Tuple class Param_Container: """ args: _vol_rest: the rest voltage of a neuron _vol_th: the fire threshold of a neuron _t_ref: the refractory time of a neuoron ...
16,921
37.546697
119
py
moment-neural-network
moment-neural-network-main/mnn/mnn_core/__init__.py
# -*- coding: utf-8 -*- from . import nn from .mnn_pytorch import mnn_activate_trio, mnn_activate_no_rho, get_core_attr, set_core_attr, reset_core_attr from .mnn_utils import Mnn_Core_Func
188
46.25
110
py
moment-neural-network
moment-neural-network-main/mnn/mnn_core/mnn_pytorch.py
# -*- coding: utf-8 -*- """ Created on Sat Oct 3 14:49:43 2020 Copyright 2020 Zhichao Zhu, ISTBI, Fudan University China """ from typing import Any import torch from .mnn_utils import * mnn_core_func = Mnn_Core_Func() def _batch_detach(*args): temp = list() for i in args: temp.append(i.cpu().detach...
4,871
38.934426
160
py
moment-neural-network
moment-neural-network-main/mnn/mnn_core/nn/batch_norm.py
# -*- coding: utf-8 -*- from typing import Tuple import torch from torch import Tensor from torch.nn import init from torch.nn.parameter import Parameter from . import functional class BatchNorm1dDuo(torch.nn.Module): __constant__ = ['num_features'] num_features: int def __init__(self, num_features: int,...
3,256
36.436782
113
py
moment-neural-network
moment-neural-network-main/mnn/mnn_core/nn/activation.py
# -*- coding: utf-8 -*- import torch from torch import Tensor from typing import Tuple from . import functional from ..mnn_pytorch import mnn_activate_trio, mnn_activate_no_rho class OriginMnnActivation(torch.nn.Module): def forward(self, *args) -> Tuple[Tensor, Tensor]: u, cov = functional.parse_input(ar...
686
31.714286
64
py
moment-neural-network
moment-neural-network-main/mnn/mnn_core/nn/functional.py
import math import torch from torch import Tensor from typing import Tuple, Any, Optional import torch.nn.functional as F class ModifyDiagToOne(torch.autograd.Function): @staticmethod def forward(ctx: Any, rho: Tensor) -> Tensor: torch.diagonal(rho, dim1=-1, dim2=-2).data.fill_(1.0) return rho...
6,083
36.097561
131
py
moment-neural-network
moment-neural-network-main/mnn/mnn_core/nn/custom_batch_norm.py
# -*- coding: utf-8 -*- import torch from torch.nn.parameter import Parameter from torch import Tensor from typing import Optional, Tuple from . import functional def _compute_weight(gamma: Optional[Tensor], var, eps=1e-5): if gamma is None: return 1 / torch.sqrt(var + eps) else: return gamma ...
4,938
41.213675
136
py
moment-neural-network
moment-neural-network-main/mnn/mnn_core/nn/linear.py
# -*- coding: utf-8 -*- import torch import math from typing import Tuple, Optional from torch.nn.parameter import Parameter from torch.nn import init import numpy as np import torch.nn.functional as F from torch import Tensor from . import functional class LinearDuo(torch.nn.Module): __constant__ = ['in_features...
5,152
37.17037
134
py
moment-neural-network
moment-neural-network-main/mnn/mnn_core/nn/mconv2d.py
import torch class MomentConv2d(torch.nn.Module): __constant__ = ['in_channels', 'out_channels','kernel_size', 'stride'] in_channels: int out_channels: int kernel_size: int stride: int def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int) -> None: super...
3,520
38.561798
120
py
moment-neural-network
moment-neural-network-main/mnn/mnn_core/nn/criterion.py
import torch from torch import Tensor from torch.nn import functional as F from typing import Tuple from . import functional class LabelSmoothing(torch.nn.Module): def __init__(self, num_class: int = 10, alpha: float = 0.1) -> None: super(LabelSmoothing, self).__init__() assert 0. <= alpha < 1. ...
8,229
42.544974
150
py
moment-neural-network
moment-neural-network-main/mnn/mnn_core/nn/ensemble.py
# -*- coding: utf-8 -*- from typing import Tuple, Optional import torch from torch import Tensor from .activation import OriginMnnActivation from . import linear, batch_norm, custom_batch_norm class EnsembleLinearDuo(torch.nn.Module): def __init__(self, in_features: int, out_features: int, ln_bias_mean: bool = ...
2,733
45.338983
130
py
moment-neural-network
moment-neural-network-main/mnn/snn/snn2loihi.py
import os import torch import nxsdk.api.n2a as nx from nxsdk.api.enums.api_enums import ProbeParameter from nxsdk.graph.monitor.probes import PerformanceProbeCondition from n2_apps.modules.slayer import src as nxSlayer from n2_apps.modules.slayer.src.slayer2loihi import Slayer2Loihi import seaborn as sns from scipy imp...
35,284
45.305774
177
py
moment-neural-network
moment-neural-network-main/mnn/snn/functional.py
# -*- coding: utf-8 -*- import torch import numpy as np from .. import mnn_core from torch import Tensor from .. import utils from . import base, mnn2snn def modify_value_by_condition(data, condition): u, cov = data if 'mask_mean' in condition: u = torch.zeros_like(u) elif 'shuffle_cov' in conditio...
10,165
40.663934
141
py
moment-neural-network
moment-neural-network-main/mnn/snn/mnn2snn.py
# -*- coding: utf-8 -*- import types import torch from torch import Tensor from torch.nn import functional as F from collections import defaultdict from .. import mnn_core from .. import models from . import base from .base import SpikeMonitor, GeneralCurrentGenerator, LIFNeurons @torch.no_grad() def ln_params_transf...
13,757
38.648415
124
py
moment-neural-network
moment-neural-network-main/mnn/snn/base/base_type.py
# -*- coding: utf-8 -*- import torch class BaseCurrentGenerator(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward(self, *args, **kwargs): raise NotImplementedError def reset(self, *args, **kwargs): raise NotImplementedError class BaseMonitor(to...
1,216
23.34
44
py
moment-neural-network
moment-neural-network-main/mnn/snn/base/neurons.py
# -*- coding: utf-8 -*- import torch from torch import Tensor from .base_type import BaseNeuronType class LIFNeurons(BaseNeuronType): __constants__ = ['L', 'V_th', 'V_res', 'V_spk', 'dt', 'T_ref'] def __init__(self, num_neurons, L=1/20, V_th=20, V_res=0., V_spk=50., dt=1e-1, T_ref=5., init_vol=None,spike_dt...
2,666
39.409091
156
py
moment-neural-network
moment-neural-network-main/mnn/snn/base/functional.py
# -*- coding: utf-8 -*- import torch from torch import Tensor import numpy as np from typing import Optional def sample_size(num_neurons, num_steps=None): if num_steps is None: num = [1, num_neurons] else: if isinstance(num_neurons, int): num = (num_steps, num_neurons) else...
1,187
36.125
135
py
moment-neural-network
moment-neural-network-main/mnn/snn/base/probes.py
# -*- coding: utf-8 -*- import torch from collections import defaultdict from typing import Union, List import math from .base_type import BaseProbe class NeuronProbe(BaseProbe): def __init__(self, attr: Union[str, List], dt: float = 1e-2, probe_interval: int = 1,...
1,877
35.115385
91
py
moment-neural-network
moment-neural-network-main/mnn/snn/base/currents.py
# -*- coding: utf-8 -*- import numpy as np import torch from torch import Tensor from typing import Optional from .base_type import BaseCurrentGenerator from .functional import sample_size, pregenerate_gaussian_current class PregeneratedCurrent(BaseCurrentGenerator): def __init__(self, pregenerated_current: Tens...
5,926
37.993421
138
py
moment-neural-network
moment-neural-network-main/mnn/snn/base/monitors.py
# -*- coding: utf-8 -*- import torch from torch import Tensor from .base_type import BaseMonitor class SpikeMonitor(BaseMonitor): def __init__(self, num_neurons, dt=1e-1, **kwargs): super(SpikeMonitor, self).__init__() self.register_buffer('monitor', torch.zeros(num_neurons).unsqueeze(0).to(torch....
1,296
34.054054
113
py
moment-neural-network
moment-neural-network-main/mnn/utils/training_tools/general_train.py
import os import shutil import tempfile import time from enum import Enum import numpy as np import torch import torch.backends.cudnn as cudnn from . import general_prepare from . import functional as func class Summary(Enum): NONE = 0 AVERAGE = 1 SUM = 2 COUNT = 3 class AverageMeter(object): "...
21,713
39.435754
144
py
moment-neural-network
moment-neural-network-main/mnn/utils/training_tools/general_prepare.py
import argparse import os import random import numpy as np import torch.backends.cudnn as cudnn import torch.nn import torchvision import yaml from torch.utils.data import DataLoader from torch.utils.data.distributed import DistributedSampler import warnings try: from torch.distributed.optim import ZeroRedundancy...
12,207
39.423841
128
py
moment-neural-network
moment-neural-network-main/mnn/utils/training_tools/functional.py
# -*- coding: utf-8 -*- import yaml import torch import os import warnings from torch import Tensor, distributed as dist, multiprocessing as mp from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import DistributedSampler, DataLoader class RecordMethods: @staticmethod def make_d...
6,629
29.552995
119
py
moment-neural-network
moment-neural-network-main/mnn/utils/dataloaders/mnist_loader.py
# -*- coding: utf-8 -*- from typing import Callable import torchvision from torch.utils.data import DataLoader from torchvision import transforms def classic_mnist_loader(data_dir: str, train_batch: int = 128, test_batch: int = 100, transform_train: Callable = transforms.Compose([transforms....
1,239
52.913043
118
py
csn
csn-main/src/models/dist_prob_layer.py
import tensorflow as tf from tensorflow import keras class DistProbLayer(keras.layers.Layer): def __init__(self, num_classes, duplication_factor): # Note that we assume the same number of classes and prototypes. super(DistProbLayer, self).__init__() self.num_classes = num_classes self.dup...
1,395
44.032258
122
py
csn
csn-main/src/models/proto_model.py
import networkx as nx import numpy as np import tensorflow as tf from classification_models.tfkeras import Classifiers from tensorflow import keras from tensorflow.keras import layers import pandas as pd import seaborn as sn import cv2 import pickle as pkl import random from scipy import stats from src.data_parsing.mn...
76,608
51.328552
152
py
csn
csn-main/src/models/proto_layer.py
import tensorflow as tf from tensorflow import keras import numpy as np class ProtoLayer(tf.keras.layers.Layer): def __init__(self, num_prototypes, dim, fixed_protos=None, in_plane=True, unit_cube_init=False): super(ProtoLayer, self).__init__() self.num_prototypes = num_prototypes self.lat...
5,494
51.333333
127
py
csn
csn-main/src/scripts/train_parity_after.py
import numpy as np import tensorflow as tf from src.data_parsing.mnist_data import get_digit_data, make_noisy from src.models.proto_model import ProtoModel from src.utils.gpu import set_gpu_config set_gpu_config() print(tf.test.is_gpu_available()) tf.compat.v1.disable_eager_execution() latent_dim = 32 noise_level =...
4,160
36.486486
114
py
csn
csn-main/src/scripts/train_adult.py
import numpy as np from tensorflow import keras import tensorflow as tf from src.data_parsing.adult_data import get_adult_data from src.models.proto_model import ProtoModel from src.utils.gpu import set_gpu_config set_gpu_config() print(tf.test.is_gpu_available()) tf.compat.v1.disable_eager_execution() wass_setup = ...
4,326
44.072917
178
py
csn
csn-main/src/scripts/baseline_fashion_tree_edits.py
import numpy as np import tensorflow as tf from src.data_parsing.mnist_data import get_fashion_data, make_noisy, get_fashion_tree from src.models.proto_model import ProtoModel from src.utils.eval import trees_match, graph_edit_dist from src.utils.gpu import set_gpu_config from src.utils.to_files import write_to_file ...
4,279
40.960784
122
py
csn
csn-main/src/scripts/train_fashion.py
import numpy as np import tensorflow as tf from src.data_parsing.mnist_data import get_fashion_data, make_noisy, get_fashion_tree from src.models.proto_model import ProtoModel from src.utils.gpu import set_gpu_config from src.utils.eval import trees_match, graph_edit_dist from src.utils.plotting import plot_mst from s...
5,032
45.601852
203
py
csn
csn-main/src/scripts/train_correlated.py
import numpy as np import tensorflow as tf from src.models.proto_model import ProtoModel import tensorflow.keras as keras from src.utils.gpu import set_gpu_config set_gpu_config() print(tf.test.is_gpu_available()) tf.compat.v1.disable_eager_execution() factor = 1 def get_rainy_data(num_examples=10000): true_tem...
3,163
38.55
189
py
csn
csn-main/src/scripts/train_bolts.py
import networkx as nx import numpy as np import tensorflow as tf from src.data_parsing.bolts.data_parser import DataParser from src.models.proto_model import ProtoModel from src.utils.eval import trees_match, graph_edit_dist from src.utils.gpu import set_gpu_config from src.utils.to_files import write_to_file set_gpu...
8,443
47.251429
255
py
csn
csn-main/src/scripts/train_german.py
import numpy as np import tensorflow as tf import tensorflow.keras as keras from src.data_parsing.german_data import get_german_data from src.models.proto_model import ProtoModel from src.utils.gpu import set_gpu_config set_gpu_config() print(tf.test.is_gpu_available()) tf.compat.v1.disable_eager_execution() wass_se...
4,186
40.455446
189
py
csn
csn-main/src/scripts/train_hierarchical.py
# Mycal's recreation of the hierarchical prototype network training idea. import numpy as np import tensorflow as tf import tensorflow.keras as keras from src.data_parsing.mnist_data import get_digit_data, make_noisy, get_parity_tree from src.models.proto_model import ProtoModel from src.utils.to_files import write_t...
4,534
46.239583
169
py
csn
csn-main/src/scripts/train_mnist_unsupervised.py
import numpy as np import tensorflow as tf from src.data_parsing.mnist_data import get_digit_data, make_noisy, get_guided_tree from src.models.proto_model import ProtoModel from src.utils.eval import trees_match from src.utils.gpu import set_gpu_config set_gpu_config() print(tf.test.is_gpu_available()) tf.compat.v1....
2,955
47.459016
144
py
csn
csn-main/src/scripts/train_cifar100_deep.py
import numpy as np import tensorflow as tf from src.data_parsing.cifar_data import get_deep_data, get_deep_tree from src.models.proto_model import ProtoModel from src.utils.eval import trees_match, graph_edit_dist from src.utils.gpu import set_gpu_config from src.utils.to_files import write_to_file set_gpu_config() ...
3,332
48.746269
203
py
csn
csn-main/src/scripts/train_hierarchical_fashion.py
# Mycal's recreation of the hierarchical prototype network training idea. import numpy as np import tensorflow as tf import tensorflow.keras as keras from src.data_parsing.mnist_data import get_fashion_data, make_noisy, get_fashion_tree from src.models.proto_model import ProtoModel from src.utils.to_files import writ...
5,242
44.991228
217
py
csn
csn-main/src/scripts/train_cifar10.py
import tensorflow as tf from src.data_parsing.cifar_data import get_cifar10_data from src.models.proto_model import ProtoModel from src.utils.gpu import set_gpu_config set_gpu_config() print(tf.test.is_gpu_available()) tf.compat.v1.disable_eager_execution() latent_dim = 40 x_train, y_train, y_train_one_hot, x_test,...
1,822
41.395349
138
py
csn
csn-main/src/scripts/baseline_digit_tree_edits.py
import numpy as np import tensorflow as tf from src.data_parsing.mnist_data import get_digit_data, get_parity_tree from src.models.proto_model import ProtoModel from src.utils.eval import trees_match, graph_edit_dist from src.utils.gpu import set_gpu_config from src.utils.to_files import write_to_file set_gpu_config(...
3,181
43.194444
114
py
csn
csn-main/src/scripts/train_mnist_elastic.py
import tensorflow as tf from src.data_parsing.mnist_data import get_digit_data from src.models.proto_model import ProtoModel from src.utils.gpu import set_gpu_config set_gpu_config() print(tf.test.is_gpu_available()) tf.compat.v1.disable_eager_execution() latent_dim = 40 x_train, y_train, y_train_one_hot, x_test, y...
1,528
38.205128
123
py
csn
csn-main/src/scripts/train_hierarchical_cifar100.py
import numpy as np import tensorflow as tf import tensorflow.keras as keras from src.data_parsing.cifar_data import get_cifar100_data, get_cifar100_tree, get_cifar100_mapping from src.models.proto_model import ProtoModel from src.utils.eval import trees_match, graph_edit_dist from src.utils.gpu import set_gpu_config f...
4,087
47.094118
140
py
csn
csn-main/src/scripts/train_mnist.py
import numpy as np import tensorflow as tf from src.data_parsing.mnist_data import get_digit_data, make_noisy, get_parity_tree from src.models.proto_model import ProtoModel from src.utils.eval import trees_match, graph_edit_dist from src.utils.gpu import set_gpu_config from src.utils.to_files import write_to_file set...
4,387
47.755556
203
py
csn
csn-main/src/scripts/train_cifar100.py
import numpy as np import tensorflow as tf from src.data_parsing.cifar_data import get_cifar100_data, get_cifar100_tree from src.models.proto_model import ProtoModel from src.utils.eval import trees_match, graph_edit_dist from src.utils.gpu import set_gpu_config from src.utils.to_files import write_to_file set_gpu_co...
2,857
47.440678
199
py
csn
csn-main/src/data_parsing/german_data.py
import numpy as np import pandas as pd from pandas.api.types import is_string_dtype def normalize(df): result = df.copy() max_value = df.max() min_value = df.min() result = (df - min_value) / (max_value - min_value) return result def rebalance(x, p, y, dist): keep_x = [] keep_p = [] ...
3,492
38.247191
116
py
csn
csn-main/src/data_parsing/mnist_data.py
from keras.datasets import fashion_mnist from keras.datasets import mnist from tensorflow.keras.utils import to_categorical import networkx as nx def get_digit_data(): # Load the data. (x_train, y_train), (x_test, y_test) = mnist.load_data() image_size = x_train.shape[1] original_dim = image_size * im...
6,820
34.526042
105
py
csn
csn-main/src/data_parsing/cifar_data.py
import networkx as nx import numpy as np from keras.datasets import cifar10, cifar100 from tensorflow.keras.utils import to_categorical cifar_fine_labels = [ 'apple', # id 0 'aquarium_fish', 'baby', 'bear', 'beaver', 'bed', 'bee', 'beetle', 'bicycle', 'bottle', 'bowl', ...
23,121
34.35474
201
py
csn
csn-main/src/data_parsing/inaturalist/inaturalist_dataflow.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: iNaturalist.py from tensorflow.keras.utils import to_categorical import json import os import os.path as osp import pickle import cv2 import numpy as np __all__ = ['iNaturalistMeta', 'iNaturalist', 'iNaturalistFiles'] ground_truth_dir = '/mnt/mount_sda2/src/inatura...
8,967
35.307692
110
py
csn
csn-main/tst/test_proto_layer.py
import unittest from src.models.proto_layer import ProtoLayer from tensorflow import keras import numpy as np from src.models.proto_model import ProtoModel class MyTestCase(unittest.TestCase): def setUp(self) -> None: keras.backend.clear_session() def test_projecting1(self): num_prototypes = 2...
2,764
38.5
108
py
Generalization-and-Memorization-in-Sparse-Training
Generalization-and-Memorization-in-Sparse-Training-main/run.py
""" [Title] run.py [Usage] The file to train a model and save model information. [Functions to be added] [ ] iterative training [ ] sparsity-aware initialization [ ] random pruning (random mask?) [ ] SNIP pruning """ from loader import load_dataset from optim import Model from helper import pruner, plo...
19,948
44.965438
120
py
Generalization-and-Memorization-in-Sparse-Training
Generalization-and-Memorization-in-Sparse-Training-main/exp-spectrum.py
""" [Title] experiment-spectrum.py [Usage] This is a file to calculate the hessian spectrum. """ from helper import utils, pruner, hessian from pathlib import Path from torch import nn from PIL import Image from functools import reduce from abc import ABC, abstractmethod from torch.utils.data import DataLoader from to...
6,223
33.577778
86
py
Generalization-and-Memorization-in-Sparse-Training
Generalization-and-Memorization-in-Sparse-Training-main/exp-trace.py
""" [Title] experiment-trace.py [Usage] This is a file to calculate the hessian traces. """ # from pyhessian import hessian import pyhessian from helper import utils, pruner from pathlib import Path from torch import nn from PIL import Image from functools import reduce from abc import ABC, abstractmethod from torch.u...
5,001
30.459119
85
py