repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
STTS | STTS-main/VideoSwin/tests/test_data/test_pipelines/test_loadings/__init__.py | from .base import BaseTestLoading
__all__ = ['BaseTestLoading']
| 65 | 15.5 | 33 | 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_localization_utils.py | import os.path as osp
import numpy as np
import pytest
from numpy.testing import assert_array_almost_equal, assert_array_equal
from mmaction.localization import (generate_bsp_feature,
generate_candidate_proposals, soft_nms,
temporal_iop, temporal_i... | 7,536 | 35.946078 | 79 | py |
STTS | STTS-main/VideoSwin/tests/test_utils/__init__.py | 0 | 0 | 0 | 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_utils/test_decorator.py | import pytest
from mmaction.utils import import_module_error_class, import_module_error_func
def test_import_module_error_class():
@import_module_error_class('mmdet')
class ExampleClass:
pass
with pytest.raises(ImportError):
ExampleClass()
@import_module_error_class('mmdet')
cl... | 654 | 18.848485 | 78 | py |
STTS | STTS-main/VideoSwin/tests/test_metrics/test_accuracy.py | import os.path as osp
import random
import numpy as np
import pytest
from numpy.testing import assert_array_almost_equal, assert_array_equal
from mmaction.core import (ActivityNetLocalization,
average_recall_at_avg_proposals, confusion_matrix,
get_weighted_score, ... | 11,392 | 35.751613 | 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/Kinetics/t0_0.625.py | _base_ = [
'../_base_/models/swin/swin_base.py', '../_base_/default_runtime.py'
]
model=dict(backbone=dict(patch_size=(2,4,4), drop_path_rate=0.2, time_pruning_loc=[0], time_left_ratio=[0.625], time_score='tpool', pretrained2d=False), test_cfg=dict(max_testing_views=2))
# dataset settings
dataset_type = 'VideoData... | 3,950 | 30.862903 | 188 | py |
STTS | STTS-main/VideoSwin/configs/Kinetics/t0_0.5625.py | _base_ = [
'../_base_/models/swin/swin_base.py', '../_base_/default_runtime.py'
]
model=dict(backbone=dict(patch_size=(2,4,4), drop_path_rate=0.2, time_pruning_loc=[0], time_left_ratio=[0.5625], time_score='tpool', pretrained2d=False), test_cfg=dict(max_testing_views=2))
# dataset settings
dataset_type = 'VideoDat... | 3,951 | 30.870968 | 189 | py |
STTS | STTS-main/VideoSwin/configs/Kinetics/t0_0.875.py | _base_ = [
'../_base_/models/swin/swin_base.py', '../_base_/default_runtime.py'
]
model=dict(backbone=dict(patch_size=(2,4,4), drop_path_rate=0.2, time_pruning_loc=[0], time_left_ratio=[0.875], time_score='tpool', pretrained2d=False), test_cfg=dict(max_testing_views=2))
# dataset settings
dataset_type = 'VideoData... | 3,950 | 30.862903 | 188 | py |
STTS | STTS-main/VideoSwin/configs/Kinetics/t0_0.75.py | _base_ = [
'../_base_/models/swin/swin_base.py', '../_base_/default_runtime.py'
]
model=dict(backbone=dict(patch_size=(2,4,4), drop_path_rate=0.2, time_pruning_loc=[0], time_left_ratio=[0.75], time_score='tpool', pretrained2d=False), test_cfg=dict(max_testing_views=2))
# dataset settings
dataset_type = 'VideoDatas... | 3,949 | 30.854839 | 187 | py |
STTS | STTS-main/VideoSwin/configs/Kinetics/t0_0.375.py | _base_ = [
'../_base_/models/swin/swin_base.py', '../_base_/default_runtime.py'
]
model=dict(backbone=dict(patch_size=(2,4,4), drop_path_rate=0.2, time_pruning_loc=[0], time_left_ratio=[0.375], time_score='tpool', pretrained2d=False), test_cfg=dict(max_testing_views=2))
# dataset settings
dataset_type = 'VideoData... | 3,950 | 30.862903 | 188 | py |
STTS | STTS-main/VideoSwin/configs/_base_/default_runtime.py | checkpoint_config = dict(interval=1)
log_config = dict(
interval=20,
hooks=[
dict(type='TextLoggerHook'),
# dict(type='TensorboardLoggerHook'),
])
# runtime settings
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
| 310 | 21.214286 | 45 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/slowfast_r50.py | # model settings
model = dict(
type='Recognizer3D',
backbone=dict(
type='ResNet3dSlowFast',
pretrained=None,
resample_rate=8, # tau
speed_ratio=8, # alpha
channel_ratio=8, # beta_inv
slow_pathway=dict(
type='resnet3d',
depth=50,
... | 1,123 | 27.1 | 41 | 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/r2plus1d_r34.py | # model settings
model = dict(
type='Recognizer3D',
backbone=dict(
type='ResNet2Plus1d',
depth=34,
pretrained=None,
pretrained2d=False,
norm_eval=False,
conv_cfg=dict(type='Conv2plus1d'),
norm_cfg=dict(type='SyncBN', requires_grad=True, eps=1e-3),
... | 813 | 27.068966 | 67 | 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/audioonly_r50.py | # model settings
model = dict(
type='AudioRecognizer',
backbone=dict(
type='ResNetAudio',
depth=50,
pretrained=None,
in_channels=1,
norm_eval=False),
cls_head=dict(
type='AudioTSNHead',
num_classes=400,
in_channels=1024,
dropout_ratio=0... | 451 | 22.789474 | 41 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/tsn_r50_audio.py | # model settings
model = dict(
type='AudioRecognizer',
backbone=dict(type='ResNet', depth=50, in_channels=1, norm_eval=False),
cls_head=dict(
type='AudioTSNHead',
num_classes=400,
in_channels=2048,
dropout_ratio=0.5,
init_std=0.01),
# model training and testing se... | 388 | 26.785714 | 75 | 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/bmn_400x100.py | # model settings
model = dict(
type='BMN',
temporal_dim=100,
boundary_ratio=0.5,
num_samples=32,
num_samples_per_bin=3,
feat_dim=400,
soft_nms_alpha=0.4,
soft_nms_low_threshold=0.5,
soft_nms_high_threshold=0.9,
post_process_top_k=100)
| 275 | 20.230769 | 32 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/tsm_mobilenet_v2.py | # model settings
model = dict(
type='Recognizer2D',
backbone=dict(
type='MobileNetV2TSM',
shift_div=8,
num_segments=8,
is_shift=True,
pretrained='mmcls://mobilenet_v2'),
cls_head=dict(
type='TSMHead',
num_segments=8,
num_classes=400,
in... | 594 | 24.869565 | 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/csn_ig65m_pretrained.py | # model settings
model = dict(
type='Recognizer3D',
backbone=dict(
type='ResNet3dCSN',
pretrained2d=False,
pretrained= # noqa: E251
'https://download.openmmlab.com/mmaction/recognition/csn/ircsn_from_scratch_r152_ig65m_20200807-771c4135.pth', # noqa: E501
depth=152,
... | 709 | 28.583333 | 132 | 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/bsn_tem.py | # model settings
model = dict(
type='TEM',
temporal_dim=100,
boundary_ratio=0.1,
tem_feat_dim=400,
tem_hidden_dim=512,
tem_match_threshold=0.5)
| 168 | 17.777778 | 28 | 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 |
STTS | STTS-main/VideoSwin/configs/_base_/models/x3d.py | # model settings
model = dict(
type='Recognizer3D',
backbone=dict(type='X3D', gamma_w=1, gamma_b=2.25, gamma_d=2.2),
cls_head=dict(
type='X3DHead',
in_channels=432,
num_classes=400,
spatial_type='avg',
dropout_ratio=0.5,
fc1_bias=False),
# model training a... | 401 | 25.8 | 68 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/bsn_pem.py | # model settings
model = dict(
type='PEM',
pem_feat_dim=32,
pem_hidden_dim=256,
pem_u_ratio_m=1,
pem_u_ratio_l=2,
pem_high_temporal_iou_threshold=0.6,
pem_low_temporal_iou_threshold=0.2,
soft_nms_alpha=0.75,
soft_nms_low_threshold=0.65,
soft_nms_high_threshold=0.9,
post_proce... | 334 | 22.928571 | 40 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/vip/vip_tiny.py | # model settings
model = dict(
type='Recognizer3D',
backbone=dict(
type='VideoParser',
inplanes=64,
num_chs=(64, 128, 256, 512),
patch_sizes=[8, 7, 7, 7],
num_heads=[1, 2, 4, 8],
num_enc_heads=[1, 2, 4, 8],
num_parts=[32, 32, 32, 32],
num_laye... | 636 | 23.5 | 41 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/swin/swin_base.py | # model settings
_base_ = "swin_tiny.py"
model = dict(backbone=dict(depths=[2, 2, 18, 2],
embed_dim=128,
num_heads=[4, 8, 16, 32]),
cls_head=dict(in_channels=1024))
| 232 | 32.285714 | 53 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/swin/swin_large.py | # model settings
_base_ = "swin_tiny.py"
model = dict(backbone=dict(depths=[2, 2, 18, 2],
embed_dim=192,
num_heads=[6, 12, 24, 48]),
cls_head=dict(in_channels=1536))
| 233 | 32.428571 | 54 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/swin/swin_tiny.py | # model settings
model = dict(
type='Recognizer3D',
backbone=dict(
type='SwinTransformer3D',
patch_size=(4,4,4),
embed_dim=96,
depths=[2, 2, 6, 2],
num_heads=[3, 6, 12, 24],
window_size=(8,7,7),
mlp_ratio=4.,
qkv_bias=True,
qk_scale=None,
... | 614 | 23.6 | 42 | py |
STTS | STTS-main/VideoSwin/configs/_base_/models/swin/swin_small.py | # model settings
_base_ = "swin_tiny.py"
model = dict(backbone=dict(depths=[2, 2, 18, 2]))
| 91 | 22 | 49 | py |
STTS | STTS-main/VideoSwin/configs/_base_/schedules/sgd_100e.py | # optimizer
optimizer = dict(
type='SGD',
lr=0.01, # this lr is used for 8 gpus
momentum=0.9,
weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2))
# learning policy
lr_config = dict(policy='step', step=[40, 80])
total_epochs = 100
| 282 | 24.727273 | 65 | py |
STTS | STTS-main/VideoSwin/configs/_base_/schedules/sgd_tsm_mobilenet_v2_50e.py | # optimizer
optimizer = dict(
type='SGD',
constructor='TSMOptimizerConstructor',
paramwise_cfg=dict(fc_lr5=True),
lr=0.01, # this lr is used for 8 gpus
momentum=0.9,
weight_decay=0.00002)
optimizer_config = dict(grad_clip=dict(max_norm=20, norm_type=2))
# learning policy
lr_config = dict(policy... | 362 | 26.923077 | 65 | py |
STTS | STTS-main/VideoSwin/configs/_base_/schedules/sgd_50e.py | # optimizer
optimizer = dict(
type='SGD',
lr=0.01, # this lr is used for 8 gpus
momentum=0.9,
weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2))
# learning policy
lr_config = dict(policy='step', step=[20, 40])
total_epochs = 50
| 281 | 24.636364 | 65 | py |
STTS | STTS-main/VideoSwin/configs/_base_/schedules/adam_20e.py | # optimizer
optimizer = dict(
type='Adam', lr=0.01, weight_decay=0.00001) # this lr is used for 1 gpus
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=10)
total_epochs = 20
| 225 | 27.25 | 77 | py |
STTS | STTS-main/VideoSwin/configs/_base_/schedules/sgd_tsm_mobilenet_v2_100e.py | # optimizer
optimizer = dict(
type='SGD',
constructor='TSMOptimizerConstructor',
paramwise_cfg=dict(fc_lr5=True),
lr=0.01, # this lr is used for 8 gpus
momentum=0.9,
weight_decay=0.00002)
optimizer_config = dict(grad_clip=dict(max_norm=20, norm_type=2))
# learning policy
lr_config = dict(policy... | 363 | 27 | 65 | py |
STTS | STTS-main/VideoSwin/configs/_base_/schedules/sgd_150e_warmup.py | # optimizer
optimizer = dict(
type='SGD', lr=0.01, momentum=0.9,
weight_decay=0.0001) # this lr is used for 8 gpus
optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2))
# learning policy
lr_config = dict(
policy='step',
step=[90, 130],
warmup='linear',
warmup_by_epoch=True,
warm... | 352 | 24.214286 | 65 | py |
STTS | STTS-main/VideoSwin/configs/_base_/schedules/sgd_tsm_100e.py | # optimizer
optimizer = dict(
type='SGD',
constructor='TSMOptimizerConstructor',
paramwise_cfg=dict(fc_lr5=True),
lr=0.02, # this lr is used for 8 gpus
momentum=0.9,
weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=20, norm_type=2))
# learning policy
lr_config = dict(policy=... | 362 | 26.923077 | 65 | py |
STTS | STTS-main/VideoSwin/configs/_base_/schedules/sgd_tsm_50e.py | # optimizer
optimizer = dict(
type='SGD',
constructor='TSMOptimizerConstructor',
paramwise_cfg=dict(fc_lr5=True),
lr=0.01, # this lr is used for 8 gpus
momentum=0.9,
weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=20, norm_type=2))
# learning policy
lr_config = dict(policy=... | 361 | 26.846154 | 65 | 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/run_cox_baselines.py | # Base / Native
import os
import pickle
# Numerical / Array
from lifelines.utils import concordance_index
from lifelines import CoxPHFitter
import numpy as np
import pandas as pd
pd.options.display.max_rows = 999
# Env
from utils import CI_pm
from utils import cox_log_rank
from utils import getCleanAllDataset, addHis... | 4,162 | 50.395062 | 129 | 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/core/utils_data.py | import os
import pandas as pd
import numpy as np
################
# Data Utils
################
def addHistomolecularSubtype(data):
"""
Molecular Subtype: IDHwt == 0, IDHmut-non-codel == 1, IDHmut-codel == 2
Histology Subtype: astrocytoma == 0, oligoastrocytoma == 1, oligodendroglioma == 2, glioblastoma =... | 9,075 | 54.006061 | 205 | py |
PathomicFusion | PathomicFusion-master/core/utils_analysis.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_... | 59,192 | 53.55576 | 208 | 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 |
restflow | restflow-master/tests/test.py | import unittest
import sys
from IPython.display import Image, display
import sympy
import os
script_path = os.path.abspath(__file__) # Get the absolute path of the script
script_dir = os.path.dirname(script_path) # Get the directory of the script
os.chdir(script_dir) # Change the current working directory to t... | 13,164 | 39.137195 | 286 | py |
restflow | restflow-master/restflow/symtools.py | import itertools
import sympy
def taylor(function_expression, variable_list, evaluation_point, degree):
"""
Returns a sympy expression of the Taylor series up to a given degree, of
a given multivariate expression, approximated as a multivariate
polynomial evaluated at the evaluation_point
"""
n... | 3,299 | 44.833333 | 186 | py |
restflow | restflow-master/restflow/graph.py | import math
import itertools
import sympy
import matplotlib.pyplot as plt
import feynman
from restflow import symbolic
class Edge:
"""Directed edge with label.
Attributes:
start (Vertex): start vertex
end (Vertex): end vertex
label (Vector or VectorAdd): wave vector to label edge
angle (real): or... | 11,176 | 32.972644 | 475 | py |
restflow | restflow-master/restflow/symvec.py | import copy
"""Implementation of symbolic vectors with sympy."""
class Context:
def __init__(self):
self.dots = {}
def add_dot_product(self, s1, s2, s_dot):
self.dots[frozenset((s1,s2))] = s_dot
def vector(self,sym):
return Vector(self,sym)
class VectorAdd:
"""
Represents ... | 4,135 | 28.542857 | 115 | py |
restflow | restflow-master/restflow/symbolic.py | import sympy
from restflow import symtools
from restflow import symvec
# global symbols
K_d, Lambda, delta_l, dim = sympy.symbols('K_d Lambda δl d')
def _integrate_theta(expr,cs,d):
"""Symbolically replace powers of cos by integrated expression."""
expr = expr.subs(cs**4,3/(d*(d+2)))
expr = expr.subs(cs**... | 6,204 | 36.379518 | 183 | py |
restflow | restflow-master/restflow/__init__.py | from restflow.graph import *
from restflow.symvec import Context
from restflow.symbolic import integrate | 104 | 34 | 39 | py |
cc | cc-master/optimise.py | import tensorflow as tf
from utils import *
from sklearn.model_selection import KFold
from models import *
import time
import datetime
import hyperopt
class FLAGS:
dir = "/data"
training_file = "clickbait17-validation-170630"
validation_file = "clickbait17-train-170331"
epochs = 20
batch_size = 64... | 10,843 | 59.581006 | 366 | py |
cc | cc-master/utils.py | import numpy as np
import json
import os
import re
import nltk
from gensim.models import Word2Vec
from tweet_utils import *
from collections import Counter
from PIL import Image
import scipy.io
import tensorflow as tf
from scipy import ndimage
import hickle
PAD = "<pad>" # reserve 0 for pad
UNK = "<unk>" # reserve 1... | 14,046 | 43.312303 | 188 | py |
cc | cc-master/tweet_utils.py | # -*- coding: utf-8 -*-
"""
Twokenize -- a tokenizer designed for Twitter text in English and some other European languages.
This tokenizer code has gone through a long history:
(1) Brendan O'Connor wrote original version in Python, http://github.com/brendano/tweetmotif
TweetMotif: Exploratory Search and Topic ... | 13,028 | 41.718033 | 185 | 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 |
cc | cc-master/train.py | import tensorflow as tf
from utils import *
from sklearn.model_selection import KFold
from models import *
import time
import datetime
tf.app.flags.DEFINE_string("dir", "/data", "folder directory")
tf.app.flags.DEFINE_string("training_file", "clickbait17-validation-170630", "Training data file")
tf.app.flags.DEFINE_st... | 11,319 | 65.19883 | 366 | py |
cc | cc-master/test_final.py | import tensorflow as tf
from utils import *
from sklearn.model_selection import KFold
# from models import *
import time
import datetime
from sklearn.metrics import mean_squared_error as mse
from sklearn.metrics import accuracy_score as acc
import argparse
tf.app.flags.DEFINE_string("dir", "/data", "folder directory")... | 6,002 | 53.081081 | 275 | 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/utils/__init__.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
@Author:wangfy
@project:PNNConvModel
@Time:2020/6/17 4:49 下午
''' | 115 | 15.571429 | 23 | py |
cl4ctr | cl4ctr-main/utils/utils_de.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
def load_trained_embedding(from_model,to_model):
"""
:param from_model:
:param to_model:
:return: model with trained params
"""
model_dict = to_model.state_dict()
state_dict_trained = {name: param for name, param in from_model.named_parameters() ... | 562 | 27.15 | 116 | py |
cl4ctr | cl4ctr-main/model/DeepFM.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from model.BasiclLayer import BasicCTR, BasicCL4CTR, FactorizationMachine, MultiLayerPerceptron
class DeepFM(BasicCTR):
def __init__(self, field_dims, embed_dim, mlp_layers=(400, 400, 400), dropout=0.5):
super(DeepFM, self).__init__(field_dims, embed_dim)
... | 1,538 | 37.475 | 115 | 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/__init__.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
| 45 | 14.333333 | 22 | 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/model/FM.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from model.BasiclLayer import BasicCTR, BasicCL4CTR, FactorizationMachine, FeaturesLinear
class FactorizationMachineModel(BasicCTR):
def __init__(self, field_dims, embed_dim):
super(FactorizationMachineModel, self).__init__(field_dims, embed_dim)
self.... | 1,190 | 30.342105 | 106 | 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/__init__.py | # coding=utf-8
"""A package for Knowledge Graph Matching and Entity Alignment."""
| 82 | 26.666667 | 66 | 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/__init__.py | # coding=utf-8
"""Components for building and training models."""
from .losses import BaseLoss, MarginLoss, MatchingLoss, SampledMatchingLoss, get_matching_loss, get_pairwise_loss
from .similarity import BoundInverseTransformation, CosineSimilarity, DistanceToSimilarity, DotProductSimilarity, LpSimilarity, NegativeTran... | 747 | 31.521739 | 194 | 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__.py | # coding=utf-8
"""Modules for embeddings."""
from .base import get_embedding_pair
from .init.base import ConstantNodeEmbeddingInitializer, PretrainedNodeEmbeddingInitializer, RandomNodeEmbeddingInitializer
__all__ = [
'ConstantNodeEmbeddingInitializer',
'PretrainedNodeEmbeddingInitializer',
'RandomNodeEmbe... | 367 | 29.666667 | 123 | 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/modules/embeddings/init/__init__.py | # coding=utf-8
"""Node embedding initialization methods."""
from .base import NodeEmbeddingInitializer
__all__ = [
'NodeEmbeddingInitializer',
]
| 150 | 17.875 | 44 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.