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
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/__init__.py
0
0
0
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/__init__.py
from problems.tsp.problem_tsp import TSP from problems.vrp.problem_vrp import CVRP, SDVRP from problems.op.problem_op import OP from problems.pctsp.problem_pctsp import PCTSPDet, PCTSPStoch from problems.toposort.problem_toposort import TopoSort, TopoSortDataset
263
43
72
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/pctsp/pctsp_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 re import time from datetime import timedelta import random from scipy.spatial import distance_matrix from .sales...
20,018
42.901316
120
py
RESPECT
RESPECT-main/problems/pctsp/pctsp_ortools.py
#!/usr/bin/env python # This Python file uses the following encoding: utf-8 # Copyright 2015 Tin Arm Engineering AB # Copyright 2018 Google LLC # 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 #...
8,401
33.576132
106
py
RESPECT
RESPECT-main/problems/pctsp/__init__.py
0
0
0
py
RESPECT
RESPECT-main/problems/pctsp/pctsp_gurobi.py
#!/usr/bin/python # Copyright 2017, Gurobi Optimization, Inc. # Solve a traveling salesman problem on a set of # points using lazy constraints. The base MIP model only includes # 'degree-2' constraints, requiring each node to have exactly # two incident edges. Solutions to this model may contain subtours - # tours...
4,796
37.685484
117
py
RESPECT
RESPECT-main/problems/pctsp/salesman/__init__.py
0
0
0
py
RESPECT
RESPECT-main/problems/pctsp/salesman/pctsp/__main__.py
# from qextractor.application import main # main()
50
24.5
41
py
RESPECT
RESPECT-main/problems/pctsp/salesman/pctsp/application.py
# module application.py # # Copyright (c) 2015 Rafael Reis # """ application module - Main module that solves the Prize Collecting Travelling Salesman Problem """ from pctsp.model.pctsp import * from pctsp.model import solution from pctsp.algo.genius import genius from pctsp.algo import ilocal_search as ils from pkg_...
1,467
23.065574
93
py
RESPECT
RESPECT-main/problems/pctsp/salesman/pctsp/__init__.py
# package qextractor # # Copyright (c) 2015 Rafael Reis # """ Package qextractor - Packages for building and evaluating a machine learning model to tackle the Quotation Extractor Task """ __version__="1.0" __author__ = "Rafael Reis <rafael2reis@gmail.com>"
257
22.454545
76
py
RESPECT
RESPECT-main/problems/pctsp/salesman/pctsp/model/solution.py
# module solution.py # # Copyright (c) 2018 Rafael Reis # """ solution module - Implements Solution, a class that describes a solution for the problem. """ __version__="1.0" import numpy as np import copy import sys from random import shuffle def random(pctsp, start_size): s = Solution(pctsp) length = len(pc...
4,987
29.230303
118
py
RESPECT
RESPECT-main/problems/pctsp/salesman/pctsp/model/pctsp.py
# module pctsp.py # # Copyright (c) 2018 Rafael Reis # """ pctsp module - Implements Pctsp, a class that describes an instance of the problem.. """ __version__="1.0" import numpy as np import re class Pctsp(object): """ Attributes: c (:obj:`list` of :obj:`list`): Costs from i to j p (:obj:`list...
1,051
23.465116
84
py
RESPECT
RESPECT-main/problems/pctsp/salesman/pctsp/model/__init__.py
# package model # # Copyright (c) 2018 Rafael Reis # """ Package model - Models of Prize Collecting Travelling Salesman Problem """ __version__="1.0" __author__ = "Rafael Reis <rafael2reis@gmail.com>"
202
17.454545
70
py
RESPECT
RESPECT-main/problems/pctsp/salesman/pctsp/model/tests/__init__.py
0
0
0
py
RESPECT
RESPECT-main/problems/pctsp/salesman/pctsp/model/tests/test_solution.py
# python -m pctsp.model.tests.test_solution import unittest from pctsp.model import solution from pctsp.model import pctsp import numpy as np class TestTrain(unittest.TestCase): def setUp(self): self.p = pctsp.Pctsp() self.p.prize = np.array([0, 4, 8, 3]) self.p.penal = np.array([1000, 7, ...
1,668
26.360656
88
py
RESPECT
RESPECT-main/problems/pctsp/salesman/pctsp/algo/genius.py
# module genius.py # # Copyright (c) 2018 Rafael Reis # """ genius module - Implements GENIUS, an algorithm for generation of a solution. """ __version__="1.0" from pctsp.model.pctsp import * from pctsp.model import solution import numpy as np def genius(pctsp): s = solution.random(pctsp, size=3) s = geni(p...
426
14.25
77
py
RESPECT
RESPECT-main/problems/pctsp/salesman/pctsp/algo/ilocal_search.py
# module ilocal_search.py # # Copyright (c) 2018 Rafael Reis # """ ilocal_search module - Implements Iterate Local Search algorithm. """ __version__="1.0" import numpy as np import random def ilocal_search(s, n_runs=10): h = s.copy() best = s.copy() times = [1000] * n_runs # random.sample(range(1000, 20...
2,127
20.494949
71
py
RESPECT
RESPECT-main/problems/pctsp/salesman/pctsp/algo/geni.py
# module geni.py # # Copyright (c) 2018 Rafael Reis # """ geni module - Auxiliary functions to the GENI method. """ __version__="1.0" import numpy as np import sys def geni(v, s, max_i): quality_1 = 0 quality_2 = 0 s_star = Solution() s_start.quality = sys.maxint for i in range(1, max_i): ...
641
19.709677
66
py
RESPECT
RESPECT-main/problems/pctsp/salesman/pctsp/algo/__init__.py
# package algo # # Copyright (c) 2018 Rafael Reis # """ Package algo - Algorithms for solving the Prize Collecting Travelling Salesman Problem """ __version__="1.0" __author__ = "Rafael Reis <rafael2reis@gmail.com>"
218
18.909091
87
py
RESPECT
RESPECT-main/problems/tsp/tsp_gurobi.py
#!/usr/bin/python # Copyright 2017, Gurobi Optimization, Inc. # Solve a traveling salesman problem on a set of # points using lazy constraints. The base MIP model only includes # 'degree-2' constraints, requiring each node to have exactly # two incident edges. Solutions to this model may contain subtours - # tours...
3,951
31.393443
91
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/__init__.py
0
0
0
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/vrp_baseline.py
import argparse import os import numpy as np import re from utils.data_utils import check_extension, load_dataset, save_dataset from subprocess import check_call, check_output from urllib.parse import urlparse import tempfile import time from datetime import timedelta from utils import run_all_in_pool def get_lkh_exe...
10,387
38.052632
139
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/vrp/__init__.py
0
0
0
py
RESPECT
RESPECT-main/problems/vrp/encode-attend-navigate/data_generator.py
#-*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import math from sklearn.decomposition import PCA # Compute a sequence's reward def reward(tsp_sequence): tour = np.concatenate((tsp_sequence, np.expand_dims(tsp_sequence[0],0))) # sequence to tour (end=start) inter_city_distances = np....
4,401
39.385321
129
py
RESPECT
RESPECT-main/problems/vrp/encode-attend-navigate/utils.py
# -*- coding: utf-8 -*- from __future__ import print_function import tensorflow as tf import numpy as np from tqdm import tqdm # Embed input sequence [batch_size, seq_length, from_] -> [batch_size, seq_length, to_] def embed_seq(input_seq, from_, to_, is_training, BN=True, initializer=tf.contrib.layers.xavier_initial...
6,176
60.77
152
py
RESPECT
RESPECT-main/problems/vrp/encode-attend-navigate/Neural_Reinforce.py
# coding: utf-8 # # Neural Combinatorial Optimization # In[1]: #-*- coding: utf-8 -*- import tensorflow as tf distr = tf.contrib.distributions import numpy as np from tqdm import tqdm import os import matplotlib.pyplot as plt from utils import embed_seq, encode_seq, full_glimpse, pointer from data_generator impo...
21,835
45.95914
471
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/data_generator.py
import numpy as np import math import networkx as nx import random """ Data generator for mathematical symbolic expression; Given input: File consisting of a series of mathematical equation of string type--(m0=n1+n2) Expected output: A bunch of 4-dim nodes of shape (variable_out, variable_in1, operation, va...
3,467
33
133
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/__init__.py
0
0
0
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_gurobi.py
#!/usr/bin/python # Copyright 2017, Gurobi Optimization, Inc. # Solve a traveling salesman problem on a set of # points using lazy constraints. The base MIP model only includes # 'degree-2' constraints, requiring each node to have exactly # two incident edges. Solutions to this model may contain subtours - # tours...
4,369
35.722689
109
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/op_ortools.py
#!/usr/bin/env python # This Python file uses the following encoding: utf-8 # Copyright 2015 Tin Arm Engineering AB # Copyright 2018 Google LLC # 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 #...
9,057
33.441065
106
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/__init__.py
0
0
0
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/problems/op/opga/oph.py
import math def distance( p1, p2 ): return math.sqrt( ( p1[0] - p2[0] ) ** 2 + ( p1[1] - p2[1] ) ** 2 ) #returns a path (list of points) through s with high value def ellinit_replacement( s1, start_point, end_point, tmax ): s = list( s1 ) path = [ start_point, end_point ] length = distance( start_poin...
5,481
40.530303
105
py
RESPECT
RESPECT-main/problems/op/opga/opevo.py
import sys import random import time from . import oph #fitness will take a set s and a set of weights and return a tuple containing the fitness and the best path def fitness( chrom, s, start_point, end_point, tmax ): augs = [] for i in range( len( s ) ): augs.append( ( s[ i ][0], ...
5,970
37.522581
107
py
RESPECT
RESPECT-main/problems/op/opga/optest.py
import time import opevo files = [ 'test instances/set_64_1_15.txt' ] tmaxs = [ range( 15, 80 + 1, 5 ) ] Ns = [ 64 ] test_runs = 30 assert( len( files ) == len( tmaxs ) and len( tmaxs ) == len( Ns ) ) for i in range( len( files ) ): f = open( files[ i ] ) of = open( files[ i ][ :len( files[ i ] ) - 4 ] + '...
1,057
30.117647
95
py
RESPECT
RESPECT-main/problems/op/opga/__init__.py
0
0
0
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/data_utils.py
import os import pickle def check_extension(filename): if os.path.splitext(filename)[1] != ".pkl": return filename + ".pkl" return filename def save_dataset(dataset, filename): filedir = os.path.split(filename)[0] if not os.path.isdir(filedir): os.makedirs(filedir) with open(c...
528
20.16
56
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
RESPECT
RESPECT-main/utils/log_utils.py
def log_values(cost, grad_norms, epoch, batch_id, step, log_likelihood, reinforce_loss, bl_loss, tb_logger, opts): avg_cost = cost.mean().item() grad_norms, grad_norms_clipped = grad_norms # Log values to screen print('epoch: {}, train_batch_id: {}, avg_cost: {}'.format(epoch, batch_id, ...
1,093
42.76
90
py
RESPECT
RESPECT-main/utils/parameters.py
bypass = super
15
7
14
py
RESPECT
RESPECT-main/utils/__init__.py
from .functions import *
25
12
24
py
pytorch-consistency-regularization
pytorch-consistency-regularization-master/parser.py
import argparse def get_args(): parser = argparse.ArgumentParser() # dataset config parser.add_argument("--root", "-r", default="./data", type=str, help="/path/to/dataset") parser.add_argument("--dataset", "-d", default="cifar10", choices=['stl10', 'svhn', 'cifar10', 'cifar100'], type=str, help="datas...
5,939
86.352941
158
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/__init__.py
0
0
0
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/__init__.py
0
0
0
py
pytorch-consistency-regularization
pytorch-consistency-regularization-master/ssl_lib/models/builder.py
import numpy as np from .resnet import ResNet from .shakenet import ShakeNet from .cnn13 import CNN13 def gen_model(name, num_classes, img_size): scale = int(np.ceil(np.log2(img_size))) if name == "wrn": return ResNet(num_classes, 32, scale, 4) elif name == "shake": return ShakeNet(num_c...
449
25.470588
50
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/param_scheduler/__init__.py
0
0
0
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/consistency/__init__.py
0
0
0
py
pytorch-consistency-regularization
pytorch-consistency-regularization-master/ssl_lib/consistency/builder.py
from .cross_entropy import CrossEntropy from .mean_squared import MeanSquared def gen_consistency(type, cfg): if type == "ce": return CrossEntropy() elif type == "ms": return MeanSquared() else: return None
244
21.272727
39
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/__init__.py
0
0
0
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/misc/__init__.py
0
0
0
py
pytorch-consistency-regularization
pytorch-consistency-regularization-master/ssl_lib/misc/meter.py
class Meter: def __init__(self, ema_coef=0.9): self.ema_coef = ema_coef self.params = {} def add(self, params:dict, ignores:list = []): for k, v in params.items(): if k in ignores: continue if not k in self.params.keys(): self.para...
655
27.521739
76
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/utils.py
FIXMATCH_RANDAUGMENT_OPS_LIST = [ 'identity', 'autocontrast', 'brightness', 'color', 'contrast', 'equalize', 'posterize', 'rotate', 'sharpness', 'shear_x', 'shear_y', 'solarize', 'translate_x', 'translate_y' ] UDA_RANDAUGMENT_OPS_LIST = [ 'invert', 'auto...
907
15.214286
33
py