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 |
|---|---|---|---|---|---|---|
STTS | STTS-main/VideoSwin/tests/test_runtime/test_inference.py | import mmcv
import numpy as np
import pytest
import torch
import torch.nn as nn
from mmaction.apis import inference_recognizer, init_recognizer
video_config_file = 'configs/recognition/tsn/tsn_r50_video_inference_1x1x3_100e_kinetics400_rgb.py' # noqa: E501
frame_config_file = 'configs/recognition/tsn/tsn_r50_inferen... | 6,972 | 37.313187 | 119 | py |
STTS | STTS-main/VideoSwin/tests/test_runtime/test_lr.py | import logging
import shutil
import sys
import tempfile
from unittest.mock import MagicMock, call
import torch
import torch.nn as nn
from mmcv.runner import IterTimerHook, PaviLoggerHook, build_runner
from torch.utils.data import DataLoader
def test_tin_lr_updater_hook():
sys.modules['pavi'] = MagicMock()
lo... | 3,291 | 26.898305 | 75 | py |
STTS | STTS-main/VideoSwin/tests/test_runtime/test_apis_test.py | import sys
import warnings
from unittest.mock import MagicMock, Mock, patch
import pytest
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
# TODO import test functions from mmcv and delete them from mmaction2
try:
from mmcv.engine import (collect_results_cpu, multi_gpu_test,
... | 3,346 | 27.12605 | 74 | py |
STTS | STTS-main/VideoSwin/tests/test_models/base.py | import os.path as osp
import mmcv
import numpy as np
import torch
from mmcv.utils import _BatchNorm
def check_norm_state(modules, train_state):
"""Check if norm layer is in correct train state."""
for mod in modules:
if isinstance(mod, _BatchNorm):
if mod.training != train_state:
... | 4,723 | 27.981595 | 78 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_roi_extractor.py | import torch
from mmaction.models import SingleRoIExtractor3D
def test_single_roi_extractor3d():
roi_extractor = SingleRoIExtractor3D(
roi_layer_type='RoIAlign',
featmap_stride=16,
output_size=8,
sampling_ratio=0,
pool_mode='avg',
aligned=True,
with_tempora... | 1,945 | 32.551724 | 78 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_common.py | import os.path as osp
import pytest
import torch
from mmaction.models.common import LFB, TAM, Conv2plus1d, ConvAudio
def test_conv2plus1d():
with pytest.raises(AssertionError):
# Length of kernel size, stride and padding must be the same
Conv2plus1d(3, 8, (2, 2))
conv_2plus1d = Conv2plus1d(... | 2,754 | 26.55 | 77 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_backbones.py | import copy
import pytest
import torch
import torch.nn as nn
from mmcv.utils import _BatchNorm
from mmaction.models import (C3D, X3D, MobileNetV2TSM, ResNet2Plus1d,
ResNet3dCSN, ResNet3dSlowFast, ResNet3dSlowOnly,
ResNetAudio, ResNetTIN, ResNetTSM, TANet)
from... | 25,467 | 34.971751 | 100 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_neck.py | import copy
import pytest
import torch
from mmaction.models import TPN
from .base import generate_backbone_demo_inputs
def test_tpn():
"""Test TPN backbone."""
tpn_cfg = dict(
in_channels=(1024, 2048),
out_channels=1024,
spatial_modulation_cfg=dict(
in_channels=(1024, 20... | 2,850 | 31.770115 | 73 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_gradcam.py | import pytest
import torch
from mmaction.models import build_recognizer
from mmaction.utils.gradcam_utils import GradCAM
from .base import generate_gradcam_inputs, get_recognizer_cfg
def _get_target_shapes(input_shape, num_classes=400, model_type='2D'):
if model_type not in ['2D', '3D']:
raise ValueError... | 8,364 | 35.369565 | 79 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_head.py | import os.path as osp
import tempfile
from unittest.mock import Mock, patch
import numpy as np
import pytest
import torch
import torch.nn as nn
import mmaction
from mmaction.models import (ACRNHead, AudioTSNHead, BBoxHeadAVA, FBOHead,
I3DHead, LFBInferHead, SlowFastHead, TPNHead,
... | 17,583 | 34.097804 | 79 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_localizers/test_bmn.py | import numpy as np
import torch
from mmaction.models import build_localizer
from ..base import get_localizer_cfg
def test_bmn():
model_cfg = get_localizer_cfg(
'bmn/bmn_400x100_2x8_9e_activitynet_feature.py')
if torch.cuda.is_available():
localizer_bmn = build_localizer(model_cfg.model).cuda... | 1,758 | 30.410714 | 66 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_localizers/test_ssn.py | import copy
import mmcv
import pytest
import torch
from mmaction.models import build_localizer
def test_ssn_train():
train_cfg = mmcv.ConfigDict(
dict(
ssn=dict(
assigner=dict(
positive_iou_threshold=0.7,
background_iou_threshold=0.01,
... | 7,989 | 38.359606 | 78 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_localizers/test_pem.py | import torch
from mmaction.models import build_localizer
from ..base import get_localizer_cfg
def test_pem():
model_cfg = get_localizer_cfg(
'bsn/bsn_pem_400x100_1x16_20e_activitynet_feature.py')
localizer_pem = build_localizer(model_cfg.model)
bsp_feature = torch.rand(8, 100, 32)
reference_... | 1,294 | 27.777778 | 65 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_localizers/test_tem.py | import torch
from mmaction.models import build_localizer
from ..base import get_localizer_cfg
def test_tem():
model_cfg = get_localizer_cfg(
'bsn/bsn_tem_400x100_1x16_20e_activitynet_feature.py')
localizer_tem = build_localizer(model_cfg.model)
raw_feature = torch.rand(8, 400, 100)
gt_bbox =... | 759 | 30.666667 | 74 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_recognizers/test_recognizer2d.py | import torch
from mmaction.models import build_recognizer
from ..base import generate_recognizer_demo_inputs, get_recognizer_cfg
def test_tsn():
config = get_recognizer_cfg('tsn/tsn_r50_1x1x3_100e_kinetics400_rgb.py')
config.model['backbone']['pretrained'] = None
recognizer = build_recognizer(config.mod... | 8,541 | 29.29078 | 76 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_recognizers/test_recognizer3d.py | import torch
from mmaction.models import build_recognizer
from ..base import generate_recognizer_demo_inputs, get_recognizer_cfg
def test_i3d():
config = get_recognizer_cfg('i3d/i3d_r50_32x2x1_100e_kinetics400_rgb.py')
config.model['backbone']['pretrained2d'] = False
config.model['backbone']['pretrained'... | 9,327 | 31.84507 | 77 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_recognizers/test_audio_recognizer.py | import torch
from mmaction.models import build_recognizer
from ..base import generate_recognizer_demo_inputs, get_audio_recognizer_cfg
def test_audio_recognizer():
config = get_audio_recognizer_cfg(
'resnet/tsn_r18_64x1x1_100e_kinetics400_audio_feature.py')
config.model['backbone']['pretrained'] = No... | 866 | 28.896552 | 76 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_common_modules/test_resnet.py | import pytest
import torch
import torch.nn as nn
from mmcv.utils import _BatchNorm
from mmaction.models import ResNet
from ..base import check_norm_state, generate_backbone_demo_inputs
def test_resnet_backbone():
"""Test resnet backbone."""
with pytest.raises(KeyError):
# ResNet depth should be in [1... | 4,319 | 32.75 | 70 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_common_modules/test_mobilenet_v2.py | import pytest
import torch
from mmcv.utils import _BatchNorm
from mmaction.models import MobileNetV2
from ..base import check_norm_state, generate_backbone_demo_inputs
def test_mobilenetv2_backbone():
"""Test MobileNetV2.
Modified from mmclassification.
"""
from torch.nn.modules import GroupNorm
... | 7,014 | 33.219512 | 77 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_common_modules/test_resnet3d.py | import pytest
import torch
import torch.nn as nn
from mmcv.utils import _BatchNorm
from mmaction.models import ResNet3d, ResNet3dLayer
from ..base import check_norm_state, generate_backbone_demo_inputs
def test_resnet3d_backbone():
"""Test resnet3d backbone."""
with pytest.raises(AssertionError):
# I... | 13,070 | 38.01791 | 79 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_common_modules/test_base_head.py | import torch
import torch.nn.functional as F
from mmcv.utils import assert_dict_has_keys
from mmaction.models import BaseHead
class ExampleHead(BaseHead):
# use an ExampleHead to test BaseHead
def init_weights(self):
pass
def forward(self, x):
pass
def test_base_head():
head = Exam... | 2,538 | 33.780822 | 79 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_common_modules/test_base_recognizers.py | import pytest
import torch
import torch.nn.functional as F
from mmaction.models import BaseRecognizer
class ExampleRecognizer(BaseRecognizer):
def __init__(self, train_cfg, test_cfg):
super(BaseRecognizer, self).__init__()
# reconstruct `__init__()` method in BaseRecognizer to avoid building
... | 2,178 | 32.015152 | 77 | py |
STTS | STTS-main/VideoSwin/tests/test_models/test_detectors/test_detectors.py | import pytest
import torch
from ..base import generate_detector_demo_inputs, get_detector_cfg
try:
from mmaction.models import build_detector
mmdet_imported = True
except (ImportError, ModuleNotFoundError):
mmdet_imported = False
@pytest.mark.skipif(not mmdet_imported, reason='requires mmdet')
def test_... | 1,425 | 32.952381 | 69 | py |
STTS | STTS-main/VideoSwin/tests/test_data/test_formating.py | import numpy as np
import pytest
import torch
from mmcv.parallel import DataContainer as DC
from mmcv.utils import assert_dict_has_keys
from mmaction.datasets.pipelines import (Collect, FormatAudioShape,
FormatShape, ImageToTensor, Rename,
... | 6,791 | 33.830769 | 78 | py |
STTS | STTS-main/VideoSwin/tests/test_data/test_sampler.py | from torch.utils.data import DataLoader, Dataset
from mmaction.datasets.samplers import (ClassSpecificDistributedSampler,
DistributedSampler)
class MyDataset(Dataset):
def __init__(self, class_prob={i: 1 for i in range(10)}):
super().__init__()
self.class_... | 3,148 | 31.802083 | 72 | py |
STTS | STTS-main/VideoSwin/tests/test_data/test_blending.py | import torch
from mmaction.datasets import CutmixBlending, MixupBlending
def test_mixup():
alpha = 0.2
num_classes = 10
label = torch.randint(0, num_classes, (4, ))
mixup = MixupBlending(num_classes, alpha)
# NCHW imgs
imgs = torch.randn(4, 4, 3, 32, 32)
mixed_imgs, mixed_label = mixup(i... | 1,306 | 30.119048 | 63 | py |
STTS | STTS-main/VideoSwin/tests/test_data/test_pipelines/test_loadings/test_load.py | import copy
import numpy as np
import pytest
import torch
from mmcv.utils import assert_dict_has_keys
from numpy.testing import assert_array_almost_equal
from mmaction.datasets.pipelines import (LoadAudioFeature, LoadHVULabel,
LoadLocalizationFeature,
... | 6,171 | 39.605263 | 79 | py |
STTS | STTS-main/VideoSwin/tests/test_utils/test_module_hooks.py | import copy
import os.path as osp
import mmcv
import numpy as np
import pytest
import torch
from mmaction.models import build_recognizer
from mmaction.utils import register_module_hooks
from mmaction.utils.module_hooks import GPUNormalize
def test_register_module_hooks():
_module_hooks = [
dict(
... | 4,387 | 35.264463 | 77 | py |
STTS | STTS-main/VideoSwin/tests/test_utils/test_onnx.py | import os.path as osp
import tempfile
import torch.nn as nn
from tools.deployment.pytorch2onnx import _convert_batchnorm, pytorch2onnx
class TestModel(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv3d(1, 2, 1)
self.bn = nn.SyncBatchNorm(2)
def forward(self, x)... | 845 | 25.4375 | 79 | py |
STTS | STTS-main/VideoSwin/tests/test_utils/test_bbox.py | import os.path as osp
from abc import abstractproperty
import numpy as np
import torch
from mmaction.core.bbox import bbox2result, bbox_target
from mmaction.datasets import AVADataset
from mmaction.utils import import_module_error_func
try:
from mmdet.core.bbox import build_assigner, build_sampler
except (Import... | 5,511 | 38.371429 | 79 | py |
STTS | STTS-main/VideoSwin/tests/test_metrics/test_losses.py | import numpy as np
import pytest
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv import ConfigDict
from numpy.testing import assert_almost_equal, assert_array_almost_equal
from torch.autograd import Variable
from mmaction.models import (BCELossWithLogits, BinaryLogisticRegressionLoss,
... | 13,164 | 38.653614 | 98 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/tsm_r50.py | # model settings
model = dict(
type='Recognizer2D',
backbone=dict(
type='ResNetTSM',
pretrained='torchvision://resnet50',
depth=50,
norm_eval=False,
shift_div=8),
cls_head=dict(
type='TSMHead',
num_classes=400,
in_channels=2048,
spatial... | 563 | 24.636364 | 51 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/tsn_r50.py | # model settings
model = dict(
type='Recognizer2D',
backbone=dict(
type='ResNet',
pretrained='torchvision://resnet50',
depth=50,
norm_eval=False),
cls_head=dict(
type='TSNHead',
num_classes=400,
in_channels=2048,
spatial_type='avg',
con... | 513 | 24.7 | 51 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/trn_r50.py | # model settings
model = dict(
type='Recognizer2D',
backbone=dict(
type='ResNet',
pretrained='torchvision://resnet50',
depth=50,
norm_eval=False,
partial_bn=True),
cls_head=dict(
type='TRNHead',
num_classes=400,
in_channels=2048,
num_se... | 576 | 24.086957 | 44 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/c3d_sports1m_pretrained.py | # model settings
model = dict(
type='Recognizer3D',
backbone=dict(
type='C3D',
pretrained= # noqa: E251
'https://download.openmmlab.com/mmaction/recognition/c3d/c3d_sports1m_pretrain_20201016-dcc47ddc.pth', # noqa: E501
style='pytorch',
conv_cfg=dict(type='Conv3d'),
... | 703 | 28.333333 | 124 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/tpn_slowonly_r50.py | # model settings
model = dict(
type='Recognizer3D',
backbone=dict(
type='ResNet3dSlowOnly',
depth=50,
pretrained='torchvision://resnet50',
lateral=False,
out_indices=(2, 3),
conv1_kernel=(1, 7, 7),
conv1_stride_t=1,
pool1_stride_t=1,
inflat... | 1,310 | 30.97561 | 63 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/i3d_r50.py | # model settings
model = dict(
type='Recognizer3D',
backbone=dict(
type='ResNet3d',
pretrained2d=True,
pretrained='torchvision://resnet50',
depth=50,
conv1_kernel=(5, 7, 7),
conv1_stride_t=2,
pool1_stride_t=2,
conv_cfg=dict(type='Conv3d'),
... | 870 | 30.107143 | 146 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/tin_r50.py | # model settings
model = dict(
type='Recognizer2D',
backbone=dict(
type='ResNetTIN',
pretrained='torchvision://resnet50',
depth=50,
norm_eval=False,
shift_div=4),
cls_head=dict(
type='TSMHead',
num_classes=400,
in_channels=2048,
spatial... | 562 | 24.590909 | 51 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/tanet_r50.py | # model settings
model = dict(
type='Recognizer2D',
backbone=dict(
type='TANet',
pretrained='torchvision://resnet50',
depth=50,
num_segments=8,
tam_cfg=dict()),
cls_head=dict(
type='TSMHead',
num_classes=400,
in_channels=2048,
spatial_t... | 538 | 24.666667 | 51 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/tpn_tsm_r50.py | # model settings
model = dict(
type='Recognizer2D',
backbone=dict(
type='ResNetTSM',
pretrained='torchvision://resnet50',
depth=50,
out_indices=(2, 3),
norm_eval=False,
shift_div=8),
neck=dict(
type='TPN',
in_channels=(1024, 2048),
out_... | 1,202 | 31.513514 | 63 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/slowonly_r50.py | # model settings
model = dict(
type='Recognizer3D',
backbone=dict(
type='ResNet3dSlowOnly',
depth=50,
pretrained='torchvision://resnet50',
lateral=False,
conv1_kernel=(1, 7, 7),
conv1_stride_t=1,
pool1_stride_t=1,
inflate=(0, 0, 1, 1),
norm... | 587 | 24.565217 | 44 | py |
PathomicFusion | PathomicFusion-master/data_loaders.py | ### data_loaders.py
import os
import numpy as np
import pandas as pd
from PIL import Image
from sklearn import preprocessing
import torch
import torch.nn as nn
from torch.utils.data.dataset import Dataset # For custom datasets
from torchvision import datasets, transforms
################
# Dataset Loader
#########... | 6,141 | 46.984375 | 111 | py |
PathomicFusion | PathomicFusion-master/fusion.py | import torch
import torch.nn as nn
from utils import init_max_weights
class BilinearFusion(nn.Module):
def __init__(self, skip=1, use_bilinear=1, gate1=1, gate2=1, dim1=32, dim2=32, scale_dim1=1, scale_dim2=1, mmhid=64, dropout_rate=0.25):
super(BilinearFusion, self).__init__()
self.skip = skip
... | 9,580 | 48.901042 | 172 | py |
PathomicFusion | PathomicFusion-master/utils.py | # Base / Native
import math
import os
import pickle
import re
import warnings
warnings.filterwarnings('ignore')
# Numerical / Array
import lifelines
from lifelines.utils import concordance_index
from lifelines import CoxPHFitter
from lifelines.datasets import load_regression_dataset
from lifelines.utils import k_fold_... | 41,241 | 45.235426 | 205 | py |
PathomicFusion | PathomicFusion-master/networks.py | # Base / Native
import csv
from collections import Counter
import copy
import json
import functools
import gc
import logging
import math
import os
import pdb
import pickle
import random
import sys
import tables
import time
from tqdm import tqdm
# Numerical / Array
import numpy as np
# Torch
import torch
import torch.... | 32,354 | 42.313253 | 362 | py |
PathomicFusion | PathomicFusion-master/make_splits.py | ### data_loaders.py
import argparse
import os
import pickle
import numpy as np
import pandas as pd
from PIL import Image
from sklearn import preprocessing
# Env
from networks import define_net
from utils import getCleanAllDataset
import torch
from torchvision import transforms
from options import parse_gpuids
### In... | 12,069 | 59.049751 | 221 | py |
PathomicFusion | PathomicFusion-master/train_cv.py | import os
import logging
import numpy as np
import random
import pickle
import torch
# Env
from data_loaders import *
from options import parse_args
from train_test import train, test
### 1. Initializes parser and device
opt = parse_args()
device = torch.device('cuda:{}'.format(opt.gpu_ids[0])) if opt.gpu_ids else ... | 4,216 | 46.920455 | 164 | py |
PathomicFusion | PathomicFusion-master/options.py | import argparse
import os
import torch
### Parser
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--dataroot', default='./data/TCGA_GBMLGG', help="datasets")
parser.add_argument('--checkpoints_dir', type=str, default='./checkpoints/TCGA_GBMLGG', help='models are saved here')
... | 6,901 | 49.014493 | 205 | py |
PathomicFusion | PathomicFusion-master/test_cv.py | import os
import logging
import numpy as np
import random
import pickle
import torch
# Env
from networks import define_net
from data_loaders import *
from options import parse_args
from train_test import train, test
### 1. Initializes parser and device
opt = parse_args()
device = torch.device('cuda:{}'.format(opt.g... | 3,233 | 43.30137 | 164 | py |
PathomicFusion | PathomicFusion-master/train_test.py | import random
from tqdm import tqdm
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
from torch.utils.data import RandomSampler
from data_loaders import PathgraphomicDatasetLoader, PathgraphomicFastDatasetLoader
from networks import define_net, define_reg, define_opt... | 9,077 | 54.018182 | 193 | py |
PathomicFusion | PathomicFusion-master/core/utils_models.py | # Base / Native
import math
import os
import pickle
import re
import warnings
warnings.filterwarnings('ignore')
# Numerical / Array
import lifelines
from lifelines.utils import concordance_index
from lifelines import CoxPHFitter
from lifelines.datasets import load_regression_dataset
from lifelines.utils import k_fold_... | 13,960 | 34.524173 | 156 | py |
PathomicFusion | PathomicFusion-master/CellGraph/pixelcnn.py | import torch.nn as nn
from layers_custom import maskConv0, MaskConvBlock
import torch
class MaskCNN(nn.Module):
def __init__(self, n_channel=1024, h=128):
"""PixelCNN Model"""
super(MaskCNN, self).__init__()
self.MaskConv0 = maskConv0(n_channel, h, k_size=7, stride=1, pad=3)
# larg... | 1,544 | 27.090909 | 149 | py |
PathomicFusion | PathomicFusion-master/CellGraph/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, most of the implementations on the web is copy-paste from
torchvision's resnet and has w... | 4,971 | 29.881988 | 120 | py |
PathomicFusion | PathomicFusion-master/CellGraph/model.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from resnet_custom import *
import pdb
import math
from pixelcnn import MaskCNN
device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
def initialize_weights(module):
"""
args:
... | 6,484 | 32.427835 | 142 | py |
PathomicFusion | PathomicFusion-master/CellGraph/layers_custom.py | import torch
import torch.nn as nn
import pdb
def down_shift(x, pad=None):
# Pytorch ordering
xs = [int(y) for y in x.size()]
# when downshifting, the last row is removed
x = x[:, :, :xs[2] - 1, :]
# padding left, padding right, padding top, padding bottom
pad = nn.ZeroPad2d((0, 0, 1, 0)) if p... | 3,879 | 28.172932 | 80 | py |
PathomicFusion | PathomicFusion-master/CellGraph/resnet_custom.py | # modified from Pytorch official resnet.py
# oops
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch
from torchsummary import summary
import torch.nn.functional as F
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': ... | 10,078 | 30.794953 | 90 | py |
cc | cc-master/models.py | import tensorflow as tf
class CNN:
def __init__(self, x1_maxlen, x2_maxlen, y_len, embedding, filter_sizes, num_filters, hidden_size, state_size, x3_size):
self.input_x1 = tf.placeholder(tf.int32, [None, x1_maxlen], name="post_text")
self.input_x1_len = tf.placeholder(tf.int32, [None, ], name="pos... | 20,233 | 80.58871 | 272 | py |
cl4ctr | cl4ctr-main/main_ml_base.py | import torch.nn as nn
import torch.nn.functional as F
from torch.optim.lr_scheduler import ReduceLROnPlateau
from model.FM import FactorizationMachineModel, FM_CL4CTR
from model.DeepFM import DeepFM, DeepFM_CL4CTR
import numpy as np
import random
import sys
import tqdm
import time
import argparse
import torch
import... | 9,982 | 37.693798 | 145 | py |
cl4ctr | cl4ctr-main/utils/earlystoping.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import numpy as np
import torch
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, patience=7, verbose=False, delta=0, prefix = None):
"""
Args:
patience (int... | 3,748 | 38.052083 | 111 | py |
cl4ctr | cl4ctr-main/model/data_aug.py | import torch
def maskrandom(x_emb, mask_ratio):
B, F, E = x_emb.size()
mask1 = torch.bernoulli(torch.ones(B, F, E) * mask_ratio).cuda()
mask2 = torch.bernoulli(torch.ones(B, F, E) * mask_ratio).cuda()
x_emb1 = x_emb * mask1
x_emb2 = x_emb * mask2
return x_emb1, x_emb2
def maskdimension(x_emb... | 863 | 28.793103 | 68 | py |
cl4ctr | cl4ctr-main/model/BasiclLayer.py | import torch.nn as nn
import numpy as np
from .data_aug import *
class BasicCTR(nn.Module):
def __init__(self, field_dims, embed_dim):
super(BasicCTR, self).__init__()
self.embedding = FeaturesEmbedding(field_dims, embed_dim)
def forward(self, x):
raise NotImplemented
class BasicCL4... | 9,456 | 35.513514 | 118 | py |
cl4ctr | cl4ctr-main/dataloader/frappe/dataloader.py | import numpy as np
import pandas as pd
import torch
import os
import tqdm
import pickle
class LoadData():
def __init__(self, path="./data/", dataset="frappe"):
self.dataset = dataset
self.path = path + dataset + "/"
self.trainfile = self.path + dataset + ".train.libfm"
self.testfile... | 4,921 | 44.155963 | 113 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/modules/losses.py | # coding=utf-8
"""Loss functions for entity alignment and link prediction."""
import enum
import logging
from typing import Any, Callable, Mapping, Optional
import torch
from torch import nn
from torch.nn import functional
from .similarity import Similarity
from ..data import MatchSideEnum, SIDES
from ..utils.common ... | 11,575 | 33.97281 | 149 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/modules/sampler.py | """Sampling methods for negative samples."""
from abc import abstractmethod
from typing import Optional, Tuple
import torch
from kgm.utils.types import NodeIDs
class NegativeSampler:
"""Abstract class encapsulating a logic of choosing negative examples."""
@abstractmethod
def sample(
self,
... | 1,654 | 31.45098 | 117 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/modules/graph.py | # coding=utf-8
"""
Module for message passing modules.
The message passing is split into three phases:
1) Message Creation
Calculate messages. Potentially takes the source and target node representations, as well as the relation-type of
the considered edge into account, i.e. for a triple (e_i, r, e_j): m_{i->j} ... | 11,533 | 30.172973 | 169 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/modules/similarity.py | # coding=utf-8
"""Modules for computing similarities between vectors."""
import enum
from abc import abstractmethod
from typing import Optional, Union
import torch
from torch import nn
from torch.nn import functional
from ..utils.common import get_subclass_by_name, value_to_enum
# pylint: disable=abstract-method
cl... | 9,200 | 27.933962 | 148 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/modules/embeddings/base.py | """Basic node embedding modules."""
import enum
import math
import pathlib
from typing import Any, Mapping, Optional, Type, Union
import torch
from torch import nn
from .init.base import ConstantNodeEmbeddingInitializer, NodeEmbeddingInitializer, RandomNodeEmbeddingInitializer
from .norm import EmbeddingNormalization... | 10,589 | 32.619048 | 149 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/modules/embeddings/norm.py | # coding=utf-8
"""Embedding normalization."""
import enum
from abc import abstractmethod
from typing import Union
import torch
from torch.nn import functional
from ...utils.common import get_subclass_by_name
class EmbeddingNormalizer:
"""Embedding normalization."""
@abstractmethod
def normalize(
... | 2,340 | 22.887755 | 98 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/modules/embeddings/init/base.py | # coding=utf-8
"""Node embedding initialization."""
import pathlib
from typing import Any, Optional, Sequence, Union
import torch
from torch import nn
from ....data import KnowledgeGraph, MatchSideEnum
class NodeEmbeddingInitializer:
"""Initialization methods."""
def init_one_(
self,
embed... | 4,886 | 28.439759 | 116 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/training/base.py | """Common training loop parts."""
import logging
from typing import Any, Generic, Iterable, Mapping, Optional, Tuple, Type, TypeVar
import torch
from torch import nn
from torch.optim import Optimizer
from kgm.utils.common import NonFiniteLossError, kwargs_or_empty, last
from kgm.utils.torch_utils import construct_opt... | 6,203 | 30.175879 | 114 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/training/matching.py | # coding=utf-8
"""Training loops for KG matching models."""
import logging
from abc import abstractmethod
from typing import Any, Iterable, List, Mapping, Optional, Tuple, Type
import torch
from torch.optim import Optimizer
from torch.utils import data
from .base import BaseTrainer
from ..data import KnowledgeGraphAl... | 8,475 | 30.509294 | 114 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/eval/matching.py | # coding=utf-8
"""Entity Alignment evaluation methods."""
from typing import Collection, Dict, Mapping, Optional, Tuple, TypeVar, Union
import torch
from .common import aggregate_ranks, get_rank
from ..data import MatchSideEnum, SIDES
from ..models import KGMatchingModel
from ..modules import Similarity
from ..utils.... | 6,525 | 31.63 | 110 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/eval/common.py | """Common utility methods for evaluation."""
import logging
from typing import Collection, Mapping, Optional
import torch
logger = logging.getLogger(name=__name__)
# Small constant for floating point comparison
EPSILON = 1.0e-08
def get_rank(sim: torch.FloatTensor, true: torch.LongTensor) -> torch.FloatTensor:
... | 4,478 | 36.957627 | 118 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/models/matching/base.py | # coding=utf-8
"""API for models for knowledge graph matching."""
import logging
from abc import ABC, abstractmethod
from collections import defaultdict
from typing import Any, Callable, Mapping, Optional, Type
import torch
from frozendict import frozendict
from torch import nn
from ...data import KnowledgeGraphAlign... | 9,382 | 32.996377 | 130 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/models/matching/gcn_align.py | # coding=utf-8
"""
Implementation of GCN-Align.
The paper introducing the model can be found at https://www.aclweb.org/anthology/D18-1032.pdf.
The authors' implementation can be found at https://github.com/1049451037/GCN-Align and they also refer to
https://github.com/1049451037/HIN-Align for an improved implementati... | 6,089 | 37.789809 | 137 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/utils/types.py | """Type annotation aliases."""
import torch
#: A (n, 3) tensor of IDs.
Triples = torch.LongTensor
#: A (n,) tensor of IDs.
EntityIDs = torch.LongTensor
#: A (n,) tensor of IDs.
RelationIDs = torch.LongTensor
#: A (n,) tensor of IDs.
NodeIDs = torch.LongTensor
#: A (2, n) tensor of IDs.
IDAlignment = torch.LongTens... | 381 | 17.190476 | 30 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/utils/torch_utils.py | """Utility methods using pytorch."""
import itertools
import logging
from abc import ABC
from collections import defaultdict
from operator import itemgetter
from typing import Any, Callable, MutableMapping, Optional, Sequence, Tuple, Type, TypeVar, Union
import numpy
import torch
from torch import nn, optim
from .com... | 21,537 | 32.86478 | 172 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/data/reduction.py | """Reduction strategies from Knowledge Graph to (weighted) uni-relational graphs."""
import enum
import logging
from typing import Callable, Optional
import torch
from .knowledge_graph import KnowledgeGraph
from ..utils.torch_utils import ExtendedModule, SparseCOOMatrix
logger = logging.getLogger(name=__name__)
# ... | 7,812 | 32.246809 | 155 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/data/loaders.py | """Data loading for Entity Alignment datasets."""
import abc
import io
import json
import logging
import lzma
import pathlib
import tarfile
import zipfile
from typing import Collection, Generic, Mapping, Optional, Tuple, Type, TypeVar, Union
import pandas
import requests
import torch
from .knowledge_graph import Enti... | 38,530 | 35.942474 | 184 | py |
rank-based-evaluation | rank-based-evaluation-main/src/kgm/data/knowledge_graph.py | # coding=utf-8
"""Various knowledge graph related data structures."""
import enum
import json
import logging
import lzma
import pathlib
from dataclasses import dataclass
from typing import Mapping, Optional, Tuple, Union
import torch
from ..utils.torch_utils import split_tensor
from ..utils.types import EntityIDs, ID... | 25,646 | 33.287433 | 215 | py |
rank-based-evaluation | rank-based-evaluation-main/executables/adjusted_ranking_experiments.py | # coding=utf-8
"""Evaluation of different training and test sizes."""
import argparse
import logging
import random
import mlflow
import numpy
import torch
import tqdm
from kgm.data import get_dataset_by_name
from kgm.eval.matching import evaluate_matching_model
from kgm.models import GCNAlign
from kgm.modules import ... | 4,618 | 30.855172 | 87 | py |
rank-based-evaluation | rank-based-evaluation-main/executables/degree_investigation.py | """Script to generate the evaluation for degree inductive bias."""
import numpy
import torch
from matplotlib import pyplot as plt
from scipy.stats import pearsonr, spearmanr
from kgm.data import SIDES, get_dataset_by_name
from kgm.models import GCNAlign, PureEmbeddingModel
def degree_vs_norm(
dataset
):
# ca... | 2,854 | 27.55 | 96 | py |
CIF-HieraDist | CIF-HieraDist-main/setup.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import subprocess
import sys
from setuptools import setup, find_packages, Extension
from setuptools import E... | 8,435 | 28.291667 | 92 | py |
CIF-HieraDist | CIF-HieraDist-main/hubconf.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""isort:skip_file"""
import functools
import importlib
dependencies = [
"dataclasses",
"hydra",
"numpy",
"omegaconf",
"... | 2,099 | 27.378378 | 82 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_to_text/prep_covost_data.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import logging
from pathlib import Path
import shutil
from tempfile import NamedTemporaryFile
from typi... | 8,898 | 30.782143 | 86 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_to_text/prep_mtedx_data.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import logging
import os
from pathlib import Path
import shutil
from itertools import groupby
from temp... | 10,404 | 34.03367 | 87 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_to_text/prep_aishell2_data.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import argparse
import logging
from pathlib import Path
import shutil
from tempfile import NamedTemporaryFile... | 9,428 | 31.513793 | 95 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_to_text/prep_librispeech_data.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import logging
from pathlib import Path
import shutil
from tempfile import NamedTemporaryFile
import p... | 3,811 | 29.253968 | 87 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_to_text/data_utils.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import csv
from pathlib import Path
import zipfile
from functools import reduce
from multiprocessing import cpu_count
from typing import Any, ... | 12,224 | 30.670984 | 88 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_to_text/prep_mustc_data.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import logging
import os
from pathlib import Path
import shutil
from itertools import groupby
from temp... | 11,015 | 36.726027 | 87 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_to_text/prep_aishell1_data.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import argparse
import logging
from pathlib import Path
import shutil
from tempfile import NamedTemporaryFile... | 11,501 | 31.038997 | 98 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_to_text/gen_librispeech_vocab.py | # @Time : 2022/3/2
# @Author : Minglun Han
# @File : gen_vocab.py
import argparse
import logging
from pathlib import Path
import shutil
from tempfile import NamedTemporaryFile
import pandas as pd
from examples.speech_to_text.data_utils import (
create_zip,
extract_fbank_features,
gen_config_yaml,
... | 1,514 | 24.25 | 88 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_to_text/gen_vocab.py | # @Time : 2022/3/2
# @Author : Minglun Han
# @File : gen_vocab.py
import argparse
import logging
from pathlib import Path
import shutil
from tempfile import NamedTemporaryFile
import pandas as pd
from examples.speech_to_text.data_utils import (
create_zip,
extract_fbank_features,
gen_config_yaml,
... | 1,515 | 24.266667 | 63 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_to_text/bert_feat_extract/extract_bert_feats.py | # @Time : 2022/8/15
# @Author : Minglun Han
# @File : extract_bert_feats.py
import os
import sys
import argparse
import random
import string
import json
import numpy as np
import torch
from transformers import BertTokenizer, BertModel
"""
Description:
This program is used to extract the features from pret... | 6,843 | 32.54902 | 129 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_to_text/simultaneous_translation/agents/fairseq_simul_st_agent.py | import math
import os
import json
import numpy as np
import torch
import torchaudio.compliance.kaldi as kaldi
import yaml
from fairseq import checkpoint_utils, tasks
from fairseq.file_io import PathManager
try:
from simuleval import READ_ACTION, WRITE_ACTION, DEFAULT_EOS
from simuleval.agents import SpeechAgen... | 12,271 | 32.347826 | 105 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_recognition/ctc_decoder.py | # @Time : 2021/7/26
# @Author : Minglun Han
# @File : ctc_decoder.py
import os
import sys
import torch
import random
import logging
import torch.nn.functional as F
import numpy as np
import itertools as it
# Control print options
torch.set_printoptions(profile="full")
torch.set_printoptions(profile="default")
... | 5,750 | 35.169811 | 88 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_recognition/infer.py | #!/usr/bin/env python3 -u
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Run inference for pre-processed data with a trained model.
"""
import ast
import logging
import math
import os
... | 18,560 | 32.203936 | 115 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_recognition/w2l_decoder.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Flashlight decoders.
"""
import gc
import itertools as it
import os.path as osp
from typing import List
import wa... | 17,561 | 34.336016 | 171 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_recognition/cif_decoder.py | # @Time : 2021/7/14
# @Author : Minglun Han
# @File : cif_decoder.py
"""""
Update:
By 2022/06/19
1. support LM decoding with language model by shallow fusion;
""" ""
import os
import sys
import torch
import logging
import numpy as np
import itertools as it
from torch import Tensor
import torch.... | 40,532 | 43.057609 | 116 | py |
CIF-HieraDist | CIF-HieraDist-main/examples/speech_recognition/criterions/cross_entropy_acc.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import math
import torch
import torch.nn.f... | 5,372 | 40.015267 | 85 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.