code stringlengths 17 6.64M |
|---|
def cached_path(url_or_filename, cache_dir=None, force_download=False, proxies=None, resume_download=False, user_agent: Union[(Dict, str, None)]=None, extract_compressed_file=False, force_extract=False, local_files_only=False) -> Optional[str]:
"\n Given something that might be a URL (or might be a local path)... |
def http_get(url, temp_file, proxies=None, resume_size=0, user_agent: Union[(Dict, str, None)]=None):
ua = 'transformers/{}; python/{}'.format(__version__, sys.version.split()[0])
if is_torch_available():
ua += '; torch/{}'.format(torch.__version__)
if is_tf_available():
ua += '; tensorflo... |
def get_from_cache(url, cache_dir=None, force_download=False, proxies=None, etag_timeout=10, resume_download=False, user_agent: Union[(Dict, str, None)]=None, local_files_only=False) -> Optional[str]:
"\n Given a URL, look for the corresponding file in the local cache.\n If it's not there, download it. Then... |
class cached_property(property):
'\n Descriptor that mimics @property but caches output in member variable.\n From tensorflow_datasets\n Built-in in functools from Python 3.8.\n '
def __get__(self, obj, objtype=None):
if (obj is None):
return self
if (self.fget is None... |
def torch_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
if is_torch_available():
return func(*args, **kwargs)
else:
raise ImportError(f'Method `{func.__name__}` requires PyTorch.')
return wrapper
|
def tf_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
if is_tf_available():
return func(*args, **kwargs)
else:
raise ImportError(f'Method `{func.__name__}` requires TF.')
return wrapper
|
class ModelOutput():
'\n Base class for all model outputs as dataclass. Has a ``__getitem__`` that allows indexing by integer or slice (like\n a tuple) or strings (like a dictionnary) that will ignore the ``None`` attributes.\n '
def to_tuple(self):
'\n Converts :obj:`self` to a tuple... |
class EntityEmbeddingVLayer(nn.Module):
'\n This embedding layer uses vicinity information to smooth over the continuous variables.\n If normal embedding layer is to be desired, please use EntityEmbeddingLayer (without V).\n '
def __init__(self, num_level, emdedding_dim, centroid, name):
sup... |
class EntityEmbeddingLayer(nn.Module):
def __init__(self, num_level, embedding_dim, name):
super(EntityEmbeddingLayer, self).__init__()
self.embedding = nn.Embedding(num_level, embedding_dim)
self.name = name
def forward(self, x):
return self.embedding(x)
|
class EntityDenseLayer(nn.Module):
def __init__(self, data_pd, opt: TabDataOpt, mlp=None):
super(EntityDenseLayer, self).__init__()
self.opt = opt
self.mlp = mlp
if (len(self.opt.conti_vars) and (mlp is None)):
logging.error('\n The options have specified th... |
def get_constant_schedule(optimizer: Optimizer, last_epoch: int=(- 1)):
'\n Create a schedule with a constant learning rate, using the learning rate set in optimizer.\n Args:\n optimizer (:class:`~torch.optim.Optimizer`):\n The optimizer for which to schedule the learning rate.\n la... |
def get_constant_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, last_epoch: int=(- 1)):
'\n Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate\n increases linearly between 0 and the initial lr set in the optimizer.\n Args:\n ... |
def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=(- 1)):
'\n Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0,\n after a warmup period during which it increases linearly from 0 to the initial lr set in... |
def get_cosine_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float=0.5, last_epoch: int=(- 1)):
'\n Create a schedule with a learning rate that decreases following the values of the cosine function between the\n initial lr set in the optimizer to 0, a... |
def get_cosine_with_hard_restarts_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: int=1, last_epoch: int=(- 1)):
'\n Create a schedule with a learning rate that decreases following the values of the cosine function between the\n initial lr set in the op... |
class AdamW(Optimizer):
"\n Implements Adam algorithm with weight decay fix as introduced in\n `Decoupled Weight Decay Regularization <https://arxiv.org/abs/1711.05101>`__.\n Parameters:\n params (:obj:`Iterable[torch.nn.parameter.Parameter]`):\n Iterable of parameters to optimize or di... |
@dataclass
class OptimizerOptBase():
lr: float = field(default=0.01, metadata={'help': 'The learning rate of base optimizers.Default value is 1e-2'})
|
@dataclass
class SGDOpt(OptimizerOptBase):
momentum: float = field(default=0, metadata={'help': 'The momentum parameter for SGD optimizer.Default value is 0'})
weight_decay: float = field(default=0, metadata={'help': 'The weight decay parameter for SGD optimizerDefault is 0.'})
dampening: float = field(de... |
@dataclass
class AdamWOpt(OptimizerOptBase):
betas: any = field(default=(0.9, 0.999), metadata={'help': 'The betas for Adam optimizer.Default values are (0.9, 0.999).'})
eps: str = field(default=1e-08, metadata={'help': '\n A term added to the denominator to improve numerical stability (d... |
@dataclass
class LookaheadOpt(OptimizerOptBase):
inner_opt: OptimizerOptBase = field(default=AdamWOpt(), metadata={'help': 'The optimizer setup for inner optimizer.Default is AdamW Opt.'})
la_steps: int = field(default=5, metadata={'help': 'The number of steps for the lookahead optimizer.Default value is 5.'}... |
@dataclass
class RAdamWOpt(OptimizerOptBase):
betas: any = field(default=(0.9, 0.999), metadata={'help': 'The betas for RAdam optimizer.Default values are (0.9, 0.999).'})
eps: str = field(default=1e-08, metadata={'help': '\n A term added to the denominator to improve numerical stability ... |
class Lookahead(Optimizer):
'PyTorch implementation of the lookahead wrapper.\n Lookahead Optimizer: https://arxiv.org/abs/1907.08610\n '
def __init__(self, optimizer, la_steps=5, la_alpha=0.8, pullback_momentum='none'):
'optimizer: inner optimizer\n la_steps (int): number of lookahead s... |
class RAdamW(Optimizer):
def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, degenerated_to_sgd=True):
if (not (0.0 <= lr)):
raise ValueError('Invalid learning rate: {}'.format(lr))
if (not (0.0 <= eps)):
raise ValueError('Invalid epsilon va... |
def log_lamb_rs(optimizer: Optimizer, event_writer: SummaryWriter, token_count: int):
'Log a histogram of trust ratio scalars in across layers.'
results = collections.defaultdict(list)
for group in optimizer.param_groups:
for p in group['params']:
state = optimizer.state[p]
... |
class Lamb(Optimizer):
'Implements Lamb algorithm.\n It has been proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_.\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): ... |
def is_tensorboard_available():
return _has_tensorboard
|
@contextmanager
def torch_distributed_zero_first(local_rank: int):
'\n Decorator to make all processes in distributed training wait for each local_master to do something.\n Args:\n local_rank (:obj:`int`): The rank of the local process.\n '
if (local_rank not in [(- 1), 0]):
torch.dist... |
def get_tpu_sampler(dataset: Dataset):
if (xm.xrt_world_size() <= 1):
return RandomSampler(dataset)
return DistributedSampler(dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal())
|
class SequentialDistributedSampler(Sampler):
"\n Distributed Sampler that subsamples indicies sequentially,\n making it easier to collate all results at the end.\n Even though we only use this sampler for eval and predict (no training),\n which means that the model params won't have to be synced (i.e.... |
class Trainer():
'\n Trainer is a simple but feature-complete training and eval loop for PyTorch,\n optimized for 🤗 Transformers.\n Args:\n model (:class:`~transformers.PreTrainedModel`):\n The model to train, evaluate or use for predictions.\n args (:class:`~transformers.Traini... |
def is_wandb_available():
return _has_wandb
|
def set_seed(seed: int):
'\n Helper function for reproducible behavior to set the seed in ``random``, ``numpy``, ``torch`` and/or ``tf``\n (if installed).\n Args:\n seed (:obj:`int`): The seed to set.\n '
random.seed(seed)
np.random.seed(seed)
if is_torch_available():
import... |
class EvalPrediction(NamedTuple):
'\n Evaluation output (always contains labels), to be used to compute metrics.\n Parameters:\n predictions (:obj:`np.ndarray`): Predictions of the model.\n label_ids (:obj:`np.ndarray`): Targets to be matched.\n '
predictions: np.ndarray
label_ids: ... |
class PredictionOutput(NamedTuple):
predictions: np.ndarray
label_ids: Optional[np.ndarray]
metrics: Optional[Dict[(str, float)]]
|
class TrainOutput(NamedTuple):
global_step: int
training_loss: float
|
def default_logdir() -> str:
'\n Same default as PyTorch\n '
import socket
from datetime import datetime
current_time = datetime.now().strftime('%b%d_%H-%M-%S')
return os.path.join('runs', ((current_time + '_') + socket.gethostname()))
|
@dataclass
class TrainingArguments():
output_dir: str = field(metadata={'help': 'The output directory where the model predictions and checkpoints will be written.'})
overwrite_output_dir: bool = field(default=False, metadata={'help': 'Overwrite the content of the output directory.Use this to continue training... |
def a2c_step(policy_net, value_net, optimizer_policy, optimizer_value, states, actions, returns, advantages, l2_reg):
'update critic'
values_pred = value_net(states)
value_loss = (values_pred - returns).pow(2).mean()
for param in value_net.parameters():
value_loss += (param.pow(2).sum() * l2_r... |
def collect_samples(pid, queue, env, policy, custom_reward, mean_action, render, running_state, min_batch_size):
torch.randn(pid)
log = dict()
memory = Memory()
num_steps = 0
total_reward = 0
min_reward = 1000000.0
max_reward = (- 1000000.0)
total_c_reward = 0
min_c_reward = 100000... |
def merge_log(log_list):
log = dict()
log['total_reward'] = sum([x['total_reward'] for x in log_list])
log['num_episodes'] = sum([x['num_episodes'] for x in log_list])
log['num_steps'] = sum([x['num_steps'] for x in log_list])
log['avg_reward'] = (log['total_reward'] / log['num_episodes'])
log... |
class Agent():
def __init__(self, env, policy, device, custom_reward=None, mean_action=False, render=False, running_state=None, num_threads=1):
self.env = env
self.policy = policy
self.device = device
self.custom_reward = custom_reward
self.mean_action = mean_action
... |
def estimate_advantages(rewards, masks, values, gamma, tau, device):
(rewards, masks, values) = to_device(torch.device('cpu'), rewards, masks, values)
tensor_type = type(rewards)
deltas = tensor_type(rewards.size(0), 1)
advantages = tensor_type(rewards.size(0), 1)
prev_value = 0
prev_advantage... |
def ppo_step(policy_net, value_net, optimizer_policy, optimizer_value, optim_value_iternum, states, actions, returns, advantages, fixed_log_probs, clip_epsilon, l2_reg):
'update critic'
for _ in range(optim_value_iternum):
values_pred = value_net(states)
value_loss = (values_pred - returns).po... |
def conjugate_gradients(Avp_f, b, nsteps, rdotr_tol=1e-10):
x = zeros(b.size(), device=b.device)
r = b.clone()
p = b.clone()
rdotr = torch.dot(r, r)
for i in range(nsteps):
Avp = Avp_f(p)
alpha = (rdotr / torch.dot(p, Avp))
x += (alpha * p)
r -= (alpha * Avp)
... |
def line_search(model, f, x, fullstep, expected_improve_full, max_backtracks=10, accept_ratio=0.1):
fval = f(True).item()
for stepfrac in [(0.5 ** x) for x in range(max_backtracks)]:
x_new = (x + (stepfrac * fullstep))
set_flat_params_to(model, x_new)
fval_new = f(True).item()
... |
def trpo_step(policy_net, value_net, states, actions, returns, advantages, max_kl, damping, l2_reg, use_fim=True):
'update critic'
def get_value_loss(flat_params):
set_flat_params_to(value_net, tensor(flat_params))
for param in value_net.parameters():
if (param.grad is not None):
... |
def expert_reward(state, action):
state_action = tensor(np.hstack([state, action]), dtype=dtype)
with torch.no_grad():
return (- math.log(discrim_net(state_action)[0].item()))
|
def update_params(batch, i_iter):
states = torch.from_numpy(np.stack(batch.state)).to(dtype).to(device)
actions = torch.from_numpy(np.stack(batch.action)).to(dtype).to(device)
rewards = torch.from_numpy(np.stack(batch.reward)).to(dtype).to(device)
masks = torch.from_numpy(np.stack(batch.mask)).to(dtyp... |
def main_loop():
for i_iter in range(args.max_iter_num):
'generate multiple trajectories that reach the minimum batch_size'
discrim_net.to(torch.device('cpu'))
(batch, log) = agent.collect_samples(args.min_batch_size)
discrim_net.to(device)
t0 = time.time()
update_p... |
def main_loop():
num_steps = 0
for i_episode in count():
state = env.reset()
state = running_state(state)
reward_episode = 0
for t in range(10000):
state_var = tensor(state).unsqueeze(0).to(dtype)
action = policy_net(state_var)[0][0].detach().numpy()
... |
class Value(nn.Module):
def __init__(self, state_dim, hidden_size=(128, 128), activation='tanh'):
super().__init__()
if (activation == 'tanh'):
self.activation = torch.tanh
elif (activation == 'relu'):
self.activation = torch.relu
elif (activation == 'sigmo... |
class Discriminator(nn.Module):
def __init__(self, num_inputs, hidden_size=(128, 128), activation='tanh'):
super().__init__()
if (activation == 'tanh'):
self.activation = torch.tanh
elif (activation == 'relu'):
self.activation = torch.relu
elif (activation ... |
class Policy(nn.Module):
def __init__(self, state_dim, action_dim, hidden_size=(128, 128), activation='tanh', log_std=0):
super().__init__()
self.is_disc_action = False
if (activation == 'tanh'):
self.activation = torch.tanh
elif (activation == 'relu'):
sel... |
class DiscretePolicy(nn.Module):
def __init__(self, state_dim, action_num, hidden_size=(128, 128), activation='tanh'):
super().__init__()
self.is_disc_action = True
if (activation == 'tanh'):
self.activation = torch.tanh
elif (activation == 'relu'):
self.ac... |
def normal_entropy(std):
var = std.pow(2)
entropy = (0.5 + (0.5 * torch.log(((2 * var) * math.pi))))
return entropy.sum(1, keepdim=True)
|
def normal_log_density(x, mean, log_std, std):
var = std.pow(2)
log_density = ((((- (x - mean).pow(2)) / (2 * var)) - (0.5 * math.log((2 * math.pi)))) - log_std)
return log_density.sum(1, keepdim=True)
|
class Memory(object):
def __init__(self):
self.memory = []
def push(self, *args):
'Saves a transition.'
self.memory.append(Transition(*args))
def sample(self, batch_size=None):
if (batch_size is None):
return Transition(*zip(*self.memory))
else:
... |
def assets_dir():
return path.abspath(path.join(path.dirname(path.abspath(__file__)), '../assets'))
|
def to_device(device, *args):
return [x.to(device) for x in args]
|
def get_flat_params_from(model):
params = []
for param in model.parameters():
params.append(param.view((- 1)))
flat_params = torch.cat(params)
return flat_params
|
def set_flat_params_to(model, flat_params):
prev_ind = 0
for param in model.parameters():
flat_size = int(np.prod(list(param.size())))
param.data.copy_(flat_params[prev_ind:(prev_ind + flat_size)].view(param.size()))
prev_ind += flat_size
|
def get_flat_grad_from(inputs, grad_grad=False):
grads = []
for param in inputs:
if grad_grad:
grads.append(param.grad.grad.view((- 1)))
elif (param.grad is None):
grads.append(zeros(param.view((- 1)).shape))
else:
grads.append(param.grad.view((- 1))... |
def compute_flat_grad(output, inputs, filter_input_ids=set(), retain_graph=False, create_graph=False):
if create_graph:
retain_graph = True
inputs = list(inputs)
params = []
for (i, param) in enumerate(inputs):
if (i not in filter_input_ids):
params.append(param)
grads ... |
class RunningStat(object):
def __init__(self, shape):
self._n = 0
self._M = np.zeros(shape)
self._S = np.zeros(shape)
def push(self, x):
x = np.asarray(x)
assert (x.shape == self._M.shape)
self._n += 1
if (self._n == 1):
self._M[...] = x
... |
class ZFilter():
'\n y = (x-mean)/std\n using running estimates of mean,std\n '
def __init__(self, shape, demean=True, destd=True, clip=10.0):
self.demean = demean
self.destd = destd
self.clip = clip
self.rs = RunningStat(shape)
self.fix = False
def __cal... |
class RAdam(Optimizer):
'\n Implements RAdam optimization algorithm.\n Arguments:\n params: iterable of parameters to optimize or dicts defining\n parameter groups\n lr: learning rate (default: 1e-3)\n betas: coefficients used for computing\n running averages of gr... |
class DiffGrad(Optimizer):
'\n Implements DiffGrad algorithm.\n Arguments:\n params: iterable of parameters to optimize or dicts defining\n parameter groups\n lr: learning rate (default: 1e-3)\n betas: coefficients used for computing\n running averages of g... |
class SGDW(Optimizer):
'Implements SGDW algorithm. https://arxiv.org/abs/1711.05101\n Arguments:\n params: iterable of parameters to optimize or dicts defining\n parameter groups\n lr: learning rate (default: 1e-3)\n momentum: momentum factor (default: 0)\n weight_decay: ... |
class Dice(nn.Module):
'The Data Adaptive Activation Function in DIN,which can be viewed as a generalization of PReLu and can adaptively adjust the rectified point according to distribution of input data.\n\n Input shape:\n - 2 dims: [batch_size, embedding_size(features)]\n - 3 dims: [batch_size,... |
class Identity(nn.Module):
def __init__(self, **kwargs):
super(Identity, self).__init__()
def forward(self, X):
return X
|
def activation_layer(act_name, hidden_size=None, dice_dim=2):
'Construct activation layers\n\n Args:\n act_name: str or nn.Module, name of activation function\n hidden_size: int, used for Dice activation\n dice_dim: int, used for Dice activation\n Return:\n act_layer: activation ... |
class LocalActivationUnit(nn.Module):
'The LocalActivationUnit used in DIN with which the representation of\n user interests varies adaptively given different candidate items.\n\n Input shape\n - A list of two 3D tensor with shape: ``(batch_size, 1, embedding_size)`` and ``(batch_size, T, embedd... |
class DNN(nn.Module):
'The Multi Layer Percetron\n\n Input shape\n - nD tensor with shape: ``(batch_size, ..., input_dim)``. The most common situation would be a 2D input with shape ``(batch_size, input_dim)``.\n\n Output shape\n - nD tensor with shape: ``(batch_size, ..., hidden_size[-1])... |
class PredictionLayer(nn.Module):
'\n Arguments\n - **task**: str, ``"binary"`` for binary logloss or ``"regression"`` for regression loss\n - **use_bias**: bool.Whether add bias term or not.\n '
def __init__(self, task='binary', use_bias=True, **kwargs):
if (task not in ['b... |
class Conv2dSame(nn.Conv2d):
" Tensorflow like 'SAME' convolution wrapper for 2D convolutions\n "
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True):
super(Conv2dSame, self).__init__(in_channels, out_channels, kernel_size, stride, 0, di... |
class FM(nn.Module):
'Factorization Machine models pairwise (order-2) feature interactions\n without linear term and bias.\n Input shape\n - 3D tensor with shape: ``(batch_size,field_size,embedding_size)``.\n Output shape\n - 2D tensor with shape: ``(batch_size, 1)``.\n References... |
class BiInteractionPooling(nn.Module):
'Bi-Interaction Layer used in Neural FM,compress the\n pairwise element-wise product of features into one single vector.\n\n Input shape\n - A 3D tensor with shape:``(batch_size,field_size,embedding_size)``.\n\n Output shape\n - 3D tensor with sha... |
class SENETLayer(nn.Module):
'SENETLayer used in FiBiNET.\n Input shape\n - A list of 3D tensor with shape: ``(batch_size,filed_size,embedding_size)``.\n Output shape\n - A list of 3D tensor with shape: ``(batch_size,filed_size,embedding_size)``.\n Arguments\n - **filed_size** ... |
class BilinearInteraction(nn.Module):
'BilinearInteraction Layer used in FiBiNET.\n Input shape\n - A list of 3D tensor with shape: ``(batch_size,filed_size, embedding_size)``.\n Output shape\n - 3D tensor with shape: ``(batch_size,filed_size, embedding_size)``.\n Arguments\n -... |
class CIN(nn.Module):
'Compressed Interaction Network used in xDeepFM.\n Input shape\n - 3D tensor with shape: ``(batch_size,field_size,embedding_size)``.\n Output shape\n - 2D tensor with shape: ``(batch_size, featuremap_num)`` ``featuremap_num = sum(self.layer_size[:-1]) // 2 + self.lay... |
class AFMLayer(nn.Module):
'Attentonal Factorization Machine models pairwise (order-2) feature\n interactions without linear term and bias.\n Input shape\n - A list of 3D tensor with shape: ``(batch_size,1,embedding_size)``.\n Output shape\n - 2D tensor with shape: ``(batch_size, 1)``.\... |
class InteractingLayer(nn.Module):
'A Layer used in AutoInt that model the correlations between different feature fields by multi-head self-attention mechanism.\n Input shape\n - A 3D tensor with shape: ``(batch_size,field_size,embedding_size)``.\n Output shape\n - 3D tensor with s... |
class CrossNet(nn.Module):
'The Cross Network part of Deep&Cross Network model,\n which leans both low and high degree cross feature.\n Input shape\n - 2D tensor with shape: ``(batch_size, units)``.\n Output shape\n - 2D tensor with shape: ``(batch_size, units)``.\n Arguments\n ... |
class CrossNetMix(nn.Module):
'The Cross Network part of DCN-Mix model, which improves DCN-M by:\n 1 add MOE to learn feature interactions in different subspaces\n 2 add nonlinear transformations in low-dimensional space\n Input shape\n - 2D tensor with shape: ``(batch_size, units)``.\n ... |
class InnerProductLayer(nn.Module):
'InnerProduct Layer used in PNN that compute the element-wise\n product or inner product between feature vectors.\n Input shape\n - a list of 3D tensor with shape: ``(batch_size,1,embedding_size)``.\n Output shape\n - 3D tensor with shape: ``(batch_si... |
class OutterProductLayer(nn.Module):
'OutterProduct Layer used in PNN.This implemention is\n adapted from code that the author of the paper published on https://github.com/Atomu2014/product-nets.\n Input shape\n - A list of N 3D tensor with shape: ``(batch_size,1,embedding_size)``.\n Outpu... |
class ConvLayer(nn.Module):
'Conv Layer used in CCPM.\n\n Input shape\n - A list of N 3D tensor with shape: ``(batch_size,1,filed_size,embedding_size)``.\n Output shape\n - A list of N 3D tensor with shape: ``(batch_size,last_filters,pooling_size,embedding_size)``.\n Arguments... |
class SequencePoolingLayer(nn.Module):
'The SequencePoolingLayer is used to apply pooling operation(sum,mean,max) on variable-length sequence feature/multi-value feature.\n\n Input shape\n - A list of two tensor [seq_value,seq_len]\n\n - seq_value is a 3D tensor with shape: ``(batch_size, T, e... |
class AttentionSequencePoolingLayer(nn.Module):
'The Attentional sequence pooling operation used in DIN & DIEN.\n\n Arguments\n - **att_hidden_units**:list of positive integer, the attention net layer number and units in each layer.\n\n - **att_activation**: Activation function to use in ... |
class KMaxPooling(nn.Module):
'K Max pooling that selects the k biggest value along the specific axis.\n\n Input shape\n - nD tensor with shape: ``(batch_size, ..., input_dim)``.\n\n Output shape\n - nD tensor with shape: ``(batch_size, ..., output_dim)``.\n\n Arguments\n - **... |
class AGRUCell(nn.Module):
' Attention based GRU (AGRU)\n\n Reference:\n - Deep Interest Evolution Network for Click-Through Rate Prediction[J]. arXiv preprint arXiv:1809.03672, 2018.\n '
def __init__(self, input_size, hidden_size, bias=True):
super(AGRUCell, self).__init__()
... |
class AUGRUCell(nn.Module):
' Effect of GRU with attentional update gate (AUGRU)\n\n Reference:\n - Deep Interest Evolution Network for Click-Through Rate Prediction[J]. arXiv preprint arXiv:1809.03672, 2018.\n '
def __init__(self, input_size, hidden_size, bias=True):
super(AUGRUCel... |
class DynamicGRU(nn.Module):
def __init__(self, input_size, hidden_size, bias=True, gru_type='AGRU'):
super(DynamicGRU, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
if (gru_type == 'AGRU'):
self.rnn = AGRUCell(input_size, hidden_size, bi... |
def concat_fun(inputs, axis=(- 1)):
if (len(inputs) == 1):
return inputs[0]
else:
return torch.cat(inputs, dim=axis)
|
def slice_arrays(arrays, start=None, stop=None):
'Slice an array or list of arrays.\n\n This takes an array-like, or a list of\n array-likes, and outputs:\n - arrays[start:stop] if `arrays` is an array-like\n - [x[start:stop] for x in arrays] if `arrays` is a list\n\n Can also work on list/... |
class AFM(BaseModel):
'Instantiates the Attentional Factorization Machine architecture.\n\n :param linear_feature_columns: An iterable containing all the features used by linear part of the model.\n :param dnn_feature_columns: An iterable containing all the features used by deep part of the model.\n :par... |
class AutoInt(BaseModel):
'Instantiates the AutoInt Network architecture.\n\n :param linear_feature_columns: An iterable containing all the features used by linear part of the model.\n :param dnn_feature_columns: An iterable containing all the features used by deep part of the model.\n :param att_layer_n... |
class CCPM(BaseModel):
'Instantiates the Convolutional Click Prediction Model architecture.\n\n :param linear_feature_columns: An iterable containing all the features used by linear part of the model.\n :param dnn_feature_columns: An iterable containing all the features used by deep part of the model.\n ... |
class DCN(BaseModel):
'Instantiates the Deep&Cross Network architecture. Including DCN-V (parameterization=\'vector\')\n and DCN-M (parameterization=\'matrix\').\n\n :param linear_feature_columns: An iterable containing all the features used by linear part of the model.\n :param dnn_feature_columns: An i... |
class DCNMix(BaseModel):
'Instantiates the DCN-Mix model.\n\n :param linear_feature_columns: An iterable containing all the features used by linear part of the model.\n :param dnn_feature_columns: An iterable containing all the features used by deep part of the model.\n :param cross_num: positive integet... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.