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 |
|---|---|---|---|---|---|---|
GradAug | GradAug-main/models/wideresnet_randwidth.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.randwidth_ops import RWConv2d, RWLinear, RWBatchNorm2d
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, dropRate=0.0):
super(BasicBlock, self).__init__()
self.bn1 = RWBatchNorm2... | 3,864 | 43.425287 | 115 | py |
GradAug | GradAug-main/models/resnet_randdepth.py | '''
resnet for cifar in pytorch
Reference:
[1] K. He, X. Zhang, S. Ren, and J. Sun. Deep residual learning for image recognition. In CVPR, 2016.
[2] K. He, X. Zhang, S. Ren, and J. Sun. Identity mappings in deep residual networks. In ECCV, 2016.
'''
import torch
import torch.nn as nn
import math
import numpy as np
... | 4,787 | 29.113208 | 109 | py |
GradAug | GradAug-main/models/pyramidnet_randwidth.py | import torch
import torch.nn as nn
import math
from models.randwidth_ops import RWLinear, RWConv2d, RWBatchNorm2d
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
cla... | 9,184 | 37.919492 | 129 | py |
GradAug | GradAug-main/utils/mytransforms.py | import torch
import numpy as np
from PIL import Image
from torchvision import transforms
import random
imagenet_pca = {
'eigval': np.asarray([0.2175, 0.0188, 0.0045]),
'eigvec': np.asarray([
[-0.5675, 0.7192, 0.4009],
[-0.5808, -0.0045, -0.8140],
[-0.5836, -0.6948, 0.4203],
])
}
... | 2,934 | 33.127907 | 102 | py |
HDN | HDN-master/tools/test.py | #Copyright 2021, XinruiZhan
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import os
import cv2
import torch
import numpy as np
from hdn.core.config import cfg
from hdn.tracker.tracker_builder import... | 10,757 | 42.032 | 176 | py |
HDN | HDN-master/tools/demo.py | #Copyright 2021, XinruiZhan
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import argparse
import cv2
import torch
import numpy as np
from glob import glob
from hdn.core.config import cfg
from hdn.models.m... | 11,417 | 41.764045 | 149 | py |
HDN | HDN-master/tools/train.py | #Copyright 2021, XinruiZhan
# A distribute version of training
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import logging
import os
import time
import math
import json
import random
import numpy as ... | 14,895 | 37.293059 | 185 | py |
HDN | HDN-master/hdn/tracker/base_tracker.py | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import cv2
import numpy as np
import torch
from hdn.core.config import cfg
from hdn.models.logpolar import getPolarImg, ... | 10,345 | 35.95 | 147 | py |
HDN | HDN-master/hdn/tracker/hdn_tracker_proj_e2e.py | #Copyright 2021, XinruiZhan
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import torch
import math
from hdn.tracker.hdn_tracker import hdnTracker
from hdn.core.config import cfg
from hdn.utils.bbo... | 14,392 | 49.149826 | 180 | py |
HDN | HDN-master/hdn/tracker/hdn_tracker.py | #Copyright 2021, XinruiZhan
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import torch
import math
from hdn.core.config import cfg
from hdn.tracker.base_tracker import SiameseTracker
from hdn.util... | 12,537 | 40.379538 | 162 | py |
HDN | HDN-master/hdn/core/xcorr.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import torch.nn.functional as F
def xcorr_slow(x, kernel):
"""for loop to calculate cross correlation, slow version
"""
batch = x.size()[0]
... | 2,109 | 33.032258 | 120 | py |
HDN | HDN-master/hdn/models/iou_loss.py | import torch
from torch import nn
class IOULoss(nn.Module):
def __init__(self, loc_loss_type):
super(IOULoss, self).__init__()
self.loc_loss_type = loc_loss_type
def forward(self, pred, target, weight=None):
pred_left = pred[:, 0]
pred_top = pred[:, 1]
pred_right = pre... | 1,855 | 35.392157 | 95 | py |
HDN | HDN-master/hdn/models/model_builder_e2e_unconstrained_v2.py | #Copyright 2021, XinruiZhan
'''
Designed for end-to-end homo-estimation.
unconstrained means we whether dataset give us label we can train the model.
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
impo... | 26,131 | 45.415631 | 262 | py |
HDN | HDN-master/hdn/models/init_weight.py | import torch.nn as nn
def init_weights(model):
for m in model.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight.data,
mode='fan_out',
nonlinearity='relu')
elif isinstance(m, nn.BatchNorm2d):
... | 386 | 31.25 | 56 | py |
HDN | HDN-master/hdn/models/loss.py | #Copyright 2021, XinruiZhan
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from hdn.core.config import cfg
from hdn.models.iou_los... | 8,330 | 38.112676 | 111 | py |
HDN | HDN-master/hdn/models/logpolar.py | import cv2
import numpy as np
import math
import torch.nn as nn
import torch.nn.functional as F
import torch
import matplotlib.pyplot as plt
from hdn.core.config import cfg
def getPolarImg(img, original = None):
"""
some assumption that img W==H
:param img: image
:return: polar image
"""
sz = ... | 11,196 | 33.558642 | 102 | py |
HDN | HDN-master/hdn/models/backbone/resnet_atrous.py | import math
import torch.nn as nn
import torch
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50']
def conv3x3(in_planes, out_planes, stride=1, dilation=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, bias=... | 7,286 | 29.746835 | 78 | py |
HDN | HDN-master/hdn/models/backbone/mobile_v2.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import torch.nn as nn
def conv_bn(inp, oup, stride, padding=1):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, padding, bias=False),
... | 4,315 | 27.20915 | 77 | py |
HDN | HDN-master/hdn/models/backbone/alexnet.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch.nn as nn
class AlexNetLegacy(nn.Module):
configs = [3, 96, 256, 384, 384, 256]
def __init__(self, width_mult=1):
configs = list(map(lambda... | 2,991 | 31.521739 | 72 | py |
HDN | HDN-master/hdn/models/neck/neck.py | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch.nn as nn
class AdjustLayer(nn.Module):
def __init__(self, in_channels, out_channels, cut=True, cut_lef... | 1,709 | 31.884615 | 101 | py |
HDN | HDN-master/hdn/models/neck/__init__.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import torch.nn as nn
import torch.nn.functional as F
from hdn.models.neck.neck import AdjustLayer, AdjustAllLayer
NECKS = {
'AdjustLayer': Adjus... | 445 | 21.3 | 60 | py |
HDN | HDN-master/hdn/models/head/ban.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import torch.nn as nn
import torch.nn.functional as F
from hdn.core.xcorr import xcorr_fast, xcorr_depthwise
class BAN(nn.Module):
def __init__(self):
... | 4,392 | 33.054264 | 107 | py |
HDN | HDN-master/hdn/models/head/ban_lp.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import torch.nn as nn
import torch.nn.functional as F
from hdn.core.xcorr import xcorr_fast, xcorr_depthwise, xcorr_depthwise_circular
from hdn.models.head.... | 3,288 | 34.365591 | 111 | py |
HDN | HDN-master/hdn/datasets/custom_transforms.py | import torch
import numpy as np
import cv2
class Normalize(object):
def __init__(self):
self.mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
self.std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
def __call__(self, sample):
return (sample / 255. - self.mean) / self.std
... | 478 | 27.176471 | 69 | py |
HDN | HDN-master/hdn/datasets/dataset/unconstrained_v2_dataset.py | #Copyright 2021, XinruiZhan
"""
this file implements the perspective transforma augmentation on template image as search, or just use sampled two images from video as template and search.
we just need to adjust the interval, if there is interval we use unsupervised, if not, then use supervised
"""
from __future__ impo... | 19,251 | 46.535802 | 156 | py |
HDN | HDN-master/hdn/datasets/dataset/dataset.py | #Copyright 2021, XinruiZhan
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torchvision.transforms as transforms
from hdn.datasets.custom_transforms import Normalize, ToTensor
import orjson as json
import loggi... | 15,007 | 39.128342 | 146 | py |
HDN | HDN-master/hdn/utils/lr_scheduler.py | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import math
import numpy as np
from torch.optim.lr_scheduler import _LRScheduler
from hdn.core.config import cfg
clas... | 7,253 | 31.097345 | 107 | py |
HDN | HDN-master/hdn/utils/model_load.py | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import torch
from memory_profiler import profile
logger = logging.getLogger('global')
def check_keys(... | 4,183 | 36.026549 | 108 | py |
HDN | HDN-master/hdn/utils/point.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import torch
"""
cpu version
"""
#generate grid for NM
def generate_points(stride, size):
ori = - (size // 2) * stride # -96
x, y = np.meshgr... | 3,894 | 37.186275 | 106 | py |
HDN | HDN-master/hdn/utils/homo_utils.py | import torch
import numpy as np
import cv2
def DLT_solve(src_p, off_set):
# src_p: shape=(bs, n, 4, 2)
# off_set: shape=(bs, n, 4, 2)
# can be used to compute mesh points (multi-H)
bs, _ = src_p.shape
divide = int(np.sqrt(len(src_p[0]) / 2) - 1)
row_num = (divide + 1) * 2
for i in range(d... | 12,410 | 35.183673 | 119 | py |
HDN | HDN-master/hdn/utils/transform.py | #Copyright 2021, XinruiZhan
import cv2
import matplotlib.pyplot as plt
import math
import numpy as np
import torch
def img_padding(img, sx, sy):
"""
add padding to an image [w,h] => [w+sx*2, h+sy*2]
:param img:
:param sx:
:param sy:
:return:
"""
padd_w = img.shape[1] + sx*2
padd_h = ... | 19,034 | 35.326336 | 147 | py |
HDN | HDN-master/hdn/utils/basic_trackers.py | import cv2
import matplotlib.pyplot as plt
import math
import numpy as np
import torch
from math import sin, cos, atan2, sqrt, degrees
from hdn.core.config import cfg
sift = cv2.xfeatures2d.SIFT_create()
def find_homo_by_imgs_opencv_ORB_ransac(im1, im2):
MAX_FEATURES = 500
GOOD_MATCH_PERCENT = 0.15
# Con... | 4,807 | 32.158621 | 98 | py |
HDN | HDN-master/hdn/utils/distributed.py | """
distriebuted training method
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import socket
import logging
import torch
import torch.nn as nn
import torch.distributed as dist
from hdn.utils.log_helpe... | 3,606 | 23.705479 | 78 | py |
HDN | HDN-master/hdn/utils/general.py | # coding: utf-8
import argparse
import torch
from torch.utils.data import DataLoader
import torch.nn as nn
import imageio
import os
import numpy as np
import matplotlib.pyplot as plt
def geometricDistance(correspondence, h):
"""
Correspondence err
:param correspondence: Coordinate
:param h: Homography
... | 983 | 23.6 | 81 | py |
HDN | HDN-master/toolkit/datasets/DeepHomo.py | from torch.utils.data import Dataset
import numpy as np
import cv2, torch
import os
def make_mesh(patch_w, patch_h):
x_flat = np.arange(0, patch_w)
x_flat = x_flat[np.newaxis, :]
y_one = np.ones(patch_h)
y_one = y_one[:, np.newaxis]
x_mesh = np.matmul(y_one, x_flat)
y_flat = np.arange(0, patc... | 6,774 | 36.021858 | 118 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/resnet.py | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch, imageio
from homo_estimator.Deep_homography.Oneline_DLTv1.utils import transform, DLT_solve
import matplotlib.pyplot as plt
criterion_l2 = nn.MSELoss(reduce=True, size_average=True)
triplet_loss = nn.TripletMarginLoss(margin=1.0, p=1, reduce=... | 16,688 | 36.672686 | 118 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/utils.py | import torch
import numpy as np
import cv2
import subprocess
import psutil
def DLT_solve(src_p, off_set):
# src_p: shape=(bs, n, 4, 2)
# off_set: shape=(bs, n, 4, 2)
# can be used to compute mesh points (multi-H)
bs, _ = src_p.shape
divide = int(np.sqrt(len(src_p[0])/2)-1)
row_num = (divide+1)*... | 12,962 | 33.293651 | 136 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/dataset.py | from torch.utils.data import Dataset
import numpy as np
import cv2, torch
import os
"""
Train_dataset+test_dataset. [Deep_Homography](https://github.com/JirongZhang/DeepHomography)provided dataset,
for training two homography estimation for two images we do not use this
"""
def make_mesh(patch_w,patch_h):
x_flat... | 6,550 | 36.221591 | 115 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/backbone/resnet.py | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch, imageio
# from utils import transform, DLT_solve
import matplotlib.pyplot as plt
"""
homo-estimator's backbone, reconstruction of the original Deephomography
"""
criterion_l2 = nn.MSELoss(reduce=True, size_average=True)
triplet_loss = nn.T... | 8,165 | 30.774319 | 115 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/backbone/__init__.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from torch import nn
import homo_estimator.Deep_homography.Oneline_DLTv1.backbone.resnet as resnet
import torch.utils.model_zoo as model_zoo
# from test_ideas.net.unet imp... | 2,249 | 38.473684 | 93 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/tools/get_img_info.py | # coding: utf-8
import argparse
from homo_estimator.Deep_homography.Oneline_DLTv1.dataset import *
import numpy as np
"""
In order to get template and search images info as input of homo-estiamtor network.
"""
def get_template_info(template):
"""
In order to preserve time, we separate the procedure of obtaining... | 6,470 | 36.842105 | 104 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/models/homo_model_builder.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch.nn as nn
import torch.nn.functional as F
import imageio
from hdn.core.config import cfg
from homo_estimator.Deep_homography.Oneline_DLTv1.backbone import get... | 8,336 | 37.243119 | 118 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/preprocess/input_mask_generator.py | import torch.nn as nn
class MaskGenerator(nn.Module):
def __init__(self, ):
super(MaskGenerator, self).__init__()
self.genMask = nn.Sequential(
nn.Conv2d(1, 4, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(4),
nn.ReLU(inplace=True),
nn.Conv2d... | 1,164 | 30.486486 | 68 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/preprocess/input_feature_extractor.py | import torch.nn as nn
class PreShareFeature(nn.Module):
def __init__(self, ):
super(PreShareFeature, self).__init__()
self.ShareFeature = nn.Sequential(
nn.Conv2d(1, 4, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(4),
nn.ReLU(inplace=True),
... | 982 | 29.71875 | 66 | py |
SIGIR2021 | SIGIR2021-master/src/utils.py | import os
import torch
import datetime
def print_message(*s):
s = ' '.join([str(x) for x in s])
print("[{}] {}".format(datetime.datetime.utcnow().strftime("%b %d, %H:%M:%S"), s), flush=True)
def save_checkpoint(path, epoch_idx, mb_idx, model, optimizer):
print("#> Saving a checkpoint..")
checkpoint... | 1,309 | 24.686275 | 98 | py |
SIGIR2021 | SIGIR2021-master/src/model.py | import torch
import torch.nn as nn
from nltk.stem import PorterStemmer
from random import sample, shuffle, randint
from itertools import accumulate
from transformers import *
import re
from src.parameters import DEVICE
from src.utils2 import cleanQ, cleanD
stem = PorterStemmer().stem
MAX_LENGTH = 300
def unique(s... | 6,377 | 37.421687 | 119 | py |
SIGIR2021 | SIGIR2021-master/src/model_multibert.py | import torch
import torch.nn as nn
from nltk.stem import PorterStemmer
from random import sample, shuffle, randint
from transformers import *
import re
from itertools import accumulate
from src.parameters import DEVICE
from src.utils2 import cleanQ, cleanD
stem = PorterStemmer().stem
MAX_LENGTH = 300
def unique(seq... | 4,114 | 38.951456 | 119 | py |
SIGIR2021 | SIGIR2021-master/src/parameters.py | import torch
DEVICE = torch.device("cuda:0")
DEFAULT_DATA_DIR = './data_download/'
SAVED_CHECKPOINTS = [32*1000, 100*1000, 150*1000, 200*1000, 300*1000, 400*1000]
| 166 | 19.875 | 79 | py |
SIGIR2021 | SIGIR2021-master/src/train.py | import os
import random
import torch
from argparse import ArgumentParser
from src.training.data_reader import train
from src.utils import print_message, create_directory
def main():
random.seed(12345)
torch.manual_seed(1)
parser = ArgumentParser(description='Training ColBERT with <query, positive passa... | 1,761 | 34.959184 | 128 | py |
SIGIR2021 | SIGIR2021-master/src/index.py | import random
import datetime
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from time import time
from math import ceil
from src.model_multibert import *
from multiprocessing import Pool
from src.evaluation.loaders import load_checkpoint
MB_SIZE = 1024
def print_message(*s):
s... | 3,047 | 29.787879 | 119 | py |
SIGIR2021 | SIGIR2021-master/src/evaluation/ranking.py | import os
import random
import time
import torch
from src.utils import print_message, load_checkpoint, batch
from src.evaluation.metrics import Metrics
def rerank(args, query, pids, passages, index=None):
colbert = args.colbert
#tokenized_passages = list(args.pool.map(colbert.tokenizer.tokenize, passages))
... | 2,777 | 38.126761 | 116 | py |
SIGIR2021 | SIGIR2021-master/src/training/data_reader.py | import os
import random
import torch
import torch.nn as nn
from argparse import ArgumentParser
from transformers import AdamW
from src.parameters import DEVICE, SAVED_CHECKPOINTS
from src.model import MultiBERT
from src.utils import print_message, save_checkpoint
import re
import datetime
class TrainReader:
def ... | 2,567 | 31.923077 | 119 | py |
LoGo | LoGo-main/main.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.9
import os
import sys
import json
import random
import copy
import pickle
import numpy as np
import pandas as pd
import medmnist
from medmnist import INFO
import torch
import torch.nn.functional as F
from torchvision import datasets, transforms
from ... | 10,805 | 47.457399 | 148 | py |
LoGo | LoGo-main/models/resnet.py | import torch
import torch.nn as nn
__all__ = ['resnet10', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'wide_resnet50_2', 'wide_resnet101_2']
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out... | 9,005 | 37.323404 | 109 | py |
LoGo | LoGo-main/models/mobilenet.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.9
import torch
from torch import nn
import torch.nn.functional as F
'''MobileNet in PyTorch.
See the paper "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
for more details.
'''
class Block(nn.Module):
'''Depth... | 2,277 | 35.15873 | 123 | py |
LoGo | LoGo-main/models/cnn4conv.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.9
import torch
from torch import nn
def conv3x3(in_channels, out_channels, **kwargs):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, **kwargs),
nn.BatchNorm2d(out_channels, track_running_stats=... | 1,416 | 27.34 | 81 | py |
LoGo | LoGo-main/util/longtail_dataset.py | import numpy as np
from PIL import Image
from torchvision import datasets, transforms
class IMBALANCECIFAR10(datasets.CIFAR10):
cls_num = 10
def __init__(self, phase, imbalance_ratio, root='data/cifar10_lt/', imb_type='exp', train_aug=True):
train = True if phase == 'train' else False
super(... | 4,753 | 34.214815 | 113 | py |
LoGo | LoGo-main/util/misc.py | import numpy as np
from torch.utils.data import Dataset
class DatasetSplit(Dataset):
def __init__(self, dataset, idxs):
self.dataset = dataset
self.idxs = list(idxs)
def __len__(self):
return len(self.idxs)
def __getitem__(self, item):
image, label = self.dataset[self.id... | 696 | 21.483871 | 52 | py |
LoGo | LoGo-main/util/data_simulator.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.9
import os
import math
import pickle
import random
import numpy as np
import torch
def shard_balance(dataset, args):
K = args.num_classes
y_train_dict = {i: [] for i in range(K)}
for idx, d in enumerate(dataset):
if args.dat... | 6,082 | 34.782353 | 119 | py |
LoGo | LoGo-main/fl_methods/base.py | import copy
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from util.misc import DatasetSplit
class FederatedLearning:
def __init__(self, args, dict_users_train_label=None):
self.args = args
self.dict_users_train_label = dict_users_train_label
self.loss_func =... | 2,247 | 32.058824 | 115 | py |
LoGo | LoGo-main/fl_methods/fedprox.py | import copy
import torch
from .base import FederatedLearning
class FedProx(FederatedLearning):
def __init__(self, args, dict_users_train_label=None):
super().__init__(args, dict_users_train_label)
def train(self, net, user_idx=None, lr=0.01, momentum=0.9, weight_decay=0.00001):
net.train()
... | 1,709 | 33.897959 | 109 | py |
LoGo | LoGo-main/fl_methods/fedavg.py | import torch
from .base import FederatedLearning
class FedAvg(FederatedLearning):
def __init__(self, args, dict_users_train_label=None):
super().__init__(args, dict_users_train_label)
def train(self, net, user_idx=None, lr=0.01, momentum=0.9, weight_decay=0.00001):
net.train()
# tra... | 1,393 | 33.85 | 109 | py |
LoGo | LoGo-main/fl_methods/scaffold.py | import copy
import torch
from .base import FederatedLearning
class SCAFFOLD(FederatedLearning):
def __init__(self, args, dict_users_train_label=None):
super().__init__(args, dict_users_train_label)
def init_c_nets(self, net_glob):
self.c_nets = {}
for i in range(self.args.num_users)... | 3,530 | 37.380435 | 132 | py |
LoGo | LoGo-main/query_strategies/margin_sampling.py | import copy
import numpy as np
import torch
import torch.nn as nn
from .strategy import Strategy
class MarginSampling(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
unlabel_idxs = np.array(unlabel_idxs)
if self.args.query_model_mode == "global":
... | 753 | 26.925926 | 69 | py |
LoGo | LoGo-main/query_strategies/dbal.py | import copy
import numpy as np
from tqdm import tqdm
from sklearn.cluster import KMeans
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from .strategy import Strategy
class DatasetSplit(Dataset):
def __init__(self, dataset, idxs):
self.dataset = dataset
... | 1,679 | 30.111111 | 90 | py |
LoGo | LoGo-main/query_strategies/alfa_mix.py | import copy
import math
import numpy as np
from select import select
from sklearn.cluster import KMeans
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
from torch.autograd import Variable
from .strategy import Strategy, DatasetSplit
class ALFAMix(Strategy):
def __in... | 10,525 | 39.484615 | 151 | py |
LoGo | LoGo-main/query_strategies/egl.py | import copy
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
from .strategy import Strategy
class DatasetSplit(Dataset):
def __init__(self, dataset, idxs):
self.dataset = dataset
self.idxs = list(idxs)
def __len__(self):
return l... | 1,812 | 31.963636 | 94 | py |
LoGo | LoGo-main/query_strategies/entropy_sampling.py | import copy
import numpy as np
import torch
from .strategy import Strategy
class EntropySampling(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
unlabel_idxs = np.array(unlabel_idxs)
if self.args.query_model_mode == "global":
probs = self.predict... | 766 | 28.5 | 69 | py |
LoGo | LoGo-main/query_strategies/strategy.py | import copy
import numpy as np
from copy import deepcopy
from datetime import datetime
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.data import DataLoader, Dataset
class DatasetSplit(Dataset):
def __init__(self... | 6,979 | 36.326203 | 123 | py |
LoGo | LoGo-main/query_strategies/gcnal.py | import math
import numpy as np
from tqdm import tqdm
from sklearn.metrics import pairwise_distances
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import Dataset
from torch.nn.parameter import Parameter
from .strategy import Strategy
class GCNAL(... | 6,451 | 31.918367 | 117 | py |
LoGo | LoGo-main/query_strategies/__init__.py | import os
import sys
import copy
import pickle
import random
import datetime
import numpy as np
import torch
from models import get_model
from .random_sampling import RandomSampling
from .least_confidence import LeastConfidence
from .margin_sampling import MarginSampling
from .entropy_sampling import EntropySampling
... | 5,878 | 40.695035 | 149 | py |
LoGo | LoGo-main/query_strategies/adversial_deepfool.py | import copy
import numpy as np
from tqdm import tqdm
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset
from .strategy import Strategy
class DatasetSplit(Dataset):
def __init__(self, dataset, idxs):
self.dataset = dataset
self.idxs = list(idxs)
def __len__(sel... | 2,570 | 27.566667 | 90 | py |
LoGo | LoGo-main/query_strategies/fal/ensemble_logit.py | import pdb
import copy
import numpy as np
from scipy import stats
from sklearn.metrics import pairwise_distances
import torch
from ..strategy import Strategy
class EnsLogitConf(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
unlabel_idxs = np.array(unlabel_idxs)
... | 4,828 | 30.769737 | 113 | py |
LoGo | LoGo-main/query_strategies/fal/logo.py | import copy
import math
import numpy as np
from copy import deepcopy
from sklearn.cluster import KMeans
import torch
import torch.nn as nn
from ..strategy import Strategy
class LoGo(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
unlabel_idxs = np.array(unlabel_idxs)
... | 3,718 | 37.340206 | 101 | py |
LoGo | LoGo-main/query_strategies/fal/ensemble_rank.py | import pdb
import copy
import numpy as np
from enum import unique
from scipy import stats
from sklearn.metrics import pairwise_distances
import torch
from ..strategy import Strategy
class EnsRankEntropy(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
unlabel_idxs = np.array(... | 3,720 | 32.522523 | 117 | py |
LoGo | LoGo-main/query_strategies/fal/finetuning.py | import pdb
import copy
import numpy as np
from enum import unique
from scipy import stats
from copy import deepcopy
from sklearn.metrics import pairwise_distances
import torch
from ..strategy import Strategy
class FTEntropy(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
unl... | 2,217 | 30.239437 | 88 | py |
ReChorus | ReChorus-master/src/main.py | # -*- coding: UTF-8 -*-
import os
import sys
import pickle
import logging
import argparse
import pandas as pd
import torch
from helpers import *
from models.general import *
from models.sequential import *
from models.developing import *
from utils import utils
def parse_global_args(parser):
parser.add_argument... | 5,462 | 39.768657 | 102 | py |
ReChorus | ReChorus-master/src/helpers/BaseRunner.py | # -*- coding: UTF-8 -*-
import os
import gc
import torch
import torch.nn as nn
import logging
import numpy as np
from time import time
from tqdm import tqdm
from torch.utils.data import DataLoader
from typing import Dict, List
from utils import utils
from models.BaseModel import BaseModel
class BaseRunner(object):
... | 11,452 | 46.131687 | 124 | py |
ReChorus | ReChorus-master/src/helpers/BUIRRunner.py | # -*- coding: UTF-8 -*-
import os
import gc
import torch
import torch.nn as nn
import logging
import numpy as np
from time import time
from tqdm import tqdm
from torch.utils.data import DataLoader
from utils import utils
from models.BaseModel import BaseModel
from helpers.BaseRunner import BaseRunner
class BUIRRunn... | 1,327 | 33.051282 | 104 | py |
ReChorus | ReChorus-master/src/models/BaseModel.py | # -*- coding: UTF-8 -*-
import torch
import logging
import numpy as np
from tqdm import tqdm
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset as BaseDataset
from torch.nn.utils.rnn import pad_sequence
from typing import List
from utils import utils
from helpers.BaseReader imp... | 9,962 | 39.173387 | 119 | py |
ReChorus | ReChorus-master/src/models/general/NeuMF.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" NeuMF
Reference:
"Neural Collaborative Filtering"
Xiangnan He et al., WWW'2017.
Reference code:
The authors' tensorflow implementation https://github.com/hexiangnan/neural_collaborative_filtering
CMD example:
python... | 2,848 | 36 | 103 | py |
ReChorus | ReChorus-master/src/models/general/BPRMF.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" BPRMF
Reference:
"Bayesian personalized ranking from implicit feedback"
Rendle et al., UAI'2009.
CMD example:
python main.py --model_name BPRMF --emb_size 64 --lr 1e-3 --l2 1e-6 --dataset 'Grocery_and_Gourmet_Food'
"""
... | 1,534 | 30.326531 | 108 | py |
ReChorus | ReChorus-master/src/models/general/BUIR.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" BUIR
Reference:
"Bootstrapping User and Item Representations for One-Class Collaborative Filtering"
Lee et al., SIGIR'2021.
CMD example:
python main.py --model_name BUIR --emb_size 64 --lr 1e-3 --l2 1e-6 --dataset 'Groc... | 4,676 | 39.318966 | 115 | py |
ReChorus | ReChorus-master/src/models/general/CFKG.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" CFKG
Reference:
"Learning over Knowledge-Base Embeddings for Recommendation"
Yongfeng Zhang et al., SIGIR'2018.
Note:
In the built-in dataset, we have four kinds of relations: buy, category, complement, substitute, wher... | 6,084 | 45.807692 | 115 | py |
ReChorus | ReChorus-master/src/models/general/DirectAU.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" DirectAU
Reference:
"Towards Representation Alignment and Uniformity in Collaborative Filtering"
Wang et al., KDD'2022.
CMD example:
python main.py --model_name DirectAU --dataset Grocery_and_Gourmet_Food \
... | 2,990 | 30.484211 | 82 | py |
ReChorus | ReChorus-master/src/models/general/LightGCN.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" LightGCN
Reference:
"LightGCN: Simplifying and Powering Graph Convolution Network for Recommendation"
He et al., SIGIR'2020.
CMD example:
python main.py --model_name LightGCN --emb_size 64 --n_layers 3 --lr 1e-3 --l2 1e... | 4,769 | 34.597015 | 109 | py |
ReChorus | ReChorus-master/src/models/general/POP.py | # -*- coding: UTF-8 -*-
import torch
import numpy as np
from models.BaseModel import GeneralModel
class POP(GeneralModel):
"""
Recommendation according to item's popularity.
Should run with --train 0
"""
def __init__(self, args, corpus):
super().__init__(args, corpus)
self.popula... | 774 | 28.807692 | 75 | py |
ReChorus | ReChorus-master/src/models/developing/SRGNN.py | # -*- coding: UTF-8 -*-
import torch
from torch import nn
from torch.nn import Parameter
from torch.nn import functional as F
import numpy as np
from models.BaseModel import SequentialModel
class SRGNN(SequentialModel):
reader = 'SeqReader'
runner = 'BaseRunner'
extra_log_args = ['num_layers']
@sta... | 6,782 | 43.045455 | 114 | py |
ReChorus | ReChorus-master/src/models/developing/S3Rec.py | # -*- coding: UTF-8 -*-
import os
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from models.BaseModel import SequentialModel
from utils import layers
class S3Rec(SequentialModel):
reader = 'SeqReader'
runner = 'BaseRunner'
extra_log_args = ['emb_siz... | 10,204 | 46.465116 | 117 | py |
ReChorus | ReChorus-master/src/models/developing/FourierTA.py | # -*- coding: UTF-8 -*-
import torch
import torch.nn as nn
import numpy as np
from utils import layers
from models.BaseModel import SequentialModel
from helpers.KDAReader import KDAReader
class FourierTA(SequentialModel):
reader = 'SeqReader'
runner = 'BaseRunner'
extra_log_args = ['t_scalar']
@sta... | 5,011 | 40.421488 | 99 | py |
ReChorus | ReChorus-master/src/models/developing/CLRec.py | # -*- coding: UTF-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from models.BaseModel import SequentialModel
from utils import layers
class CLRec(SequentialModel):
reader = 'SeqReader'
runner = 'BaseRunner'
extra_log_args = ['batch_size', 'temp']
@stati... | 5,081 | 35.826087 | 102 | py |
ReChorus | ReChorus-master/src/models/sequential/FPMC.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" FPMC
Reference:
"Factorizing Personalized Markov Chains for Next-Basket Recommendation"
Rendle et al., WWW'2010.
CMD example:
python main.py --model_name FPMC --emb_size 64 --lr 1e-3 --l2 1e-6 --history_max 20 \
--d... | 2,684 | 35.283784 | 114 | py |
ReChorus | ReChorus-master/src/models/sequential/SASRec.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" SASRec
Reference:
"Self-attentive Sequential Recommendation"
Kang et al., IEEE'2018.
Note:
When incorporating position embedding, we make the position index start from the most recent interaction.
CMD example:
pytho... | 3,606 | 38.637363 | 109 | py |
ReChorus | ReChorus-master/src/models/sequential/Caser.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" Caser
Reference:
"Personalized Top-N Sequential Recommendation via Convolutional Sequence Embedding"
Jiaxi Tang et al., WSDM'2018.
Reference code:
https://github.com/graytowne/caser_pytorch
Note:
We use a maximum of... | 4,363 | 41.368932 | 119 | py |
ReChorus | ReChorus-master/src/models/sequential/SLRCPlus.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" SLRC+
Reference:
"Modeling Item-specific Temporal Dynamics of Repeat Consumption for Recommender Systems"
Chenyang Wang et al., TheWebConf'2019.
Reference code:
The authors' tensorflow implementation https://github.com/... | 5,414 | 45.282051 | 111 | py |
ReChorus | ReChorus-master/src/models/sequential/NARM.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" NARM
Reference:
"Neural Attentive Session-based Recommendation"
Jing Li et al., CIKM'2017.
CMD example:
python main.py --model_name NARM --emb_size 64 --hidden_size 100 --attention_size 4 --lr 1e-3 --l2 1e-4 \
--his... | 3,776 | 43.435294 | 118 | py |
ReChorus | ReChorus-master/src/models/sequential/Chorus.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" Chorus
Reference:
"Make It a Chorus: Knowledge- and Time-aware Item Modeling for Sequential Recommendation"
Chenyang Wang et al., SIGIR'2020.
CMD example:
python main.py --model_name Chorus --emb_size 64 --margin 1 --lr... | 12,854 | 49.214844 | 119 | py |
ReChorus | ReChorus-master/src/models/sequential/ContraKDA.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" ContraKDA (KDA + ContraRec)
Reference:
"Toward Dynamic User Intention: Temporal Evolutionary Effects of Item Relations in Sequential Recommendation"
Chenyang Wang et al., TOIS'2021.
Sequential Recommendation with Multip... | 20,256 | 47.577938 | 116 | py |
ReChorus | ReChorus-master/src/models/sequential/TiMiRec.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" TiMiRec
Reference:
"Target Interest Distillation for Multi-Interest Recommendation"
Wang et al., CIKM'2022.
CMD example:
python main.py --model_name TiMiRec --dataset Grocery_and_Gourmet_Food \
--emb_... | 10,124 | 45.875 | 114 | py |
ReChorus | ReChorus-master/src/models/sequential/ContraRec.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" ContraRec
Reference:
"Sequential Recommendation with Multiple Contrast Signals"
Wang et al., TOIS'2022.
CMD example:
python main.py --model_name ContraRec --emb_size 64 --lr 1e-4 --l2 1e-6 --history_max 20 --encoder BER... | 11,519 | 40.588448 | 113 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.