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 |
|---|---|---|---|---|---|---|
sampling_cf | sampling_cf-main/pytorch_models/pop_rec.py | from torch_utils import FloatTensor
class PopRec:
def __init__(self, hyper_params, item_count):
self.hyper_params = hyper_params
self.top_items = FloatTensor([ item_count[i] for i in range(hyper_params['total_items']) ]).unsqueeze(0)
def __call__(self, data, eval = False):
users, _, _ ... | 414 | 28.642857 | 112 | py |
sampling_cf | sampling_cf-main/data_loaders/base.py | import torch
import numpy as np
from collections import defaultdict
from torch.multiprocessing import Process, Queue, Event
class CombinedBase:
def __init__(self): pass
def __len__(self): return (self.num_interactions // self.batch_size) + 1
def __del__(self):
try:
self.p.terminate() ... | 5,688 | 39.347518 | 98 | py |
sampling_cf | sampling_cf-main/data_loaders/SASRec.py | import torch
import numpy as np
from data_loaders.base import BaseTrainDataset, BaseTestDataset
from torch_utils import LongTensor, is_cuda_available
class TrainDataset(BaseTrainDataset):
def __init__(self, data, hyper_params, track_events):
super(TrainDataset, self).__init__(data, hyper_params)
s... | 3,743 | 44.108434 | 110 | py |
sampling_cf | sampling_cf-main/data_loaders/SVAE.py | import torch
import numpy as np
from data_loaders.base import BaseTrainDataset, BaseTestDataset
from torch_utils import LongTensor, FloatTensor, is_cuda_available
class TrainDataset(BaseTrainDataset):
def __init__(self, data, hyper_params, track_events):
super(TrainDataset, self).__init__(data, hyper_para... | 3,329 | 43.4 | 104 | py |
sampling_cf | sampling_cf-main/data_loaders/MVAE.py | import numpy as np
from data_loaders.base import BaseTrainDataset, BaseTestDataset
from torch_utils import LongTensor, FloatTensor
class TrainDataset(BaseTrainDataset):
def __init__(self, data, hyper_params, track_events):
super(TrainDataset, self).__init__(data, hyper_params)
self.shuffle_allowed... | 2,616 | 44.12069 | 104 | py |
sampling_cf | sampling_cf-main/data_loaders/MF.py | import torch
import numpy as np
from data_loaders.base import BaseTrainDataset, BaseTestDataset
from torch_utils import LongTensor, FloatTensor, is_cuda_available
class TrainDataset(BaseTrainDataset):
def __init__(self, data, hyper_params, track_events):
super(TrainDataset, self).__init__(data, hyper_para... | 4,575 | 43.862745 | 114 | py |
neuralTPPs | neuralTPPs-master/debug/cumulative_attention.py | import torch as th
import matplotlib.pyplot as plt
from torch import nn
from pprint import pprint
from tqdm import tqdm
from tpp.models.base.enc_dec import EncDecProcess
from tpp.models.encoders.mlp_variable import MLPVariableEncoder
from tpp.models.decoders.self_attention_cm import SelfAttentionCmDecoder
from tpp.mo... | 2,491 | 30.544304 | 75 | py |
neuralTPPs | neuralTPPs-master/debug/batchnorm.py | import torch as th
from torch import nn
from tpp.pytorch.layers import NonNegLinear
from tpp.pytorch.layers import BatchNorm1d
def multidim_grad(a, b):
a_split = th.split(a, split_size_or_sections=1, dim=-1)
grads = [th.autograd.grad(
outputs=a_split[i],
inputs=b,
grad_outputs=th.ones... | 1,043 | 22.2 | 59 | py |
neuralTPPs | neuralTPPs-master/debug/layernorm.py | import torch as th
from torch import nn
from tpp.pytorch.layers import LayerNorm
from debug.batchnorm import multidim_grad
th.manual_seed(0)
pytorch_norm = nn.LayerNorm(3)
my_norm = LayerNorm(3, use_running_stats=True)
x = th.rand([3]).reshape(1, -1).float().repeat(2, 1)
x.requires_grad = True
pytorch_y = pytorch_... | 831 | 19.8 | 55 | py |
neuralTPPs | neuralTPPs-master/debug/regression.py | import numpy as np
import torch as th
import torch.nn
import matplotlib.pyplot as plt
from tpp.pytorch.models import MLP
def detach(x: th.Tensor) -> np.ndarray:
return x.detach().cpu().numpy()
th.manual_seed(0)
x_min, x_max, steps = 0., 100., 3000
alpha = 1.
beta = 1.
n_events = 20
epochs = 1000
cumulative =... | 2,239 | 23.086022 | 68 | py |
neuralTPPs | neuralTPPs-master/profiling/r_terms_for_pytorch_profile.py | import torch as th
from tpp.processes.hawkes.r_terms_recursive_v import get_r_terms
from tpp.utils.test import get_test_events_query
def run_test():
marks = 3
events, query = get_test_events_query(marks=marks)
beta = th.rand([marks, marks])
get_r_terms(events=events, beta=beta)
if __name__ == '__m... | 343 | 19.235294 | 64 | py |
neuralTPPs | neuralTPPs-master/profiling/get_r_terms_profile.py | import time
import matplotlib.pyplot as plt
import numpy as np
import torch as th
# from tpp.processes.hawkes.r_terms import get_r_terms as naive
from tpp.processes.hawkes.r_terms_recursive import get_r_terms as recursive
from tpp.processes.hawkes.r_terms_recursive_v import get_r_terms as recursive_v
from tpp.utils.te... | 2,568 | 28.872093 | 79 | py |
neuralTPPs | neuralTPPs-master/profiling/get_prev_times_profile.py | import time
import torch as th
import numpy as np
import matplotlib.pyplot as plt
from tpp.utils.events import get_events, get_window
from tpp.utils.history import get_prev_times
from tpp.utils import history_bst
def get_test_events_query(
batch_size=16, seq_len=16, n_queries=16, device=th.device('cpu'),
... | 3,472 | 29.464912 | 76 | py |
neuralTPPs | neuralTPPs-master/scripts/evaluate.py | import json
import numpy as np
import os
import torch as th
from argparse import ArgumentParser, Namespace
from distutils.util import strtobool
from pathlib import Path
from scripts.train import evaluate
from tpp.processes.multi_class_dataset import MultiClassDataset as Dataset
from tpp.utils.data import get_loader
f... | 7,022 | 43.732484 | 79 | py |
neuralTPPs | neuralTPPs-master/scripts/train.py | import mlflow
import mlflow.pytorch
import imageio
import json
import numpy as np
import os
import stat
import time
import torchvision
import torch as th
from torch.optim import Adam
from torch.utils.data import DataLoader
from argparse import Namespace
from copy import deepcopy
from typing import Dict, Tuple, Option... | 13,355 | 33.511628 | 79 | py |
neuralTPPs | neuralTPPs-master/tests/test_nll.py | import numpy as np
import torch as th
from tpp.processes.hawkes import neg_log_likelihood_old as nll_old
from tpp.processes.hawkes import neg_log_likelihood as nll_new
from tpp.utils.keras_preprocessing.sequence import pad_sequences
def test_nll():
n_seq = 10
my_alpha = 0.7
my_mu = 0.1
pad_id = -1.
... | 1,095 | 27.102564 | 74 | py |
neuralTPPs | neuralTPPs-master/tests/test_intensity.py | import numpy as np
import torch as th
from tpp.processes.hawkes import intensity_old as intensity_old
from tpp.processes.hawkes import intensity_at_t as intensity_new
from tpp.processes.hawkes import intensity_at_times
from tpp.utils.keras_preprocessing.sequence import pad_sequences
def test_intensity():
n_seq ... | 2,487 | 30.897436 | 79 | py |
neuralTPPs | neuralTPPs-master/tests/processes/test_hawkes_fast_custom.py | import torch as th
from tpp.utils.history_bst import get_prev_times
from tpp.processes.hawkes_fast import decoder_fast
from tpp.processes.hawkes_slow import decoder_slow
from tpp.utils.events import get_events, get_window
def get_fast_slow_results():
padding_id = -1.
times = th.Tensor([[1, 2, -1., -1.]]).ty... | 2,388 | 28.493827 | 68 | py |
neuralTPPs | neuralTPPs-master/tests/processes/test_r_terms.py | import torch as th
from tpp.processes.hawkes.r_terms import get_r_terms as get_r_terms_n
from tpp.processes.hawkes.r_terms_recursive import get_r_terms as get_r_terms_r
from tpp.processes.hawkes.r_terms_recursive_v import get_r_terms as get_r_terms_v
from tpp.utils.test import get_test_events_query
def test_r_terms(... | 1,238 | 33.416667 | 81 | py |
neuralTPPs | neuralTPPs-master/tests/processes/test_hawkes_fast.py | import torch as th
from tpp.utils.history_bst import get_prev_times
from tpp.utils.index import unravel_index
from tpp.utils.test import get_test_events_query
from tpp.processes.hawkes_fast import decoder_fast
from tpp.processes.hawkes_slow import decoder_slow
def get_fast_slow_results(
queries=1, marks=2, m... | 2,648 | 29.102273 | 68 | py |
neuralTPPs | neuralTPPs-master/tests/processes/test_r_terms_custom.py | import torch as th
from tpp.processes.hawkes.r_terms import get_r_terms as get_r_terms_n
from tpp.processes.hawkes.r_terms_recursive import get_r_terms as get_r_terms_r
from tpp.processes.hawkes.r_terms_recursive_v import get_r_terms as get_r_terms_v
from tpp.utils.events import get_events, get_window
def test_setup... | 1,451 | 32 | 81 | py |
neuralTPPs | neuralTPPs-master/tests/utils/test_stability.py | import torch as th
from tpp.utils.stability import subtract_exp
def test_stability():
a, b, c = th.tensor(8.1), th.tensor(0.0), th.tensor(0.0)
naive_subtraction_1 = th.exp(a) - th.exp(b)
safe_subtraction_1 = subtract_exp(a, b)
naive_subtraction_2 = th.exp(b) - th.exp(a)
safe_subtraction_2 = subt... | 668 | 26.875 | 62 | py |
neuralTPPs | neuralTPPs-master/tests/utils/test_searchsorted.py | import numpy as np
import torch as th
from tpp.utils.searchsorted import searchsorted
def get_test_data(rows=7, data_cols=9, query_cols=11, padding_id=-1.):
x_padded = th.rand(rows, data_cols).float()
x_padded = th.sort(x_padded, dim=-1).values
query = th.rand(rows, query_cols).float()
lens = th.rand... | 1,037 | 30.454545 | 70 | py |
neuralTPPs | neuralTPPs-master/tests/utils/test_to_flat_idxs.py | import torch as th
from tpp.utils.test import get_test_events_query
def test_to_flat_idxs():
events, query = get_test_events_query()
times_marked = events.get_times(marked=True)
times = events.get_times()
masks = events.get_mask(marked=True)
to_flat_idxs = events.to_flat_idxs
for time_marke... | 586 | 25.681818 | 62 | py |
neuralTPPs | neuralTPPs-master/tests/utils/test_get_previous_times_marked.py | import torch as th
from tpp.utils.test import get_test_events_query
from tpp.utils.history_bst import get_prev_times
from tpp.utils.history_marked_bst import get_prev_times_marked
def test_get_previous_times_marked():
th.random.manual_seed(0)
events, query = get_test_events_query(
batch_size=1, max_s... | 482 | 24.421053 | 62 | py |
neuralTPPs | neuralTPPs-master/tests/utils/test_get_previous_times.py | import torch as th
from tests.processes.test_hawkes_fast import get_test_setup
from tpp.utils.history import get_prev_times
from tpp.utils.history_bst import get_prev_times as get_prev_times_bst
def test_get_previous_times():
(marks, query, events,
prev_times, is_event,
alpha, beta, mu) = get_test_setu... | 1,395 | 35.736842 | 74 | py |
neuralTPPs | neuralTPPs-master/tpp/models/__init__.py | from argparse import Namespace
from torch import nn
from pprint import pprint
from tpp.models.base.enc_dec import EncDecProcess
from tpp.models.base.modular import ModularProcess
from tpp.models.poisson import PoissonProcess
from tpp.models.encoders.base.encoder import Encoder
from tpp.models.encoders.gru import GRUE... | 4,192 | 36.106195 | 111 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/conditional_poisson_cm.py | import torch as th
from typing import List, Optional, Tuple, Dict
from tpp.models.decoders.base.cumulative import CumulativeDecoder
from tpp.models.base.process import Events
from tpp.pytorch.models import MLP
from tpp.utils.encoding import encoding_size
from tpp.utils.index import take_2_by_2, take_3_by_2
class ... | 5,722 | 41.392593 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/hawkes.py | import torch as th
import torch.nn as nn
from typing import Dict, Optional, Tuple
from tpp.models.decoders.base.decoder import Decoder
from tpp.utils.events import Events
from tpp.utils.nnplus import non_neg_param
from tpp.processes.hawkes_fast import decoder_fast as hawkes_decoder
# from tpp.processes.hawkes_slow im... | 1,860 | 32.836364 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/conditional_poisson.py | import torch as th
from typing import Dict, Optional, Tuple, List
from tpp.models.decoders.base.decoder import Decoder
from tpp.pytorch.models import MLP
from tpp.utils.events import Events
from tpp.utils.index import take_2_by_2, take_3_by_2
from tpp.utils.stability import epsilon, check_tensor
class Conditional... | 3,000 | 36.987342 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/log_normal_mixture.py | import math
import torch as th
import torch.nn as nn
from typing import Dict, Optional, Tuple, List
from tpp.models.decoders.base.decoder import Decoder
from tpp.utils.events import Events
from tpp.utils.index import take_3_by_2, take_2_by_2
from tpp.utils.stability import epsilon, check_tensor
class LogNormalMixt... | 6,516 | 40.509554 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/self_attention_cm.py | import torch as th
from typing import List, Optional, Tuple, Dict
from tpp.models.decoders.base.cumulative import CumulativeDecoder
from tpp.models.base.process import Events
from tpp.pytorch.models import MLP
from tpp.utils.encoding import encoding_size
from tpp.utils.transformer_utils import TransformerDecoderNet... | 8,473 | 40.950495 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/poisson.py | import torch as th
import torch.nn as nn
from typing import Dict, Optional, Tuple
from tpp.models.decoders.base.decoder import Decoder
from tpp.utils.events import Events
from tpp.utils.nnplus import non_neg_param
class PoissonDecoder(Decoder):
"""A parametric Hawkes Process decoder.
Args:
marks: T... | 1,740 | 33.82 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/rmtpp.py | import torch as th
import torch.nn as nn
from typing import Dict, Optional, Tuple
from tpp.models.decoders.base.decoder import Decoder
from tpp.utils.events import Events
from tpp.utils.index import take_3_by_2, take_2_by_2
from tpp.utils.stability import epsilon, subtract_exp, check_tensor
class RMTPPDecoder(Decod... | 5,709 | 41.61194 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/self_attention_simple_cm.py | import torch as th
from typing import List, Optional, Tuple, Dict
from tpp.models.decoders.base.cumulative import CumulativeDecoder
from tpp.models.base.process import Events
from tpp.pytorch.models import MLP
from tpp.utils.encoding import encoding_size
class SelfAttentionCmDecoder(CumulativeDecoder):
"""A s... | 7,952 | 39.784615 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/mlp_mc.py | import torch as th
import torch.nn.functional as F
from typing import List, Optional, Tuple, Dict
from tpp.models.decoders.base.monte_carlo import MCDecoder
from tpp.models.base.process import Events
from tpp.pytorch.models import MLP
from tpp.utils.encoding import encoding_size
from tpp.utils.index import take_3_b... | 5,563 | 39.911765 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/self_attention_mc.py | import torch as th
import torch.nn.functional as F
from typing import List, Optional, Tuple, Dict
from tpp.models.decoders.base.monte_carlo import MCDecoder
from tpp.models.base.process import Events
from tpp.pytorch.models import MLP
from tpp.utils.encoding import encoding_size
from tpp.utils.transformer_utils imp... | 7,944 | 41.945946 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/mlp_cm.py | import torch as th
from typing import List, Optional, Tuple, Dict
from tpp.models.decoders.base.cumulative import CumulativeDecoder
from tpp.models.base.process import Events
from tpp.pytorch.models import MLP
from tpp.utils.encoding import encoding_size
from tpp.utils.index import take_3_by_2
class MLPCmDecoder(... | 5,883 | 40.730496 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/rmtpp_cm.py | import torch as th
import torch.nn as nn
from typing import Dict, Optional, Tuple
from tpp.models.decoders.base.cumulative import CumulativeDecoder
from tpp.utils.events import Events
from tpp.utils.index import take_3_by_2, take_2_by_2
from tpp.utils.stability import epsilon
class RMTPPCmDecoder(CumulativeDecoder)... | 5,695 | 42.151515 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/neural_hawkes.py | """
Based on the implementation of Xiao Liu on Jan. 31, 2019.
https://github.com/xiao03/nh
"""
from typing import List, Optional, Tuple, Dict
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from tpp.models.decoders.base.monte_carlo import MCDecoder
from tpp.models.base.process import Events
... | 7,444 | 36.225 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/base/variable_history.py | import abc
import torch as th
import torch.nn as nn
from typing import Optional
from tpp.models.base.process import Events
from tpp.models.decoders.base.decoder import Decoder
from tpp.pytorch.models import MLP
from tpp.utils.encoding import SinusoidalEncoding
from tpp.utils.encoding import event_encoder
from tpp.... | 5,694 | 39.105634 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/base/decoder.py | import abc
import torch as th
import torch.nn as nn
from typing import Dict, Optional, Tuple
from tpp.utils.events import Events
class Decoder(nn.Module, abc.ABC):
"""An decoder for a TPP.
Args:
name: The name of the decoder class.
input_size: The dimensionality of the input required from ... | 3,146 | 37.851852 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/base/cumulative.py | import abc
import torch as th
from typing import Optional, Tuple, Dict
from tpp.models.base.process import Events
from tpp.models.decoders.base.variable_history import VariableHistoryDecoder
from tpp.pytorch.layers.log import Log
from tpp.utils.stability import epsilon, check_tensor, subtract_exp
class Cumulativ... | 10,617 | 41.64257 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/decoders/base/monte_carlo.py | import abc
import torch as th
from typing import Optional, Tuple, Dict
from tpp.models.decoders.base.variable_history import VariableHistoryDecoder
from tpp.models.base.process import Events
from tpp.utils.stability import check_tensor
class MCDecoder(VariableHistoryDecoder, abc.ABC):
"""Decoder based on Monte... | 8,100 | 43.756906 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/encoders/identity.py | import torch as th
from typing import Dict, Optional, Tuple
from tpp.models.encoders.base.variable_history import VariableHistoryEncoder
from tpp.utils.encoding import encoding_size
from tpp.utils.events import Events
class IdentityEncoder(VariableHistoryEncoder):
"""Variable encoder that passes the representat... | 2,409 | 37.870968 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/encoders/mlp_variable.py | import torch as th
from typing import Dict, List, Optional, Tuple
from tpp.models.encoders.base.variable_history import VariableHistoryEncoder
from tpp.pytorch.models import MLP
from tpp.utils.events import Events
class MLPVariableEncoder(VariableHistoryEncoder):
"""Variable MLP encoder, i.e. r(t) = MLP(rep(l, ... | 3,057 | 38.714286 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/encoders/gru.py | from torch import nn
from typing import Optional, List
from tpp.models.encoders.base.recurrent import RecurrentEncoder
from tpp.utils.encoding import encoding_size
class GRUEncoder(RecurrentEncoder):
"""GRU network, based on a variable recurrent encoder.
Args:
units_rnn: Hidden size of the GRU.
... | 2,738 | 38.128571 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/encoders/self_attention.py | import torch as th
import torch.nn.functional as F
from typing import List, Optional, Tuple, Dict
from tpp.models.encoders.base.variable_history import VariableHistoryEncoder
from tpp.pytorch.models import MLP
from tpp.utils.events import Events
from tpp.utils.transformer_utils import TransformerEncoderNetwork
from... | 5,508 | 38.070922 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/encoders/mlp_fixed.py | from typing import List, Optional
from tpp.models.encoders.base.fixed_history import FixedHistoryEncoder
from tpp.pytorch.models import MLP
class MLPFixedEncoder(FixedHistoryEncoder):
"""MLP network using a fixed history encoder.
Args
units_mlp: List of hidden layers sizes.
activation_mlp: A... | 1,597 | 34.511111 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/encoders/stub.py | import torch as th
from typing import Dict, Optional, Tuple
from tpp.models.encoders.base.encoder import Encoder
from tpp.utils.events import Events
class StubEncoder(Encoder):
"""An encoder that does nothing. Used for e.g. the Hawkes decoder that
needs no encoding.
Args:
marks: The distinc... | 691 | 29.086957 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/encoders/base/encoder.py | import abc
import torch as th
import torch.nn as nn
from typing import Dict, Optional, Tuple
from tpp.utils.events import Events
class Encoder(nn.Module, abc.ABC):
"""An encoder for a TPP.
Args:
name: The name of the encoder class.
output_size: The output size (dimensionality) of the repre... | 1,346 | 26.489796 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/encoders/base/variable_history.py | import abc
import torch as th
import torch.nn as nn
from typing import Optional, Tuple
from tpp.utils.events import Events
from tpp.models.encoders.base.encoder import Encoder
from tpp.pytorch.models import LAYER_CLASSES, MLP
from tpp.utils.history import get_prev_times
from tpp.utils.encoding import SinusoidalEn... | 4,746 | 37.593496 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/encoders/base/recurrent.py | import torch as th
import torch.nn as nn
import torch.nn.functional as F
from typing import Dict, List, Optional, Tuple
from tpp.models.encoders.base.variable_history import VariableHistoryEncoder
from tpp.pytorch.models import MLP
from tpp.utils.events import Events
class RecurrentEncoder(VariableHistoryEncoder):
... | 3,414 | 37.370787 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/encoders/base/fixed_history.py | import torch as th
import torch.nn as nn
from typing import Dict, Optional, Tuple
from tpp.utils.events import Events
from tpp.models.encoders.base.encoder import Encoder
from tpp.utils.history import build_histories
class FixedHistoryEncoder(Encoder):
"""A parametric encoder process with a fixed history size r... | 3,415 | 36.130435 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/base/modular.py | import torch as th
import torch.nn as nn
import torch.nn.functional as F
from tpp.utils.events import Events
from typing import Dict, Optional, Tuple
from tpp.models.base.enc_dec import EncDecProcess
class ModularProcess(EncDecProcess):
"""Build a process out of multiple process instances.
Args:
pr... | 4,297 | 37.035398 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/base/enc_dec.py | import torch as th
from typing import Dict, Optional, Tuple
from tpp.models.decoders.base.decoder import Decoder
from tpp.models.encoders.base.encoder import Encoder
from tpp.models.base.process import Process
from tpp.utils.events import Events
from tpp.utils.history_bst import get_prev_times
from tpp.utils.index im... | 11,732 | 40.903571 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/models/base/process.py | import abc
import torch as th
import torch.nn as nn
from typing import Dict, Optional, Tuple
from tpp.utils.events import Events
class Process(nn.Module):
def __init__(self, name: str, marks: Optional[int] = 1, **kwargs):
"""A parametric process.
Args:
name: The name of the process.
... | 1,777 | 28.633333 | 78 | py |
neuralTPPs | neuralTPPs-master/tpp/processes/hawkes_fast.py | import torch as th
from typing import Dict, Optional, Tuple
# from tpp.processes.hawkes.r_terms import get_r_terms as get_r_terms
# from tpp.processes.hawkes.r_terms_recursive import get_r_terms
from tpp.processes.hawkes.r_terms_recursive_v import get_r_terms
from tpp.utils.events import Events
from tpp.utils.history... | 5,271 | 44.059829 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/processes/hawkes.py | import torch as th
from torch.nn.functional import relu
def intensity_at_t(mu, alpha, sequences_padded, mask, t):
"""Finds the hawkes intensity:
mu + alpha * sum( np.exp(-(t-s)) for s in points if s<=t )
Args:
mu: float
alpha: float
sequences_padded: 2d numpy array
mask: ... | 3,827 | 27.355556 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/processes/hawkes_slow.py | import torch as th
from typing import Dict, Optional, Tuple
import tpp.utils.batch as bu
from tpp.utils.events import Events
def decoder_slow(
events: Events,
query: th.Tensor,
prev_times: th.Tensor,
is_event: th.Tensor,
alpha: th.Tensor,
beta: th.Tensor,
mu:... | 4,663 | 40.274336 | 78 | py |
neuralTPPs | neuralTPPs-master/tpp/processes/multi_class_dataset.py | import json
import os
import numpy as np
import torch as th
from tick.hawkes import SimuHawkes, HawkesKernelExp
from tqdm import tqdm
from typing import List
from tpp.utils.marked_times import objects_from_events
from tpp.utils.marked_times import pad
from tpp.utils.record import hawkes_seq_to_record
class MultiCl... | 7,324 | 34.216346 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/processes/hawkes/r_terms.py | import torch as th
from tpp.utils.events import Events
def get_r_terms(events: Events, beta: th.Tensor) -> th.Tensor:
"""
R_{m,n}(i)=sum_{j: t_j^n < t_i^m} exp(- beta_{m,n} (t_i^m - t_j^n))
Returns:
[B,Li,M,N] The R term for each event. Note, these are only defined when
there are actuall... | 1,208 | 34.558824 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/processes/hawkes/r_terms_recursive_v.py | import time
import torch as th
from tpp.utils.events import Events
def get_r_terms(events: Events, beta: th.Tensor) -> th.Tensor:
"""
R_{m,n}(i)=sum_{j: t_j^n < t_i^m} exp(- beta_{m,n} (t_i^m - t_j^n))
Computed using the recursive definition
R_{m,n}(i) = term_1 + term_2
R_{m,n}(1) = 0
term_... | 2,081 | 34.896552 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/processes/hawkes/r_terms_recursive.py | import torch as th
from typing import Optional
from tpp.utils.events import Events
def get_r_terms(
events: Events,
beta: th.Tensor,
r_terms: Optional[th.Tensor] = None) -> th.Tensor:
"""
R_{m,n}(i)=sum_{j: t_j^n < t_i^m} exp(- beta_{m,n} (t_i^m - t_j^n))
Computed using the recu... | 2,154 | 33.206349 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/lr_scheduler.py | import torch
import torch.optim as optim
from torch.optim.lr_scheduler import _LRScheduler
def create_lr_scheduler(optimizer, args):
if not isinstance(optimizer, optim.Optimizer):
# assume FP16_Optimizer
optimizer = optimizer.optimizer
if args.lr_scheduler == 'plateau':
lr_scheduler ... | 4,016 | 38.382353 | 103 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/events.py | import torch as th
from typing import NamedTuple, Optional, Tuple
class Events(NamedTuple):
"""All event information.
Props:
times: [B,L] The times of the events.
times_first: [B] The time of the first event.
times_first_idx: [B] The index (into [L]) of the first event.
times... | 6,790 | 37.367232 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/test.py | import torch as th
from tpp.utils.events import get_events, get_window
from tpp.utils.marked_times import pad
def get_test_events_query(
marks=2,
batch_size=16,
max_seq_len=16,
queries=4,
padding_id=-1.,
device=th.device('cpu'), dtype=th.float32):
seq_lens = th.ran... | 1,260 | 31.333333 | 70 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/marked_times.py | import torch as th
from torch.nn.functional import one_hot
from tqdm import tqdm
from typing import Dict, List, Optional
from tpp.utils.sequence import pad_sequence
def get_unmasked_tensor(
x: th.Tensor, mask: th.Tensor) -> List[th.Tensor]:
"""
Args:
x: [B,L] The tensor to subset by ... | 3,590 | 30.5 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/dtype.py | import numpy as np
import torch as th
TORCH_TO_NUMPY = {
th.float32: np.float32}
NUMPY_TO_TORCH = {k: v for v, k in TORCH_TO_NUMPY.items()}
| 146 | 17.375 | 58 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/sequence.py | """
Adapted from torch.nn.utils.rnn.pad_sequence
"""
def pad_sequence(sequences, batch_first=False, padding_value=0, pad_len=None):
r"""Pad a list of variable length Tensors with ``padding_value``
``pad_sequence`` stacks a list of Tensors along a new dimension,
and pads them to equal length. For example,... | 2,818 | 37.094595 | 84 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/batch.py | import torch as th
def _batchwise_fn(x, y, f):
"""For each value of `x` and `y`, compute `f(x, y)` batch-wise.
Args:
x (th.Tensor): [B1, B2, ... , BN, X] The first tensor.
y (th.Tensor): [B1, B2, ... , BN, Y] The second tensor.
f (function): The function to apply.
Returns:
... | 1,674 | 25.587302 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/history_marked_bst.py | import torch as th
from typing import Optional, Tuple
from tpp.utils.events import Events
from tpp.utils.index import take_2_by_2
from tpp.utils.searchsorted import searchsorted_marked
def get_prev_times_marked(
query: th.Tensor,
events: Events,
allow_window: Optional[bool] = False
) -> Tupl... | 4,577 | 44.78 | 81 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/record.py | import numpy as np
import torch as th
from typing import Dict, List, Tuple
def hawkes_seq_to_record(seq: List[np.ndarray]):
times = np.concatenate(seq)
labels = np.concatenate([[i] * len(x) for i, x in enumerate(seq)])
sort_idx = np.argsort(times)
times = times[sort_idx]
labels = labels[sort_idx]... | 443 | 25.117647 | 70 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/multi_head_attention.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.init import xavier_uniform_
from torch.nn.init import constant_
from torch.nn.init import xavier_normal_
from typing import Optional, Tuple
class MultiheadAttention(nn.Module):
r"""Allows the model to jointly attend to information
... | 25,378 | 46.975425 | 117 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/searchsorted.py | import torch as th
from torchsearchsorted import searchsorted as ss
from typing import Optional
def searchsorted(
a: th.Tensor, v: th.Tensor, mask: Optional[th.Tensor] = None):
"""
Args:
a: [B,L] The row sorted array to tree sort batch-wise.
v: [B,T] The queries for the t... | 1,750 | 29.719298 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/logging.py | import numpy as np
import pandas as pd
import tabulate
import torch as th
from typing import Optional
from argparse import Namespace
tabulate.MIN_PADDING = 0
def _format_key(x, split=".", key_length=5):
x = x.split(split)
x = [y[:key_length] for y in x]
x = split.join(x)
return x
def _format_dict... | 5,292 | 30.135294 | 78 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/utils.py | import torch as th
def smallest_positive(inputs, dim):
"""
Args
inputs: 3d array [B,T,L].
dim: dimension on which the largest tj lower than t is evaluated.
Return
(delta_t, idx_delta_t), is_candidate:
delta_t: t - tj, where th is the largest value lower than t
... | 1,196 | 41.75 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/data.py | import os
from torch.utils.data import DataLoader
from argparse import Namespace
from typing import Optional
from tpp.processes.multi_class_dataset import MultiClassDataset as Dataset
def get_loader(
dataset: Dataset,
args: Namespace,
shuffle: Optional[bool] = True) -> DataLoader:
return... | 1,153 | 27.146341 | 78 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/run.py | import git
import torch
import numpy as np
def check_repo(allow_uncommitted):
repo = git.Repo()
if repo.is_dirty() and not allow_uncommitted:
raise Warning("Repo contains uncommitted changes!")
return repo
def set_seed(seed):
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.ma... | 485 | 20.130435 | 59 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/history_bst.py | import torch as th
from typing import Optional, Tuple
from tpp.utils.events import Events
from tpp.utils.index import take_2_by_2
from tpp.utils.searchsorted import searchsorted
def get_prev_times(
query: th.Tensor,
events: Events,
allow_window: Optional[bool] = False
) -> Tuple[Tuple[th.Ten... | 2,991 | 42.362319 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/stability.py | import torch as th
from typing import Optional
def epsilon(eps=1e-30, dtype=th.float32, device=None):
return th.tensor(eps, dtype=dtype, device=device)
def epsilon_like(x, eps=1e-3):
return th.zeros_like(x) + th.tensor(eps, dtype=x.dtype, device=x.device)
def log_sub_exp(
a: th.Tensor,
b:... | 1,660 | 26.683333 | 76 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/plot.py | import json
import mlflow
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import torch as th
from argparse import Namespace
from matplotlib.figure import Figure
from pathlib import Path
from torch.utils.data import DataLoader
from typing import Dict, List, Optional, Tuple
from tpp.... | 19,536 | 38.70935 | 91 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/transformer_utils.py | import copy
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from tpp.pytorch.activations import ACTIVATIONS
from tpp.pytorch.activations import AdaptiveGumbel
from tpp.pytorch.activations import AdaptiveGumbelSoftplus
from tpp.pytorch.layers import LAYER_CLASSES
from tpp.pytorch.layers import ... | 13,319 | 38.525223 | 81 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/encoding.py | import torch as th
import torch.nn as nn
import math
import numpy as np
from typing import Optional, Callable
class SinusoidalEncoding(nn.Module):
def __init__(self, emb_dim, scaling):
super(SinusoidalEncoding, self).__init__()
self.emb_dim = emb_dim
self.scaling = scaling
def forwar... | 3,655 | 34.153846 | 78 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/index.py | import torch as th
def take_3_by_2(x: th.Tensor, index: th.LongTensor) -> th.Tensor:
"""Index into a rank 3 tensor with a rank 2 tensor. Specifically, replace
each index I with the corresponding indexed D-dimensional vector, where I
specifies the location in L, batch-wise.
Args:
x: [B,L,D] Th... | 2,668 | 32.3625 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/history.py | import torch as th
from typing import Optional, Tuple
from tpp.utils import batch as bu
from tpp.utils.events import Events
from tpp.utils.utils import smallest_positive
from tpp.utils.index import take_2_by_2
from tpp.utils.history_bst import get_prev_times as get_prev_times_bst
def _get_rank(x: th.Tensor) -> int:... | 6,494 | 38.603659 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/utils/keras_preprocessing/sequence.py | # -*- coding: utf-8 -*-
"""Utilities for preprocessing sequence data.
Copied verbatim from
https://github.com/keras-team/keras-preprocessing/blob/master/keras_preprocessing/sequence.py
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
im... | 4,092 | 35.873874 | 93 | py |
neuralTPPs | neuralTPPs-master/tpp/pytorch/models.py | import torch.nn as nn
from collections.abc import Iterable
from typing import List, Optional
from tpp.pytorch.activations import ParametricSoftplus, AdaptiveGumbel
from tpp.pytorch.activations import AdaptiveGumbelSoftplus
from tpp.pytorch.layers import LAYER_CLASSES
from tpp.pytorch.activations import ACTIVATIONS
... | 3,855 | 35.377358 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/pytorch/layers/dense.py | import torch as th
import torch.nn.functional as F
from torch import nn
class NonNegLinear(nn.Linear):
def __init__(self, in_features, out_features, bias=True, eps=0.):
super(NonNegLinear, self).__init__(in_features, out_features, bias)
self.eps = eps
self.positivify_weights()
def po... | 2,008 | 30.888889 | 77 | py |
neuralTPPs | neuralTPPs-master/tpp/pytorch/layers/batchnorm.py | import torch as th
from torch import nn
class BatchNorm1d(nn.BatchNorm1d):
def __init__(self, num_features, eps=1e-5, momentum=0.1,
affine=True, track_running_stats=True,
use_running_estimates=False,
normalise_over_final=False):
super(BatchNorm1d, self)._... | 3,663 | 39.711111 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/pytorch/layers/layernorm.py | import torch as th
from torch import nn
from typing import Optional
from tpp.utils.nnplus import non_neg_param
class LayerNorm(nn.LayerNorm):
def __init__(
self,
normalized_shape,
eps=1e-5,
elementwise_affine=True,
momentum=.1,
use_running_... | 3,327 | 35.571429 | 83 | py |
neuralTPPs | neuralTPPs-master/tpp/pytorch/layers/log.py | import torch as th
class Log(th.autograd.Function):
"""Safe implementation of x ↦ log(x)."""
@staticmethod
def forward(ctx, x):
log = x.log()
ctx.save_for_backward(x)
return log
@staticmethod
def backward(ctx, grad_output):
x, = ctx.saved_tensors
return th.... | 362 | 21.6875 | 59 | py |
neuralTPPs | neuralTPPs-master/tpp/pytorch/layers/__init__.py | from tpp.pytorch.layers.batchnorm import BatchNorm1d
from tpp.pytorch.layers.dense import LAYER_CLASSES
from tpp.pytorch.layers.dense import NonNegLinear
from tpp.pytorch.layers.dense import SigmoidLinear
from tpp.pytorch.layers.dense import SoftPlusLinear
from tpp.pytorch.layers.layernorm import LayerNorm
| 310 | 33.555556 | 52 | py |
neuralTPPs | neuralTPPs-master/tpp/pytorch/activations/gumbel.py | import math
import torch as th
from torch import nn
from tpp.utils.nnplus import non_neg_param
from tpp.utils.stability import epsilon_like
from tpp.pytorch.activations.softplus import ParametricSoftplus
class AdaptiveGumbel(nn.Module):
def __init__(self, units):
super(AdaptiveGumbel, self).__init__()
... | 2,272 | 28.519481 | 83 | py |
neuralTPPs | neuralTPPs-master/tpp/pytorch/activations/softplus.py | import torch as th
from torch import nn
from tpp.utils.nnplus import non_neg_param
from tpp.utils.stability import epsilon_like
class MonotonicSoftplus(nn.Module):
"""A version of the softplus that stays monotonic
"""
def __init__(self, beta=1, threshold=20):
super(MonotonicSoftplus, self).__init... | 2,617 | 29.8 | 75 | py |
neuralTPPs | neuralTPPs-master/tpp/pytorch/activations/pau_utils.py | from time import time
import numpy as np
import torch
import torch.nn as nn
from numpy.random.mtrand import RandomState
def get_constants_for_inits(name, seed=17):
# (numerator: [x, x.pow(1), x.pow(2), x.pow(3), x.pow(4, x.pow(5)], denominator: (x, x.pow(2), center)
if name == "pade_sigmoid_3":
retu... | 6,193 | 33.220994 | 113 | py |
neuralTPPs | neuralTPPs-master/tpp/pytorch/activations/__init__.py | from torch import nn
from tpp.pytorch.activations.arctan import Arctan
from tpp.pytorch.activations.gumbel import AdaptiveGumbel
from tpp.pytorch.activations.gumbel import AdaptiveGumbelSoftplus
from tpp.pytorch.activations.pau import PAU
from tpp.pytorch.activations.softplus import MonotonicSoftplus
from tpp.pytorch.... | 860 | 30.888889 | 65 | py |
neuralTPPs | neuralTPPs-master/tpp/pytorch/activations/pau.py | """
Taken from
https://github.com/ml-research/pau/blob/master/pau/cuda/python_imp/Pade.py
"""
import torch as th
from tpp.pytorch.activations.pau_utils import PADEACTIVATION_Function_based
class PAU(PADEACTIVATION_Function_based):
def __init__(
self,
init_coefficients="pade_optimized_lea... | 1,563 | 26.928571 | 79 | py |
neuralTPPs | neuralTPPs-master/tpp/pytorch/activations/arctan.py | import torch as th
import torch.nn as nn
class Arctan(nn.Module):
"""Arctan activation function
"""
def __init__(self):
super(Arctan, self).__init__()
def forward(self, x):
return th.atan(x)
| 226 | 16.461538 | 38 | py |
more-or-let | more-or-let-master/pydrobert/mol/callbacks.py | '''Callbacks and callback-related periphery'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from csv import DictReader
from six.moves.cPickle import dump
import numpy as np
from keras.callbacks import Callback
from keras.callbacks import EarlyStopping
... | 14,210 | 37.099196 | 79 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.