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
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/monsterkong/monsterPerson.py
__author__ = 'Erilyth' import pygame import os from .person import Person ''' This class defines all the Monsters present in our game. Each Monster can only move on the top floor and cannot move vertically. ''' class MonsterPerson(Person): def __init__(self, raw_image, position, rng, dir, width=15, height=15): ...
6,131
43.434783
126
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/monsterkong/onBoard.py
__author__ = 'Batchu Vishal' import pygame class OnBoard(pygame.sprite.Sprite): ''' This class defines all inanimate objects that we need to display on our board. Any object that is on the board and not a person, comes under this class (ex. Coins,Ladders,Walls etc) Sets up the image and its position f...
1,433
34.85
113
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/monsterkong/person.py
__author__ = 'Batchu Vishal' import pygame ''' This class defines all living things in the game, ex.Donkey Kong, Player etc Each of these objects can move in any direction specified. ''' class Person(pygame.sprite.Sprite): def __init__(self, raw_image, position, width, height): super(Person, self).__ini...
2,660
35.958333
126
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/monsterkong/coin.py
__author__ = 'Batchu Vishal' import pygame import os from .onBoard import OnBoard class Coin(OnBoard): """ This class defines all our coins. Each coin will increase our score by an amount of 'value' We animate each coin with 5 images A coin inherits from the OnBoard class since we will use it as a...
1,900
43.209302
129
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/monsterkong/player.py
__author__ = 'Batchu Vishal' from .person import Person ''' This class defines our player. It inherits from the Person class since a Player is also a person. We specialize the person by adding capabilities such as jump etc.. ''' class Player(Person): def __init__(self, raw_image, position, width, height): ...
3,438
44.25
97
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/monsterkong/wall.py
__author__ = 'Batchu Vishal' from onBoard import OnBoard import pygame ''' This class defines all our walls in the game. Currently not much is done here, but we can add traps to certain walls such as spiked walls etc to damage the player ''' class Wall(OnBoard): def __init__(self, raw_image, position): ...
534
25.75
116
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/monsterkong/__init__.py
__author__ = 'Batchu Vishal' import pygame import sys from pygame.constants import K_a, K_d, K_SPACE, K_w, K_s, QUIT, KEYDOWN from .board import Board #from ..base import base #from ple.games import base from ple.games.base.pygamewrapper import PyGameWrapper import numpy as np import os class MonsterKong(PyGameWrappe...
9,882
41.78355
104
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/doom/doom.py
import os from ..base.doomwrapper import DoomWrapper class Doom(DoomWrapper): def __init__(self, scenario="basic"): cfg_file = "assets/cfg/%s.cfg" % scenario scenario_file = "%s.wad" % scenario width = 320 height = 240 package_directory = os.path.dirname(os.pa...
506
28.823529
70
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/doom/__init__.py
from .doom import Doom
23
11
22
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/base/__init__.py
from .pygamewrapper import PyGameWrapper try: from .doomwrapper import DoomWrapper except: print("couldn't import doomish")
132
21.166667
40
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/base/doomwrapper.py
import sys import time import numpy as np import pygame try: #ty @ gdb & ppaquette import doom_py import doom_py.vizdoom as vizdoom except ImportError: raise ImportError("Please install doom_py.") class DoomWrapper(object): def __init__(self, width, height, cfg_file, scenario_file): sel...
4,175
27.60274
96
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/base/pygamewrapper.py
import pygame import numpy as np from pygame.constants import KEYDOWN, KEYUP, K_F15 class PyGameWrapper(object): """PyGameWrapper class ple.games.base.PyGameWrapper(width, height, actions={}) This :class:`PyGameWrapper` class sets methods all games require. It should be subclassed when creating new gam...
5,629
24.825688
157
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/utils/vec2d.py
import math class vec2d(): def __init__(self, pos): self.x = pos[0] self.y = pos[1] def __add__(self, o): x = self.x + o.x y = self.y + o.y return vec2d((x, y)) def __eq__(self, o): return self.x == o.x and self.y == o.y def normalize(self): ...
419
17.26087
59
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/utils/__init__.py
import numpy as np def percent_round_int(percent, x): return np.round(percent * x).astype(int)
101
16
44
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/ple/games/flappybird/__init__.py
import os import sys import numpy as np import pygame from pygame.constants import K_w from .. import base class BirdPlayer(pygame.sprite.Sprite): def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, init_pos, image_assets, rng, color="red", scale=1.0): self.SCREEN_WIDTH = ...
13,508
29.632653
144
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/examples/example_doom.py
import numpy as np from ple import PLE from ple.games import Doom class NaiveAgent(): """ This is our naive agent. It picks actions at random! """ def __init__(self, actions): self.actions = actions def pickAction(self, reward, obs): return self.actions[np.random.randint(0, len(self.actions))] ############...
867
21.842105
62
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/examples/keras_nonvis.py
# thanks to @edersantana and @fchollet for suggestions & help. import numpy as np from ple import PLE # our environment from ple.games.catcher import Catcher from keras.models import Sequential from keras.layers.core import Dense from keras.optimizers import SGD from example_support import ExampleAgent, ReplayMemor...
5,449
31.634731
167
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/examples/example_support.py
import numpy as np from collections import deque # keras and model related from keras.models import Sequential from keras.layers.core import Dense, Flatten from keras.layers.convolutional import Convolution2D from keras.optimizers import SGD, Adam, RMSprop import theano.tensor as T class ExampleAgent(): """ ...
6,844
30.837209
201
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/examples/random_agent.py
import numpy as np from ple import PLE from ple.games.raycastmaze import RaycastMaze class NaiveAgent(): """ This is our naive agent. It picks actions at random! """ def __init__(self, actions): self.actions = actions def pickAction(self, reward, obs): return self.actions...
1,263
20.793103
68
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/examples/scaling_rewards.py
import numpy as np from ple import PLE from ple.games.waterworld import WaterWorld # lets adjust the rewards our agent recieves rewards = { "tick": -0.01, # each time the game steps forward in time the agent gets -0.1 "positive": 1.0, # each time the agent collects a green circle "negative": -5.0, # ea...
937
30.266667
82
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/tests/test_ple_doom.py
#!/usr/bin/python import nose import nose import numpy as np import unittest class NaiveAgent(): def __init__(self, actions): self.actions = actions def pickAction(self, reward, obs): return self.actions[np.random.randint(0, len(self.actions))] class MyTestCase(unittest.TestCase): de...
779
18.5
68
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/tests/test_ple.py
#!/usr/bin/python """ This tests that all the PLE games launch, except for doom; we explicitly check that it isn't defined. """ import nose import numpy as np import unittest NUM_STEPS=150 class NaiveAgent(): def __init__(self, actions): self.actions = actions def pickAction(self, reward, obs):...
2,211
23.043478
68
py
PyGame-Learning-Environment
PyGame-Learning-Environment-master/docs/conf.py
import sys import os from mock import Mock sys.modules['pygame'] = Mock() sys.modules['pygame.constants'] = Mock() #so we can import ple sys.path.append(os.path.join(os.path.dirname(__name__), "..")) extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'sphinx.ext.viewc...
1,940
22.962963
95
py
Intraclass-clustering-measures
Intraclass-clustering-measures-main/kendal_coefficient.py
import math as m import numpy as np np.random.seed(1) def kendall_coeff(metric_values,test_performances): set_size = len(metric_values) coeff = 0 count = 0 for m1,t1 in zip(metric_values,test_performances): for m2,t2 in zip(metric_values,test_performances): if (m1,t1)!=(m2,t2): ...
1,999
39.816327
113
py
Intraclass-clustering-measures
Intraclass-clustering-measures-main/measures.py
''' Measures of intraclass clustering ability and generalization ''' import sys sys.path.insert(0, "../") import warnings import numpy as np from scipy.spatial.distance import cosine from sklearn.metrics import silhouette_score, silhouette_samples, calinski_harabasz_score from sklearn.metrics.pairwise import cosine_...
23,997
45.15
181
py
Diverse-ViT
Diverse-ViT-main/main.py
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. import argparse import datetime import numpy as np import time import torch import torch.backends.cudnn as cudnn import json import warnings warnings.filterwarnings('ignore') from pathlib import Path from timm.data import Mixup from timm.models impor...
22,308
47.079741
119
py
Diverse-ViT
Diverse-ViT-main/losses.py
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. """ Implements the knowledge distillation loss """ import torch import torch.nn as nn from torch.nn import functional as F class DistillationLoss(torch.nn.Module): """ This module wraps a standard criterion and adds an extra knowledge distilla...
2,792
41.969231
114
py
Diverse-ViT
Diverse-ViT-main/engine.py
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. """ Train and eval functions used in main.py """ import sys import math import utils import torch import torch.nn as nn from timm.data import Mixup from losses import DistillationLoss from typing import Iterable, Optional from timm.utils import accura...
5,354
39.263158
98
py
Diverse-ViT
Diverse-ViT-main/hubconf.py
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. from models import * dependencies = ["torch", "torchvision", "timm"]
138
22.166667
47
py
Diverse-ViT
Diverse-ViT-main/gradinit_optimizers.py
import torch import math import pdb class RescaleAdam(torch.optim.Optimizer): r"""Implements Adam algorithm. It has been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups ...
7,541
45.269939
111
py
Diverse-ViT
Diverse-ViT-main/run_with_submitit.py
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. """ A script to run multinode training with submitit. """ import argparse import os import uuid from pathlib import Path import main as classification import submitit def parse_args(): classification_parser = classification.get_args_parser() ...
4,075
31.094488
103
py
Diverse-ViT
Diverse-ViT-main/utils.py
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. """ Misc functions, including distributed helpers. Mostly copy-paste from torchvision references. """ import io import os import time from collections import defaultdict, deque import datetime import torch import torch.distributed as dist class Smo...
7,067
28.573222
94
py
Diverse-ViT
Diverse-ViT-main/vision_transformer_diverse.py
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in 'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929 The official jax code is released and available at https://github.com/google-research/vision_transformer De...
17,793
40.574766
132
py
Diverse-ViT
Diverse-ViT-main/layers.py
import math import torch import torch.nn as nn from torch.nn import functional as F from torch.nn import init from torch.nn.parameter import Parameter from torch.nn.modules.utils import _pair class Linear(nn.Linear): def __init__(self, in_features, out_features, bias=True): super(Linear, self).__init__(in...
1,575
36.52381
95
py
Diverse-ViT
Diverse-ViT-main/datasets.py
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. import os import json from torchvision import datasets, transforms from torchvision.datasets.folder import ImageFolder, default_loader from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.data import create_transform ...
4,235
36.821429
105
py
Diverse-ViT
Diverse-ViT-main/reg.py
import torch import numpy as np from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy __all__ = ['Loss_mixing', 'Loss_cosine', 'Loss_contrastive', 'Loss_cosine_attn', 'Loss_condition_orth_weight'] # Embedding Level Size: (Batch-size, Tokens, Dims * Heads) # Attention Level Size: (B...
15,331
34.084668
115
py
Diverse-ViT
Diverse-ViT-main/models.py
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. import torch import torch.nn as nn from functools import partial from timm.models.vision_transformer import VisionTransformer, _cfg from timm.models.registry import register_model from timm.models.layers import trunc_normal_ from vision_transformer_di...
4,745
37.585366
146
py
Diverse-ViT
Diverse-ViT-main/samplers.py
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. import torch import torch.distributed as dist import math class RASampler(torch.utils.data.Sampler): """Sampler that restricts data loading to a subset of the dataset for distributed, with repeated augmentation. It ensures that different ...
2,292
37.216667
103
py
Diverse-ViT
Diverse-ViT-main/loss_scaler.py
""" CUDA / AMP utils Hacked together by / Copyright 2020 Ross Wightman """ import torch try: from apex import amp has_apex = True except ImportError: amp = None has_apex = False from timm.utils import * __all__ = ['NativeScaler'] class NativeScaler: state_dict_key = "amp_scaler" def __init_...
1,136
29.72973
138
py
Diverse-ViT
Diverse-ViT-main/gradient_utils.py
import torch from torch import nn from gradinit_optimizers import RescaleAdam import numpy as np import os class Scale(torch.nn.Module): def __init__(self): super(Scale, self).__init__() self.weight = torch.nn.Parameter(torch.ones(1)) def forward(self, x): return x * self.weight clas...
9,598
34.420664
163
py
Diverse-ViT
Diverse-ViT-main/mix.py
""" Mixup and Cutmix Papers: mixup: Beyond Empirical Risk Minimization (https://arxiv.org/abs/1710.09412) CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features (https://arxiv.org/abs/1905.04899) Code Reference: CutMix: https://github.com/clovaai/CutMix-PyTorch Hacked together by / Copyri...
5,266
42.528926
120
py
pennylane-ls
pennylane-ls-master/setup.py
from setuptools import setup pennylane_devices_list = [ "synqs.sqs = pennylane_ls:SingleQuditDevice", "synqs.mqs = pennylane_ls:MultiQuditDevice", "synqs.fs = pennylane_ls:FermionDevice", ] setup( name="pennylane-ls", version="0.3.0", description="A Pennylane plugin for cold atom quantum simul...
731
26.111111
70
py
pennylane-ls
pennylane-ls-master/heroku_credentials.py
# each user has his own credentials file. Do not share this with other users. username = "synqs_test" # Put here your username password = "Cm2TXfRmXennMQ5" # and the pwd
173
33.8
77
py
pennylane-ls
pennylane-ls-master/examples/example_credentials.py
# each user has his own credentials file. Do not share this with other users. username = "EXAMPLE-NAME" # Put here your username password = "EXAMPLE-PASSWORD" # and the pwd
176
34.4
77
py
pennylane-ls
pennylane-ls-master/pennylane_ls/multi_qudit_device.py
""" A device that allows us to implement operation on multiple qudits. The backend is a remote simulator. """ import json import requests import numpy as np from .django_device import DjangoDevice # observables from .multi_qudit_ops import LZ, ZObs # operations from .multi_qudit_ops import RLX, RLZ, RLZ2, RLXLY, R...
5,045
26.275676
78
py
pennylane-ls
pennylane-ls-master/pennylane_ls/single_qudit_ops.py
""" Define the operations that can be applied on a single_qudit device. """ from typing import List, Tuple import abc from pennylane.operation import Operation from pennylane.operation import Observable import numpy as np class SingleQuditOperation(Operation): """ A base class for all the single qudit opera...
3,314
18.96988
86
py
pennylane-ls
pennylane-ls-master/pennylane_ls/multi_qudit_ops.py
""" Define the operations that can be applied on a multi_qudit device. """ from typing import List, Tuple import abc from pennylane.operation import Operation from pennylane.operation import Observable import numpy as np class MultiQuditOperation(Operation): """ A base class for all the single qudit operati...
3,960
20.069149
85
py
pennylane-ls
pennylane-ls-master/pennylane_ls/_version.py
"""Version information. Version number (major.minor.patch[-label]) """ __version__ = "0.3.0[-dev]"
103
16.333333
45
py
pennylane-ls
pennylane-ls-master/pennylane_ls/fermion_device.py
""" A device that allows us to implement operation ons a fermion tweezer experiments. The backend is a remote simulator. """ import json from collections import OrderedDict import numpy as np import requests from pennylane import DeviceError from .django_device import DjangoDevice # observables from .fermion_ops i...
6,874
28.633621
86
py
pennylane-ls
pennylane-ls-master/pennylane_ls/single_qudit_device.py
""" A device that allows us to implement operation on a single qudit. The backend is a remote simulator. """ import json import requests import numpy as np from .django_device import DjangoDevice # observables from .single_qudit_ops import LZ, LZ2, ZObs # operations from .single_qudit_ops import RLX, RLZ, RLZ2, Loa...
5,096
29.520958
100
py
pennylane-ls
pennylane-ls-master/pennylane_ls/__init__.py
""" The initialization of the `pennylane-ls` module """ from .single_qudit_device import SingleQuditDevice from .multi_qudit_device import MultiQuditDevice from .fermion_device import FermionDevice from ._version import __version__
233
25
50
py
pennylane-ls
pennylane-ls-master/pennylane_ls/django_device.py
""" Define the base class for communication with the Django API as laid out for `labscript-qc` """ import time import json import requests from pennylane import Device class DjangoDevice(Device): """ The base class for all devices that call to an external server. """ _operation_map = {} _observa...
2,341
24.182796
79
py
pennylane-ls
pennylane-ls-master/pennylane_ls/fermion_ops.py
""" Define the operations that can be applied on a fermionic device. """ import abc from typing import List, Tuple from pennylane.wires import Wires from pennylane.operation import Operation, AnyWires, AllWires from pennylane.operation import Observable import numpy as np class FermionOperation(Operation): """ ...
6,782
24.02952
120
py
pennylane-ls
pennylane-ls-master/tests/test_multi_qudit.py
""" Tests for the multi qudit device. """ import unittest import numpy as np import pennylane as qml from pennylane_ls import multi_qudit_ops class TestMultiQuditDevice(unittest.TestCase): """ The test case for the multi qudit device. """ def setUp(self): self.username = "synqs_test" ...
1,179
23.081633
84
py
pennylane-ls
pennylane-ls-master/tests/test_fermion_device.py
""" Tests for the femrion device. """ import unittest import numpy as np import pennylane as qml from pennylane_ls import fermion_ops class TestFermionDevice(unittest.TestCase): """ The test case for the fermion device. """ def setUp(self): self.username = "synqs_test" self.password ...
4,096
24.93038
61
py
pennylane-ls
pennylane-ls-master/tests/test_single_qudit.py
""" Tests for the single qudit device. """ import unittest import numpy as np import pennylane as qml from pennylane_ls import single_qudit_ops class TestSingleQuditDevice(unittest.TestCase): """ The test case for the single qudit device. """ def setUp(self): self.username = "synqs_test" ...
1,902
24.373333
80
py
GATNE
GATNE-master/src/main.py
import math import os import sys import time import numpy as np import tensorflow as tf from numpy import random from utils import * def get_batches(pairs, neighbors, batch_size): n_batches = (len(pairs) + (batch_size - 1)) // batch_size for idx in range(n_batches): x, y, t, neigh = [], [], [], [] ...
10,842
45.939394
279
py
GATNE
GATNE-master/src/utils.py
import argparse import multiprocessing from collections import defaultdict from operator import index import numpy as np from six import iteritems from sklearn.metrics import (auc, f1_score, precision_recall_curve, roc_auc_score) from tqdm import tqdm from walk import RWGraph class Voca...
10,598
35.297945
123
py
GATNE
GATNE-master/src/walk.py
import random import multiprocessing from tqdm import tqdm def walk(args): walk_length, start, schema = args # Simulate a random walk starting from start node. rand = random.Random() if schema: schema_items = schema.split('-') assert schema_items[0] == schema_items[-1] walk = [st...
2,121
33.786885
204
py
GATNE
GATNE-master/src/main_pytorch.py
import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from numpy import random from torch.nn.parameter import Parameter from utils import * def get_batches(pairs, neighbors, batch_size): n_batches = (len(pairs) + (batch_size - 1)) // batch_size for idx in range(n...
10,920
36.400685
169
py
Viola-Unet
Viola-Unet-main/main.py
import argparse, os import time import numpy as np import torch from load_model import load_model, infer_seg, nibout, infer_seg_3 from load_data import load_data, post_process, read_raw_image from monai.transforms import SaveImaged from monai.data import decollate_batch if __name__ == '__main__': parser = argpa...
6,412
49.496063
150
py
Viola-Unet
Viola-Unet-main/load_model.py
import os import torch import nibabel as nib from monai.inferers import sliding_window_inference from monai.transforms.utils import map_spatial_axes from monai.data import decollate_batch from viola_unet import ViolaUNet from monai.networks.nets import DynUNet wind_levels = [[0,100], [-15, 200],[-100, 1300]] spacin...
9,563
43.691589
130
py
Viola-Unet
Viola-Unet-main/load_data.py
# load data and pre-post precess import os from glob import glob from load_model import load_model, wind_levels, spacing import numpy as np from monai.transforms import * from monai.data import Dataset, DataLoader pre_process = Compose( [ LoadImaged(keys=["image"]), AddChanneld(keys=["image"]), ...
2,772
34.101266
124
py
Viola-Unet
Viola-Unet-main/viola_unet.py
# ViolaUNet is based on DynUNet # Copyright (c) MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable...
31,635
41.23765
122
py
BlockGCL
BlockGCL-master/dataloader.py
import os.path as osp import numpy as np import torch from sklearn.model_selection import train_test_split from torch_geometric.data import Data from torch_geometric.datasets import Planetoid, Amazon, Coauthor, WikiCS from torch_geometric.transforms import Compose, NormalizeFeatures, ToUndirected from ogb.nodeproppred...
5,008
37.236641
81
py
BlockGCL
BlockGCL-master/loss.py
import torch import torch.nn.functional as F def inv_dec_loss(h1, h2, lambd): N = h1.size(0) c = torch.mm(h1.T, h2) c1 = torch.mm(h1.T, h1) c2 = torch.mm(h2.T, h2) c = c / N c1 = c1 / N c2 = c2 / N loss_inv = -torch.diagonal(c).sum() iden = torch.eye(c.shape[0]).to(h1.device) ...
471
19.521739
53
py
BlockGCL
BlockGCL-master/utils.py
import os import random import numpy as np import torch import torch.nn.functional as F from torch_sparse import SparseTensor def set_random_seeds(random_seed=0): r"""Set the seed for generating random numbers.""" torch.manual_seed(random_seed) torch.cuda.manual_seed(random_seed) torch.cuda.manual_see...
658
27.652174
55
py
BlockGCL
BlockGCL-master/model.py
import torch import torch.nn as nn from torch_geometric.nn import BatchNorm, GCNConv, LayerNorm, SAGEConv, Sequential def get_activation(name='ReLU'): if name == 'ReLU': return nn.ReLU() elif name == "PReLU": return nn.PReLU() else: raise NotImplementedError("Acitivation {} not impl...
2,427
28.975309
106
py
BlockGCL
BlockGCL-master/logger.py
import functools import logging import os import sys import torch from typing import Optional from termcolor import colored __all__ = ["setup_logger", "get_logger"] # cache the opened file object, so that different calls to `setup_logger` # with the same file name can safely write to the same file. @functools.lru_c...
6,665
33.184615
89
py
BlockGCL
BlockGCL-master/eval.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader def test(embeds, data, num_classes, FLAGS, device="cpu"): return node_cls_downstream_task_eval( input_emb=embeds, data=data, num_classes=num_classes, lr=FLAGS.lr_cls, wd=FLAGS.wd_cls, ...
4,642
31.468531
109
py
BlockGCL
BlockGCL-master/train.py
import copy import os.path as osp import numpy as np import torch import torch.nn.functional as F from absl import app, flags from torch.optim import AdamW # custom modules from logger import setup_logger from utils import set_random_seeds, edgeidx2sparse from transforms import get_graph_drop_transform from model imp...
7,308
37.267016
122
py
BlockGCL
BlockGCL-master/transforms.py
import copy import torch from torch_geometric.utils.dropout import dropout_adj from torch_geometric.transforms import Compose class DropFeatures: r"""Drops node features with probability p.""" def __init__(self, p=None): assert 0. < p < 1., \ 'Dropout probability has to be between 0 and 1...
2,025
27.942857
83
py
RecSys_PyTorch
RecSys_PyTorch-master/main.py
# Import packages import os import torch import models from data.dataset import UIRTDataset from evaluation.evaluator import Evaluator from experiment.early_stop import EarlyStop from loggers import FileLogger, CSVLogger from utils.general import make_log_dir, set_random_seed from config import load_config """ C...
1,665
22.8
103
py
RecSys_PyTorch
RecSys_PyTorch-master/setup.py
from distutils.core import setup, Extension from Cython.Build import cythonize import numpy as np import os pyx_directories = ["evaluation/backend/cython"] cpp_dirs = ["evaluation/backend/cython/include"] pwd = os.getcwd() additional_dirs = [os.path.join(pwd, d) for d in cpp_dirs] for t_dir in pyx_directories: ...
911
25.823529
77
py
RecSys_PyTorch
RecSys_PyTorch-master/config.py
from typing import List, Tuple from dataclasses import dataclass, field from omegaconf import OmegaConf @dataclass class DatasetConfig: data_path:str='datasets/ml-100k/u.data' dataname:str='ml-1m' separator:str='\t' binarize_threshold:float=0.0 implicit:bool=True min_item_per_user:int=10 m...
1,804
27.203125
114
py
RecSys_PyTorch
RecSys_PyTorch-master/trainer/helper_func.py
import copy from time import time def fit_model(model, dataset, exp_config, evaluator, early_stop, loggers, run_n=-1): # initialize experiment early_stop.initialize() # train model fit_start = time() best_valid_score = model.fit(dataset, exp_config, evaluator, early_stop, loggers) train_time =...
379
30.666667
85
py
RecSys_PyTorch
RecSys_PyTorch-master/trainer/__init__.py
from .SingleParamRepeat import SingleParamRepeat
48
48
48
py
RecSys_PyTorch
RecSys_PyTorch-master/evaluation/evaluator.py
import time import numpy as np from typing import Iterable from collections import OrderedDict from .backend import eval_func_router, predict_topk_func from data.data_batcher import DataBatcher from utils.types import sparse_to_dict class Evaluator: def __init__(self, eval_input, eval_target, protocol, ks, eval_b...
1,696
29.854545
84
py
RecSys_PyTorch
RecSys_PyTorch-master/evaluation/__init__.py
from .evaluator import Evaluator
32
32
32
py
RecSys_PyTorch
RecSys_PyTorch-master/evaluation/backend/__init__.py
HOLDOUT_METRICS = ['Prec', 'Recall', 'NDCG'] LOO_METRICS = ['HR', 'NDCG'] try: from .cython.loo import compute_loo_metrics_cy from .cython.holdout import compute_holdout_metrics_cy from .cython.func import predict_topk_cy CYTHON_OK = True except: print('evaluation with python backend...') ...
846
28.206897
58
py
RecSys_PyTorch
RecSys_PyTorch-master/evaluation/backend/python/holdout.py
import math from collections import OrderedDict import numpy as np from utils.stats import Statistics from .. import HOLDOUT_METRICS # from evaluation.backend import HOLDOUT_METRICS # HOLDOUT_METRICS = ['Prec', 'Recall', 'NDCG'] def compute_holdout_metrics_py(pred, target, ks): score_cumulator = OrderedDict() ...
3,298
34.473118
98
py
RecSys_PyTorch
RecSys_PyTorch-master/evaluation/backend/python/loo.py
import math from collections import OrderedDict import numpy as np from utils.stats import Statistics from .. import LOO_METRICS # from evaluation.backend import LOO_METRICS # LOO_METRICS = ['HR', 'NDCG'] def compute_loo_metrics_py(pred, target, ks): score_cumulator = OrderedDict() for metric in LOO_METRICS:...
905
29.2
94
py
RecSys_PyTorch
RecSys_PyTorch-master/evaluation/backend/python/__init__.py
0
0
0
py
RecSys_PyTorch
RecSys_PyTorch-master/evaluation/backend/python/func.py
from time import time import numpy as np def predict_topk_py(scores, max_k): # top_k item index (not sorted) s = time() relevant_items_partition = (-scores).argpartition(max_k, 1)[:, 0:max_k] # top_k item score (not sorted) relevant_items_partition_original_value = np.take_along_axis(scores, r...
629
34
101
py
RecSys_PyTorch
RecSys_PyTorch-master/evaluation/backend/cython/holdout.py
import math from collections import OrderedDict import numpy as np from utils.stats import Statistics try: from .holdout_func import compute_holdout except: raise ImportError('Holdout pyx import error') from .. import HOLDOUT_METRICS # HOLDOUT_METRICS = ['Prec', 'Recall', 'NDCG'] def compute_holdout_metrics_...
1,030
34.551724
112
py
RecSys_PyTorch
RecSys_PyTorch-master/evaluation/backend/cython/loo.py
import math from collections import OrderedDict import numpy as np from utils.stats import Statistics try: from .loo_func import compute_loo except: raise ImportError('Cython loo import error') from .. import LOO_METRICS # from evaluation.backend import LOO_METRICS def compute_loo_metrics_cy(pred, target, k...
833
29.888889
84
py
RecSys_PyTorch
RecSys_PyTorch-master/evaluation/backend/cython/__init__.py
0
0
0
py
RecSys_PyTorch
RecSys_PyTorch-master/experiment/early_stop.py
class EarlyStop: def __init__(self, early_stop, early_stop_measure): self.endure = 0 self.early_stop = early_stop self.early_stop_measure = early_stop_measure self.best_epoch = None self.best_score = None def initialize(self): self.best_epoch = None self...
2,092
35.086207
93
py
RecSys_PyTorch
RecSys_PyTorch-master/experiment/hparam_search.py
import os import time import copy import optuna from experiment import fit_model from utils import ResultTable, set_random_seed from logger import Logger class GridSearch: def __init__(self, model_base, dataset, early_stop, config, device, seed=2020, num_parallel=1): self.model_base = model_base s...
11,595
34.033233
165
py
RecSys_PyTorch
RecSys_PyTorch-master/models/RP3b.py
""" Bibek Paudel et al., Updatable, accurate, diverse, and scalablerecommendations for interactive applications. TiiS 2017. https://www.zora.uzh.ch/id/eprint/131338/1/TiiS_2016.pdf Main model codes from https://github.com/MaurizioFD/RecSys2019_DeepLearning_Evaluation """ import torch import torch.nn.functional as F im...
4,686
36.496
130
py
RecSys_PyTorch
RecSys_PyTorch-master/models/PureSVD.py
import numpy as np import scipy.sparse as sp from sklearn.utils.extmath import randomized_svd import torch import torch.nn.functional as F from models.BaseModel import BaseModel class PureSVD(BaseModel): def __init__(self, dataset, hparams, device): super(PureSVD, self).__init__() self.num_users = ...
2,227
33.8125
100
py
RecSys_PyTorch
RecSys_PyTorch-master/models/ItemKNN.py
""" Jun Wang et al., Unifying user-based and item-based collaborative filtering approaches by similarity fusion. SIGIR 2006. http://web4.cs.ucl.ac.uk/staff/jun.wang/papers/2006-sigir06-unifycf.pdf """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import scipy.sparse as sp from tq...
6,781
36.677778
146
py
RecSys_PyTorch
RecSys_PyTorch-master/models/MultVAE.py
""" Dawen Liang et al., Variational Autoencoders for Collaborative Filtering. WWW 2018. https://arxiv.org/pdf/1802.05814 """ import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from .BaseModel import BaseModel from data.generators import MatrixGenerator class MultVAE(BaseModel): ...
5,994
37.429487
123
py
RecSys_PyTorch
RecSys_PyTorch-master/models/P3a.py
""" Colin Cooper et al., Random Walks in Recommender Systems: Exact Computation and Simulations. WWW 2014. http://wwwconference.org/proceedings/www2014/companion/p811.pdf Main model codes from https://github.com/MaurizioFD/RecSys2019_DeepLearning_Evaluation """ import torch import torch.nn.functional as F import numpy...
4,840
35.954198
130
py
RecSys_PyTorch
RecSys_PyTorch-master/models/CDAE.py
""" Yao Wu et al., Collaborative denoising auto-encoders for top-n recommender systems. WSDM 2016. https://alicezheng.org/papers/wsdm16-cdae.pdf """ from collections import OrderedDict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from .BaseModel import BaseModel from data.gene...
4,533
38.086207
142
py
RecSys_PyTorch
RecSys_PyTorch-master/models/DAE.py
""" Yao Wu et al., Collaborative denoising auto-encoders for top-n recommender systems. WSDM 2016. https://alicezheng.org/papers/wsdm16-cdae.pdf """ from collections import OrderedDict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from .BaseModel import BaseModel from data.gene...
4,313
36.513043
123
py
RecSys_PyTorch
RecSys_PyTorch-master/models/LightGCN.py
""" LightGCN: Simplifying and Powering Graph Convolution Network for Recommendation, Xiangnan He et al., SIGIR 2020. """ import os import math import time import numpy as np import scipy.sparse as sp import torch import torch.nn as nn import torch.nn.functional as F from .BaseModel import BaseModel from data.generat...
9,931
36.198502
109
py
RecSys_PyTorch
RecSys_PyTorch-master/models/NGCF.py
""" Neural Graph Collaborative Filtering, Xiang Wang et al., SIGIR 2019. [Official tensorflow]: https://github.com/xiangwang1223/neural_graph_collaborative_filtering [PyTorch reference]: https://github.com/huangtinglin/NGCF-PyTorch """ import os import math import time import numpy as np import scipy.sparse as sp impo...
10,926
37.748227
118
py
RecSys_PyTorch
RecSys_PyTorch-master/models/__init__.py
# # Non-eural from models.ItemKNN import ItemKNN from models.PureSVD import PureSVD from models.SLIMElastic import SLIM from models.P3a import P3a from models.RP3b import RP3b from models.EASE import EASE # # Neural from models.DAE import DAE from models.CDAE import CDAE from models.MF import MF from models.MultVAE im...
500
28.470588
100
py
RecSys_PyTorch
RecSys_PyTorch-master/models/MF.py
""" Steffen Rendle et al., BPR: Bayesian Personalized Ranking from Implicit Feedback. UAI 2009. https://arxiv.org/pdf/1205.2618 """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from .BaseModel import BaseModel from data.generators import PointwiseGenerator, PairwiseGenerator ...
5,277
38.38806
109
py