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 |
|---|---|---|---|---|---|---|
ReChorus | ReChorus-master/src/models/sequential/ComiRec.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" ComiRec
Reference:
"Controllable Multi-Interest Framework for Recommendation"
Cen et al., KDD'2020.
CMD example:
python main.py --model_name ComiRec --emb_size 64 --lr 1e-3 --l2 1e-6 --attn_size 8 --K 4 --add_pos 1 \
... | 3,848 | 39.946809 | 107 | py |
ReChorus | ReChorus-master/src/models/sequential/KDA.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" KDA
Reference:
"Toward Dynamic User Intention: Temporal Evolutionary Effects of Item Relations in Sequential Recommendation"
Chenyang Wang et al., TOIS'2021.
CMD example:
python main.py --model_name KDA --emb_size 64 --... | 15,388 | 49.621711 | 116 | py |
ReChorus | ReChorus-master/src/models/sequential/GRU4Rec.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" GRU4Rec
Reference:
"Session-based Recommendations with Recurrent Neural Networks"
Hidasi et al., ICLR'2016.
CMD example:
python main.py --model_name GRU4Rec --emb_size 64 --hidden_size 128 --lr 1e-3 --l2 1e-4 --history_... | 2,685 | 35.794521 | 110 | py |
ReChorus | ReChorus-master/src/models/sequential/TiSASRec.py | # -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" TiSASRec
Reference:
"Time Interval Aware Self-Attention for Sequential Recommendation"
Jiacheng Li et al., WSDM'2020.
CMD example:
python main.py --model_name TiSASRec --emb_size 64 --num_layers 1 --num_heads 1 --lr 1e-... | 8,550 | 41.755 | 107 | py |
ReChorus | ReChorus-master/src/utils/utils.py | # -*- coding: UTF-8 -*-
import os
import random
import logging
import torch
import datetime
import numpy as np
import pandas as pd
from typing import List, Dict, NoReturn, Any
def init_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cu... | 3,723 | 33.803738 | 117 | py |
ReChorus | ReChorus-master/src/utils/layers.py | # -*- coding: UTF-8 -*-
import torch
import torch.nn as nn
import numpy as np
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, n_heads, kq_same=False, bias=True):
super().__init__()
"""
It has projection layer for getting keys, queries and values. Followed by attention.
... | 3,225 | 36.08046 | 92 | py |
CMCL-2022 | CMCL-2022-master/main.py | import torch
from base_model import Transformer
import pandas as pd
from base_dataset import CreateDataset
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader
from tqdm import tqdm
from statistics import mean
from torchmetrics.functional import r2_score
import numpy as np
MAX_E... | 2,717 | 28.225806 | 94 | py |
CMCL-2022 | CMCL-2022-master/base_model.py |
from torch import nn
from transformers import AutoConfig, AutoModel
class Transformer(nn.Module):
def __init__(self, model, num_classes=1):
super().__init__()
self.name = model
config = AutoConfig.from_pretrained(self.name)
config.output_hidden_states = True
se... | 1,126 | 27.897436 | 109 | py |
CMCL-2022 | CMCL-2022-master/base_dataset.py | from torch.utils.data import Dataset
from transformers import AutoTokenizer
import torch
class CreateDataset(Dataset):
def __init__(self,data,labels,model):
super().__init__()
self.data = data
self.labels = labels
tokenizer = AutoTokenizer.from_pretrained(model)
self.encodin... | 723 | 44.25 | 150 | py |
CMCL-2022 | CMCL-2022-master/code/main.py | import pytorch_lightning as pl
from xlm_roberta import tfRegressor
import torch
from dataloader import TransduciveDataLoader
import pandas as pd
import numpy as np
langTexts = ['ZuCo1','ZuCo2','Provo','BSC','RSC','PAHEC','PoTeC','GECO-NL']
tf_name = 'xlm-roberta-base'
train_loc = 'data/training_data/train.csv'
val... | 1,246 | 27.340909 | 87 | py |
CMCL-2022 | CMCL-2022-master/code/dataloader.py | import pytorch_lightning as pl
import torch.utils.data as TorchData
import pandas as pd
from dataset import TransduciveDataset
from utils import getLangText,seperateHyphenToSentence
import numpy as np
class TransduciveDataLoader(pl.LightningDataModule):
def __init__(self,train_location,val_location,test_loc,langT... | 3,617 | 38.758242 | 99 | py |
CMCL-2022 | CMCL-2022-master/code/dataset.py | import torch
from torch.utils.data import Dataset
from transformers import AutoTokenizer
MAX_LEN = 128
class TransduciveDataset(Dataset):
def __init__(self,texts,labels,mode ='train',tf_name = 'xlm-roberta-base') -> None:
super(TransduciveDataset,self).__init__()
try:
assert len(texts)... | 1,563 | 41.27027 | 167 | py |
CMCL-2022 | CMCL-2022-master/code/xlm_roberta.py | import pytorch_lightning as pl
from transformers import AutoModel,AutoTokenizer
import torch
import numpy as np
class tfRegressor(pl.LightningModule):
def __init__(self,lr,tf_name):
super(tfRegressor,self).__init__()
self.fe = AutoModel.from_pretrained(tf_name)
self.lr = lr
self.lin... | 2,701 | 34.552632 | 63 | py |
CMCL-2022 | CMCL-2022-master/cmcl-shared-task-main/src/dataloader.py | import torch
import transformers
FEATURES_NAMES = ['FFDAvg', 'FFDStd', 'TRTAvg', 'TRTStd']
class EyeTrackingCSV(torch.utils.data.Dataset):
"""Tokenize sentences and load them into tensors. Assume dataframe has sentence_id."""
def __init__(self, df, mode = 'train',model_name='roberta-base'):
self.model_name =... | 3,140 | 34.292135 | 110 | py |
CMCL-2022 | CMCL-2022-master/cmcl-shared-task-main/src/model.py | import random
import numpy as np
import torch
import transformers
from tqdm import tqdm
import src.dataloader
device = torch.device('cuda:1')
class RobertaRegressionModel(torch.nn.Module):
def __init__(self, model_name='roberta-base'):
super(RobertaRegressionModel, self).__init__()
if 'roberta' in model_n... | 9,123 | 36.240816 | 104 | py |
CMCL-2022 | CMCL-2022-master/cmcl-shared-task-main/notebooks/RoBERTaRegression.py | #!/usr/bin/env python
# coding: utf-8
# # RoBERTa Regression
# In[1]:
import sys
sys.path.append('../')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tqdm
import torch
from collections import defaultdict, Counter
import random
import math
import pickle
import ... | 1,196 | 13.597561 | 57 | py |
CMCL-2022 | CMCL-2022-master/cmcl-shared-task-main/notebooks/ProvoProcess.py | #!/usr/bin/env python
# coding: utf-8
# # Process Provo Corpus
# In[1]:
import sys
sys.path.append('../')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tqdm
import torch
from collections import defaultdict, Counter
import random
import math
import pickle
get_i... | 2,710 | 21.591667 | 146 | py |
CMCL-2022 | CMCL-2022-master/cmcl-shared-task-main/notebooks/InitialExplore.py | #!/usr/bin/env python
# coding: utf-8
# # Some initial exploration
# In[1]:
import sys
sys.path.append('../')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tqdm
import torch
from collections import defaultdict, Counter
import random
import math
import pickle
g... | 1,094 | 16.380952 | 79 | py |
CMCL-2022 | CMCL-2022-master/cmcl-shared-task-main/notebooks/MedianBaseline.py | #!/usr/bin/env python
# coding: utf-8
# # Median Baseline
# In[1]:
import sys
sys.path.append('../')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tqdm
import torch
from collections import defaultdict, Counter
import random
import math
import pickle
import stri... | 2,091 | 17.678571 | 73 | py |
CMCL-2022 | CMCL-2022-master/cmcl-shared-task-main/notebooks/RobertaRegression.py | # %% [markdown]
# # RoBERTa Regression
# %%
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tqdm
import torch
from collections import defaultdict, Counter
import random
import math
import pickle
import os
import src.eval_metric
import src.model
import sr... | 914 | 15.339286 | 60 | py |
RESPECT | RESPECT-main/reinforce_baselines.py | import torch
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from scipy.stats import ttest_rel
import copy
from train import rollout, get_inner_model
class Baseline(object):
def wrap_dataset(self, dataset):
return dataset
def unwrap_batch(self, batch):
return ... | 8,641 | 32.890196 | 121 | py |
RESPECT | RESPECT-main/run.py | #!/usr/bin/env python
import os
import json
import pprint as pp
import torch
import torch.optim as optim
from tensorboard_logger import Logger as TbLogger
from nets.critic_network import CriticNetwork
from options import get_options
from train import train_epoch, validate, get_inner_model
#from train_single import t... | 7,073 | 36.231579 | 137 | py |
RESPECT | RESPECT-main/train_model_run.py | import os
import time
from tqdm import tqdm
import torch
import math
from torch.utils.data import DataLoader
from torch.nn import DataParallel
from nets.attention_model import set_decode_type
from utils.log_utils import log_values
from utils import move_to
import warnings
def get_inner_model(model):
return mode... | 11,203 | 43.995984 | 243 | py |
RESPECT | RESPECT-main/options.py | import os
import time
import argparse
import torch
def get_options(args=None):
parser = argparse.ArgumentParser(
description="Attention based model for solving the Travelling Salesman Problem with Reinforcement Learning")
# Data
parser.add_argument('--problem', default='toposort', help="The probl... | 6,946 | 69.887755 | 134 | py |
RESPECT | RESPECT-main/reinforce_baselines_single.py | import torch
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from scipy.stats import ttest_rel
import copy
from train import rollout, get_inner_model
class Baseline(object):
def wrap_dataset(self, dataset):
return dataset
def unwrap_batch(self, batch):
return ... | 8,641 | 32.890196 | 121 | py |
RESPECT | RESPECT-main/train.py | import os
import time
from tqdm import tqdm
import torch
import math
from torch.utils.data import DataLoader
from torch.nn import DataParallel
from nets.attention_model import set_decode_type
from utils.log_utils import log_values
from utils import move_to
import warnings
def get_inner_model(model):
return mode... | 12,296 | 45.579545 | 295 | py |
RESPECT | RESPECT-main/dataset/dataset_generator.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
#from problems.toposort.state_toposort import StateTopoSort
#from utils.beam_search import beam_search
#from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check, graph_sorting_DAG
from collections imp... | 22,823 | 67.954683 | 229 | py |
RESPECT | RESPECT-main/nets/pointer_network_singleTraining.py | import torch
import torch.nn as nn
from torch.autograd import Variable
import math
import numpy as np
from torch.nn import TransformerEncoder, TransformerEncoderLayer
from utils import move_to
class Encoder(nn.Module):
"""Maps a graph represented as an input sequence
to a hidden vector"""
def __init__(se... | 16,623 | 40.25062 | 198 | py |
RESPECT | RESPECT-main/nets/pointer_network.py | import torch
import torch.nn as nn
from torch.autograd import Variable
import math
import numpy as np
from torch.nn import TransformerEncoder, TransformerEncoderLayer
from utils import move_to
class Encoder(nn.Module):
"""Maps a graph represented as an input sequence
to a hidden vector"""
def __init__(se... | 16,623 | 40.25062 | 198 | py |
RESPECT | RESPECT-main/nets/pointer_network_originalbatch.py | import torch
import torch.nn as nn
from torch.autograd import Variable
import math
import numpy as np
from torch.nn import TransformerEncoder, TransformerEncoderLayer
from utils import move_to
class Encoder(nn.Module):
"""Maps a graph represented as an input sequence
to a hidden vector"""
def __init__(se... | 16,271 | 40.510204 | 198 | py |
RESPECT | RESPECT-main/nets/pointer_network_model_run.py | import torch
import torch.nn as nn
from torch.autograd import Variable
import math
import numpy as np
from torch.nn import TransformerEncoder, TransformerEncoderLayer
from utils import move_to
class Encoder(nn.Module):
"""Maps a graph represented as an input sequence
to a hidden vector"""
def __init__(se... | 16,348 | 40.600509 | 198 | py |
RESPECT | RESPECT-main/nets/attention_model.py | import torch
from torch import nn
from torch.utils.checkpoint import checkpoint
import math
from typing import NamedTuple
from utils.tensor_functions import compute_in_batches
from nets.graph_encoder import GraphAttentionEncoder
from torch.nn import DataParallel
from utils.beam_search import CachedLookup
from utils.fu... | 22,485 | 42.49323 | 122 | py |
RESPECT | RESPECT-main/nets/graph_encoder.py | import torch
import numpy as np
from torch import nn
import math
class SkipConnection(nn.Module):
def __init__(self, module):
super(SkipConnection, self).__init__()
self.module = module
def forward(self, input):
return input + self.module(input)
class MultiHeadAttention(nn.Module):... | 6,927 | 32.148325 | 117 | py |
RESPECT | RESPECT-main/nets/critic_network.py | from torch import nn
from nets.graph_encoder import GraphAttentionEncoder
class CriticNetwork(nn.Module):
def __init__(
self,
input_dim,
embedding_dim,
hidden_dim,
n_layers,
encoder_normalization
):
super(CriticNetwork, self).__init__()
self.hi... | 965 | 22.560976 | 58 | py |
RESPECT | RESPECT-main/nets/pointer_network_dataset_pick3.py | import torch
import torch.nn as nn
from torch.autograd import Variable
import math
import numpy as np
from torch.nn import TransformerEncoder, TransformerEncoderLayer
from utils import move_to
class Encoder(nn.Module):
"""Maps a graph represented as an input sequence
to a hidden vector"""
def __init__(se... | 16,562 | 40.304239 | 201 | py |
RESPECT | RESPECT-main/problems/pctsp/state_pctsp.py | import torch
from typing import NamedTuple
from utils.boolmask import mask_long2bool, mask_long_scatter
import torch.nn.functional as F
bypass = super
class StatePCTSP(NamedTuple):
# Fixed input
coords: torch.Tensor # Depot + loc
expected_prize: torch.Tensor
real_prize: torch.Tensor
penalty: torc... | 7,770 | 43.405714 | 119 | py |
RESPECT | RESPECT-main/problems/pctsp/problem_pctsp.py | from torch.utils.data import Dataset
import torch
import os
import pickle
from problems.pctsp.state_pctsp import StatePCTSP
from utils.beam_search import beam_search
class PCTSP(object):
NAME = 'pctsp' # Prize Collecting TSP, without depot, with penalties
@staticmethod
def _get_costs(dataset, pi, stoch... | 7,293 | 38.215054 | 120 | py |
RESPECT | RESPECT-main/problems/tsp/problem_tsp.py | from torch.utils.data import Dataset
import torch,random
import os
import pickle
from problems.tsp.state_tsp import StateTSP
from utils.beam_search import beam_search
class TSP(object):
NAME = 'tsp'
@staticmethod
def get_costs(dataset, pi):
# Check that tours are valid, i.e. contain 0 to n -1
... | 3,449 | 34.9375 | 135 | py |
RESPECT | RESPECT-main/problems/tsp/tsp_baseline.py | import argparse
import numpy as np
import os
import time
from datetime import timedelta
from scipy.spatial import distance_matrix
from utils import run_all_in_pool
from utils.data_utils import check_extension, load_dataset, save_dataset
from subprocess import check_call, check_output, CalledProcessError
from problems.v... | 17,311 | 37.471111 | 120 | py |
RESPECT | RESPECT-main/problems/tsp/state_tsp.py | import torch
from typing import NamedTuple
from utils.boolmask import mask_long2bool, mask_long_scatter
bypass = super
class StateTSP(NamedTuple):
# Fixed input
loc: torch.Tensor
dist: torch.Tensor
# If this state contains multiple copies (i.e. beam search) for the same instance, then for memory effi... | 5,705 | 39.468085 | 121 | py |
RESPECT | RESPECT-main/problems/vrp/problem_vrp.py | from torch.utils.data import Dataset
import torch
import os
import pickle
from problems.vrp.state_cvrp import StateCVRP
from problems.vrp.state_sdvrp import StateSDVRP
from utils.beam_search import beam_search
class CVRP(object):
NAME = 'cvrp' # Capacitated Vehicle Routing Problem
VEHICLE_CAPACITY = 1.0 ... | 7,569 | 35.570048 | 117 | py |
RESPECT | RESPECT-main/problems/vrp/state_sdvrp.py | import torch
from typing import NamedTuple
bypass = super
class StateSDVRP(NamedTuple):
# Fixed input
coords: torch.Tensor
demand: torch.Tensor
# If this state contains multiple copies (i.e. beam search) for the same instance, then for memory efficiency
# the coords and demands tensors are not ke... | 4,979 | 39.487805 | 119 | py |
RESPECT | RESPECT-main/problems/vrp/state_cvrp.py | import torch
from typing import NamedTuple
from utils.boolmask import mask_long2bool, mask_long_scatter
bypass = super
class StateCVRP(NamedTuple):
# Fixed input
coords: torch.Tensor # Depot + loc
demand: torch.Tensor
# If this state contains multiple copies (i.e. beam search) for the same instance,... | 6,844 | 40.737805 | 118 | py |
RESPECT | RESPECT-main/problems/toposort/state_toposort.py | import torch
from typing import NamedTuple
from utils.boolmask import mask_long2bool, mask_long_scatter
bypass = super
class StateTopoSort(NamedTuple):
# Fixed input
loc: torch.Tensor
dist: torch.Tensor
# If this state contains multiple copies (i.e. beam search) for the same instance, then for memory... | 5,725 | 39.609929 | 121 | py |
RESPECT | RESPECT-main/problems/toposort/problem_toposort_xySorting.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
from problems.toposort.state_toposort import StateTopoSort
from utils.beam_search import beam_search
from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check
import networkx as nx
import numpy as np
... | 7,376 | 45.396226 | 192 | py |
RESPECT | RESPECT-main/problems/toposort/problem_toposort_tmp.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
from problems.toposort.state_toposort import StateTopoSort
from utils.beam_search import beam_search
from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check
import networkx as nx
import numpy as np
... | 9,242 | 46.891192 | 224 | py |
RESPECT | RESPECT-main/problems/toposort/problem_toposort_singleTraining_reversed_label.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
from problems.toposort.state_toposort import StateTopoSort
from utils.beam_search import beam_search
#from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check
from utils import smart_sort
import netwo... | 11,131 | 49.144144 | 224 | py |
RESPECT | RESPECT-main/problems/toposort/problem_toposort_model_run.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
from problems.toposort.state_toposort import StateTopoSort
from utils.beam_search import beam_search
#from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check
from utils import smart_sort
import netwo... | 10,826 | 48.438356 | 224 | py |
RESPECT | RESPECT-main/problems/toposort/problem_toposort_multipleTraining_2.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
from problems.toposort.state_toposort import StateTopoSort
from utils.beam_search import beam_search
#from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check
from utils import smart_sort
import netwo... | 11,535 | 48.939394 | 228 | py |
RESPECT | RESPECT-main/problems/toposort/dataset_generator.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
#from problems.toposort.state_toposort import StateTopoSort
#from utils.beam_search import beam_search
#from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check, graph_sorting_DAG
from collections imp... | 5,644 | 38.753521 | 131 | py |
RESPECT | RESPECT-main/problems/toposort/problem_toposort_1.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
from problems.toposort.state_toposort import StateTopoSort
from utils.beam_search import beam_search
from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check, graph_sorting_DAG
import networkx as nx
i... | 8,767 | 44.430052 | 192 | py |
RESPECT | RESPECT-main/problems/toposort/problem_toposort_multipleTraining.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
from problems.toposort.state_toposort import StateTopoSort
from utils.beam_search import beam_search
#from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check
from utils import smart_sort
import netwo... | 12,543 | 51.485356 | 260 | py |
RESPECT | RESPECT-main/problems/toposort/problem_toposort_temporary_idea.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
from problems.toposort.state_toposort import StateTopoSort
from utils.beam_search import beam_search
from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check
import networkx as nx
import numpy as np
... | 9,252 | 46.943005 | 224 | py |
RESPECT | RESPECT-main/problems/toposort/problem_toposort_2.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
from problems.toposort.state_toposort import StateTopoSort
from utils.beam_search import beam_search
from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check
import networkx as nx
import numpy as np
... | 9,254 | 46.953368 | 224 | py |
RESPECT | RESPECT-main/problems/toposort/problem_toposort_singleTraining.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
from problems.toposort.state_toposort import StateTopoSort
from utils.beam_search import beam_search
#from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check
from utils import smart_sort
import netwo... | 11,190 | 49.183857 | 224 | py |
RESPECT | RESPECT-main/problems/toposort/problem_toposort_newEmbedding.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
from problems.toposort.state_toposort import StateTopoSort
from utils.beam_search import beam_search
from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check, graph_sorting_DAG
from collections import... | 11,423 | 45.064516 | 192 | py |
RESPECT | RESPECT-main/problems/toposort/problem_toposort_multipleTraining_1.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
from problems.toposort.state_toposort import StateTopoSort
from utils.beam_search import beam_search
#from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check
from utils import smart_sort
import netwo... | 10,873 | 47.328889 | 224 | py |
RESPECT | RESPECT-main/problems/toposort/problem_toposort.py | from torch.utils.data import Dataset
import torch, random
import os
import pickle
from problems.toposort.state_toposort import StateTopoSort
from utils.beam_search import beam_search
#from utils import orderCheck, deep_sort_x, level_sorting, level_sorting_xy_pairs, order_check
from utils import smart_sort
import netwo... | 11,011 | 48.160714 | 224 | py |
RESPECT | RESPECT-main/problems/op/op_baseline.py | import argparse
import os
import numpy as np
from utils import run_all_in_pool
from utils.data_utils import check_extension, load_dataset, save_dataset
from subprocess import check_call, check_output
import tempfile
import time
from datetime import timedelta
from problems.op.opga.opevo import run_alg as run_opga_alg
fr... | 16,891 | 41.764557 | 118 | py |
RESPECT | RESPECT-main/problems/op/problem_op.py | from torch.utils.data import Dataset
import torch
import os
import pickle
from problems.op.state_op import StateOP
from utils.beam_search import beam_search
class OP(object):
NAME = 'op' # Orienteering problem
@staticmethod
def get_costs(dataset, pi):
if pi.size(-1) == 1: # In case all tours d... | 4,934 | 33.51049 | 106 | py |
RESPECT | RESPECT-main/problems/op/tsiligirides.py | import torch
from problems.op.state_op import StateOP
def op_tsiligirides(batch, sample=False, power=4.0):
state = StateOP.initialize(batch)
all_a = []
while not state.all_finished():
# Compute scores
mask = state.get_mask()
p = (
(mask[..., 1:] == 0).float() *
... | 1,672 | 37.906977 | 108 | py |
RESPECT | RESPECT-main/problems/op/state_op.py | import torch
from typing import NamedTuple
from utils.boolmask import mask_long2bool, mask_long_scatter
import torch.nn.functional as F
bypass = super
class StateOP(NamedTuple):
# Fixed input
coords: torch.Tensor # Depot + loc
prize: torch.Tensor
# Max length is not a single value, but one for each n... | 7,431 | 43.238095 | 118 | py |
RESPECT | RESPECT-main/utils/tensor_functions.py | import torch
def compute_in_batches(f, calc_batch_size, *args, n=None):
"""
Computes memory heavy function f(*args) in batches
:param n: the total number of elements, optional if it cannot be determined as args[0].size(0)
:param f: The function that is computed, should take only tensors as arguments a... | 1,608 | 44.971429 | 120 | py |
RESPECT | RESPECT-main/utils/monkey_patch.py | import torch
from itertools import chain
from collections import defaultdict, Iterable
from copy import deepcopy
def load_state_dict(self, state_dict):
"""Loads the optimizer state.
Arguments:
state_dict (dict): optimizer state. Should be an object returned
from a call to :meth:`state_dict... | 2,734 | 38.071429 | 90 | py |
RESPECT | RESPECT-main/utils/functions.py | import warnings
import torch
import numpy as np
import os
import json
from tqdm import tqdm
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import Pool
import torch.nn.functional as F
import networkx as nx
import random
def load_problem(name):
from problems import TSP, CVRP, SDVRP, OP, ... | 21,760 | 33.486529 | 160 | py |
RESPECT | RESPECT-main/utils/boolmask.py | import torch
import torch.nn.functional as F
def _pad_mask(mask):
# By taking -size % 8, we get 0 if exactly divisible by 8
# and required padding otherwise (i.e. -1 % 8 = 7 pad)
pad = -mask.size(-1) % 8
if pad != 0:
mask = F.pad(mask, [0, pad])
return mask, mask.size(-1) // 8
def _mask_... | 2,809 | 37.493151 | 131 | py |
RESPECT | RESPECT-main/utils/lexsort.py | import torch
import numpy as np
def torch_lexsort(keys, dim=-1):
if keys[0].is_cuda:
return _torch_lexsort_cuda(keys, dim)
else:
# Use numpy lex sort
return torch.from_numpy(np.lexsort([k.numpy() for k in keys], axis=dim))
def _torch_lexsort_cuda(keys, dim=-1):
"""
Function c... | 2,382 | 41.553571 | 127 | py |
RESPECT | RESPECT-main/utils/beam_search.py | import time
import torch
from typing import NamedTuple
from utils.lexsort import torch_lexsort
def beam_search(*args, **kwargs):
beams, final_state = _beam_search(*args, **kwargs)
return get_beam_search_results(beams, final_state)
def get_beam_search_results(beams, final_state):
beam = beams[-1] # Fina... | 8,521 | 36.875556 | 117 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/moon_data_exp.py | """
Two moons experiment for visualization
"""
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from tqdm import tqdm
from ssl_lib.a... | 8,998 | 37.788793 | 123 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/train_val_test.py | import logging
import numpy, random, time
import torch
import torch.nn.functional as F
import torch.optim as optim
from ssl_lib.algs.builder import gen_ssl_alg
from ssl_lib.algs import utils as alg_utils
from ssl_lib.models import utils as model_utils
from ssl_lib.consistency.builder import gen_consistency
from ssl_li... | 9,950 | 35.054348 | 132 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/train_test.py | import logging
import numpy, random, time, json
import torch
import torch.nn.functional as F
import torch.optim as optim
from ssl_lib.algs.builder import gen_ssl_alg
from ssl_lib.algs import utils as alg_utils
from ssl_lib.models import utils as model_utils
from ssl_lib.consistency.builder import gen_consistency
from ... | 10,043 | 35.129496 | 121 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/models/resnet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .utils import leaky_relu, conv3x3, BatchNorm2d, param_init, BaseModel
class _Residual(nn.Module):
def __init__(self, input_channels, output_channels, stride=1, activate_before_residual=False):
super().__init__()
layer = []
... | 2,568 | 31.1125 | 111 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/models/utils.py | import math
import torch.nn as nn
import torch.nn.functional as F
class BaseModel(nn.Module):
def forward(self, x):
f = self.feature_extractor(x)
f = f.mean((2, 3))
return self.classifier(f)
def logits_with_feature(self, x):
f = self.feature_extractor(x)
c = self.class... | 2,915 | 30.354839 | 93 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/models/cnn13.py | import torch.nn as nn
from .utils import leaky_relu, conv3x3, BatchNorm2d, BaseModel
class CNN13(BaseModel):
"""
13-layer CNN
Parameters
--------
num_classes: int
number of classes
filters: int
number of filters
"""
def __init__(self, num_classes, filters, *args, **kwa... | 1,778 | 30.210526 | 62 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/models/shakenet.py | import itertools
import torch
import torch.nn as nn
import torch.nn.functional as F
from .utils import conv3x3, BatchNorm2d, param_init, BaseModel
class _ShakeShake(nn.Module):
def __init__(self, branch1, branch2):
super().__init__()
self.branch1 = branch1
self.branch2 = branch2
def f... | 3,250 | 28.026786 | 107 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/param_scheduler/scheduler.py | import torch
import warnings
import math
import torch.optim as optim
def exp_warmup(base_value, max_warmup_iter, cur_step):
"""exponential warmup proposed in mean teacher
calcurate
base_value * exp(-5(1 - t)^2), t = cur_step / max_warmup_iter
Parameters
-----
base_value: float
maximu... | 1,758 | 24.128571 | 132 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/consistency/mean_squared.py | import torch.nn as nn
import torch.nn.functional as F
def mean_squared(y, target, mask=None):
y = y.softmax(1)
loss = F.mse_loss(y, target, reduction="none").mean(1)
if mask is not None:
loss = mask * loss
return loss.mean()
class MeanSquared(nn.Module):
def forward(self, y, target, mask=N... | 396 | 29.538462 | 61 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/consistency/cross_entropy.py | import torch.nn as nn
import torch.nn.functional as F
def cross_entropy(y, target, mask=None):
if target.ndim == 1: # for hard label
loss = F.cross_entropy(y, target, reduction="none")
else:
loss = -(target * F.log_softmax(y, 1)).sum(1)
if mask is not None:
loss = mask * loss
re... | 486 | 29.4375 | 61 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/datasets/utils.py | import os
import numpy as np
import torch
from torch.utils.data import Sampler
from torchvision.datasets import SVHN, CIFAR10, CIFAR100, STL10
class InfiniteSampler(Sampler):
""" sampling without replacement """
def __init__(self, num_data, num_sample):
epochs = num_sample // num_data + 1
self... | 4,664 | 36.620968 | 105 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/datasets/builder.py | import os
import numpy as np
from torch.utils.data import DataLoader
from torchvision import transforms
from . import utils
from . import dataset_class
from ..augmentation.builder import gen_strong_augmentation, gen_weak_augmentation
from ..augmentation.augmentation_pool import numpy_batch_gcn, ZCA, GCN
def __val_la... | 7,546 | 33.619266 | 105 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/datasets/dataset_class.py | import torch
class LabeledDataset:
"""
For labeled dataset
"""
def __init__(self, dataset, transform=None):
self.dataset = dataset
self.transform = transform
def __getitem__(self, idx):
image = torch.from_numpy(self.dataset["images"][idx]).float()
image = image.per... | 1,422 | 29.276596 | 82 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/augmentation/augmentation_pool.py | import random
import torch
import torch.nn.functional as F
import numpy as np
from PIL import ImageOps, ImageEnhance, ImageFilter, Image
"""
For PIL.Image
"""
def autocontrast(x, *args, **kwargs):
return ImageOps.autocontrast(x.convert("RGB")).convert("RGBA")
def brightness(x, level, magnitude=10, max_level=1... | 7,397 | 27.344828 | 98 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/augmentation/augmentation_class.py | import torch
import torchvision.transforms as tt
from . import augmentation_pool as aug_pool
from .rand_augment import RandAugment
class ReduceChannelwithNormalize:
""" Reduce alpha channel of RGBA """
def __init__(self, mean, scale, zca):
self.mean = mean
self.scale = scale
self.zca ... | 2,986 | 25.433628 | 102 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/algs/consistency.py | import torch
from .utils import sharpening, tempereture_softmax
class ConsistencyRegularization:
"""
Basis Consistency Regularization
Parameters
--------
consistency: str
consistency objective name
threshold: float
threshold to make mask
sharpen: float
sharpening te... | 1,674 | 26.916667 | 97 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/algs/utils.py | import torch
import torch.nn as nn
def make_pseudo_label(logits, threshold):
max_value, hard_label = logits.softmax(1).max(1)
mask = (max_value >= threshold)
return hard_label, mask
def sharpening(soft_labels, temp):
soft_labels = soft_labels.pow(temp)
return soft_labels / soft_labels.abs().sum(... | 1,736 | 27.47541 | 84 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/algs/vat.py | import torch
from .consistency import ConsistencyRegularization
class VAT(ConsistencyRegularization):
"""
Virtual Adversarial Training https://arxiv.org/abs/1704.03976
Parameters
--------
consistency: str
consistency objective name
threshold: float
threshold to make mask
sh... | 2,419 | 26.5 | 108 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/algs/pseudo_label.py | import torch
import torch.nn.functional as F
from .consistency import ConsistencyRegularization
from ..consistency.cross_entropy import CrossEntropy
from .utils import make_pseudo_label, sharpening
class PseudoLabel(ConsistencyRegularization):
"""
PseudoLabel
Parameters
--------
consistency: str
... | 1,136 | 25.44186 | 97 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/algs/ict.py | import torch
from .consistency import ConsistencyRegularization
from .utils import mixup
class ICT(ConsistencyRegularization):
"""
Interpolation Consistency Training https://arxiv.org/abs/1903.03825
Parameters
--------
consistency: str
consistency objective name
threshold: float
... | 1,377 | 24.054545 | 109 | py |
rulstm | rulstm-master/FEATEXT/extract_example_obj.py | import torch
import numpy as np
from torch import nn
from pretrainedmodels import bninception
from torchvision import transforms
from glob import glob
from PIL import Image
import lmdb
from tqdm import tqdm
from os.path import basename
env = lmdb.open('features/obj', map_size=1099511627776)
video_name = 'P01_01_frame_... | 681 | 26.28 | 80 | py |
rulstm | rulstm-master/FEATEXT/extract_example_rgb.py | import torch
from torch import nn
from pretrainedmodels import bninception
from torchvision import transforms
from glob import glob
from PIL import Image
import lmdb
from tqdm import tqdm
from os.path import basename
from argparse import ArgumentParser
env = lmdb.open('features/rgb', map_size=1099511627776)
device = ... | 1,291 | 26.489362 | 83 | py |
rulstm | rulstm-master/FEATEXT/extract_example_flow.py | import torch
from torch import nn
from pretrainedmodels import bninception
from torchvision import transforms
from glob import glob
from PIL import Image
import lmdb
from tqdm import tqdm
from os.path import basename
from argparse import ArgumentParser
env = lmdb.open('features/flow', map_size=1099511627776)
device =... | 1,787 | 29.827586 | 85 | py |
rulstm | rulstm-master/RULSTM/main.py | """Main training/test program for RULSTM"""
from argparse import ArgumentParser
from dataset import SequenceDataset
from os.path import join
from models import RULSTM, RULSTMFusion
import torch
from torch.utils.data import DataLoader
from torch.nn import functional as F
from utils import topk_accuracy, ValueMeter, topk... | 30,172 | 46.219092 | 208 | py |
rulstm | rulstm-master/RULSTM/dataset.py | """ Implements a dataset object which allows to read representations from LMDB datasets in a multi-modal fashion
The dataset can sample frames for both the anticipation and early recognition tasks."""
import numpy as np
import lmdb
from tqdm import tqdm
from torch.utils import data
import pandas as pd
def read_repres... | 9,400 | 43.554502 | 134 | py |
rulstm | rulstm-master/RULSTM/models.py | from torch import nn
import torch
from torch.nn.init import normal, constant
import numpy as np
from torch.nn import functional as F
class OpenLSTM(nn.Module):
""""An LSTM implementation that returns the intermediate hidden and cell states.
The original implementation of PyTorch only returns the last cell vect... | 6,687 | 40.540373 | 131 | py |
rulstm | rulstm-master/FasterRCNN/tools/detect_video.py | #!/usr/bin/env python
# Copyright (c) 2017-present, Facebook, Inc.
#
# 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 a... | 4,411 | 29.013605 | 78 | py |
chase | chase-master/python/src/example.py | # MLP for Pima Indians Dataset with grid search via sklearn
#import tensorflow as tf
from sklearn.cross_validation import train_test_split, cross_val_predict, cross_val_score
from sklearn.metrics import accuracy_score
import os
os.environ['THEANO_FLAGS']="device=cpu,openmp=True"
import datetime
from keras.models impor... | 3,449 | 34.204082 | 92 | py |
chase | chase-master/python/src/ml/classifier_dnn.py | import os
from numpy.random import seed
seed(1)
os.environ['PYTHONHASHSEED'] = '0'
os.environ['THEANO_FLAGS'] = "floatX=float64,device=cpu,openmp=True"
# os.environ['THEANO_FLAGS']="openmp=True"
os.environ['OMP_NUM_THREADS'] = '16'
import theano
theano.config.openmp = True
# import tensorflow as tf
# tf.set_random... | 23,117 | 39.629174 | 137 | py |
chase | chase-master/python/src/ml/multiclassifier_dnn.py | import numpy
import pandas
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.preprocessing import LabelEnco... | 1,381 | 31.139535 | 89 | py |
chase | chase-master/python/src/ml/dnn_model_creator.py | from keras.engine import Model
from keras.layers import Dropout, GlobalMaxPooling1D, Dense, Conv1D, MaxPooling1D, Bidirectional, Concatenate, Flatten, \
GRU
from keras.layers import LSTM
from keras import backend as K
from keras.models import Sequential
from keras.regularizers import L1L2
def create_regularizer(... | 28,293 | 42.866667 | 158 | py |
nussl | nussl-master/nussl/core/migration.py | import torch
import json
from .. import __version__, STFTParams
from ..separation.base import SeparationException
from ..datasets import transforms as tfm
from ..evaluation import BSSEvalV4, BSSEvalScale
class SafeModelLoader(object):
"""
Loads a nussl model and populates the metadata with defaults if
""... | 5,681 | 32.423529 | 86 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.