|
| 1 | +import torch |
| 2 | +import torch.nn as nn |
| 3 | + |
| 4 | + |
| 5 | +class EmbeddingLayer(nn.Module): |
| 6 | + def __init__( |
| 7 | + self, |
| 8 | + num_feature_info, |
| 9 | + cat_feature_info, |
| 10 | + d_model, |
| 11 | + embedding_activation=nn.Identity(), |
| 12 | + layer_norm_after_embedding=False, |
| 13 | + use_cls=False, |
| 14 | + cls_position=0, |
| 15 | + cat_encoding="int", |
| 16 | + ): |
| 17 | + """ |
| 18 | + Embedding layer that handles numerical and categorical embeddings. |
| 19 | +
|
| 20 | + Parameters |
| 21 | + ---------- |
| 22 | + num_feature_info : dict |
| 23 | + Dictionary where keys are numerical feature names and values are their respective input dimensions. |
| 24 | + cat_feature_info : dict |
| 25 | + Dictionary where keys are categorical feature names and values are the number of categories for each feature. |
| 26 | + d_model : int |
| 27 | + Dimensionality of the embeddings. |
| 28 | + embedding_activation : nn.Module, optional |
| 29 | + Activation function to apply after embedding. Default is `nn.Identity()`. |
| 30 | + layer_norm_after_embedding : bool, optional |
| 31 | + If True, applies layer normalization after embeddings. Default is `False`. |
| 32 | + use_cls : bool, optional |
| 33 | + If True, includes a class token in the embeddings. Default is `False`. |
| 34 | + cls_position : int, optional |
| 35 | + Position to place the class token, either at the start (0) or end (1) of the sequence. Default is `0`. |
| 36 | +
|
| 37 | + Methods |
| 38 | + ------- |
| 39 | + forward(num_features=None, cat_features=None) |
| 40 | + Defines the forward pass of the model. |
| 41 | + """ |
| 42 | + super(EmbeddingLayer, self).__init__() |
| 43 | + |
| 44 | + self.d_model = d_model |
| 45 | + self.embedding_activation = embedding_activation |
| 46 | + self.layer_norm_after_embedding = layer_norm_after_embedding |
| 47 | + self.use_cls = use_cls |
| 48 | + self.cls_position = cls_position |
| 49 | + |
| 50 | + self.num_embeddings = nn.ModuleList( |
| 51 | + [ |
| 52 | + nn.Sequential( |
| 53 | + nn.Linear(input_shape, d_model, bias=False), |
| 54 | + self.embedding_activation, |
| 55 | + ) |
| 56 | + for feature_name, input_shape in num_feature_info.items() |
| 57 | + ] |
| 58 | + ) |
| 59 | + |
| 60 | + self.cat_embeddings = nn.ModuleList() |
| 61 | + for feature_name, num_categories in cat_feature_info.items(): |
| 62 | + if cat_encoding == "int": |
| 63 | + self.cat_embeddings.append( |
| 64 | + nn.Sequential( |
| 65 | + nn.Embedding(num_categories + 1, d_model), |
| 66 | + self.embedding_activation, |
| 67 | + ) |
| 68 | + ) |
| 69 | + elif cat_encoding == "one-hot": |
| 70 | + self.cat_embeddings.append( |
| 71 | + nn.Sequential( |
| 72 | + OneHotEncoding(num_categories), |
| 73 | + nn.Linear(num_categories, d_model, bias=False), |
| 74 | + self.embedding_activation, |
| 75 | + ) |
| 76 | + ) |
| 77 | + |
| 78 | + if self.use_cls: |
| 79 | + self.cls_token = nn.Parameter(torch.zeros(1, 1, d_model)) |
| 80 | + if layer_norm_after_embedding: |
| 81 | + self.embedding_norm = nn.LayerNorm(d_model) |
| 82 | + |
| 83 | + self.seq_len = len(self.num_embeddings) + len(self.cat_embeddings) |
| 84 | + |
| 85 | + def forward(self, num_features=None, cat_features=None): |
| 86 | + """ |
| 87 | + Defines the forward pass of the model. |
| 88 | +
|
| 89 | + Parameters |
| 90 | + ---------- |
| 91 | + num_features : Tensor, optional |
| 92 | + Tensor containing the numerical features. |
| 93 | + cat_features : Tensor, optional |
| 94 | + Tensor containing the categorical features. |
| 95 | +
|
| 96 | + Returns |
| 97 | + ------- |
| 98 | + Tensor |
| 99 | + The output embeddings of the model. |
| 100 | +
|
| 101 | + Raises |
| 102 | + ------ |
| 103 | + ValueError |
| 104 | + If no features are provided to the model. |
| 105 | + """ |
| 106 | + if self.use_cls: |
| 107 | + batch_size = ( |
| 108 | + cat_features[0].size(0) |
| 109 | + if cat_features != [] |
| 110 | + else num_features[0].size(0) |
| 111 | + ) |
| 112 | + cls_tokens = self.cls_token.expand(batch_size, -1, -1) |
| 113 | + |
| 114 | + if self.cat_embeddings and cat_features is not None: |
| 115 | + cat_embeddings = [ |
| 116 | + emb(cat_features[i]) for i, emb in enumerate(self.cat_embeddings) |
| 117 | + ] |
| 118 | + cat_embeddings = torch.stack(cat_embeddings, dim=1) |
| 119 | + cat_embeddings = torch.squeeze(cat_embeddings, dim=2) |
| 120 | + if self.layer_norm_after_embedding: |
| 121 | + cat_embeddings = self.embedding_norm(cat_embeddings) |
| 122 | + else: |
| 123 | + cat_embeddings = None |
| 124 | + |
| 125 | + if self.num_embeddings and num_features is not None: |
| 126 | + num_embeddings = [ |
| 127 | + emb(num_features[i]) for i, emb in enumerate(self.num_embeddings) |
| 128 | + ] |
| 129 | + num_embeddings = torch.stack(num_embeddings, dim=1) |
| 130 | + if self.layer_norm_after_embedding: |
| 131 | + num_embeddings = self.embedding_norm(num_embeddings) |
| 132 | + else: |
| 133 | + num_embeddings = None |
| 134 | + |
| 135 | + if cat_embeddings is not None and num_embeddings is not None: |
| 136 | + x = torch.cat([cat_embeddings, num_embeddings], dim=1) |
| 137 | + elif cat_embeddings is not None: |
| 138 | + x = cat_embeddings |
| 139 | + elif num_embeddings is not None: |
| 140 | + x = num_embeddings |
| 141 | + else: |
| 142 | + raise ValueError("No features provided to the model.") |
| 143 | + |
| 144 | + if self.use_cls: |
| 145 | + if self.cls_position == 0: |
| 146 | + x = torch.cat([cls_tokens, x], dim=1) |
| 147 | + elif self.cls_position == 1: |
| 148 | + x = torch.cat([x, cls_tokens], dim=1) |
| 149 | + else: |
| 150 | + raise ValueError( |
| 151 | + "Invalid cls_position value. It should be either 0 or 1." |
| 152 | + ) |
| 153 | + |
| 154 | + return x |
| 155 | + |
| 156 | + |
| 157 | +class OneHotEncoding(nn.Module): |
| 158 | + def __init__(self, num_categories): |
| 159 | + super(OneHotEncoding, self).__init__() |
| 160 | + self.num_categories = num_categories |
| 161 | + |
| 162 | + def forward(self, x): |
| 163 | + return torch.nn.functional.one_hot(x, num_classes=self.num_categories).float() |
0 commit comments