-
Notifications
You must be signed in to change notification settings - Fork 148
/
tabular.py
239 lines (205 loc) · 8.76 KB
/
tabular.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from typing import List, Optional, Tuple, Type, Union
from merlin.models.utils.doc_utils import docstring_parameter
from merlin.schema import Tags, TagsType
from merlin_standard_lib import Schema
from ..block.base import SequentialBlock
from ..block.mlp import MLPBlock
from ..tabular.base import (
TABULAR_MODULE_PARAMS_DOCSTRING,
AsTabular,
MergeTabular,
TabularAggregationType,
TabularModule,
TabularTransformationType,
)
from ..utils.torch_utils import get_output_sizes_from_schema
from .continuous import ContinuousFeatures
from .embedding import EmbeddingFeatures, PretrainedEmbeddingFeatures, SoftEmbeddingFeatures
TABULAR_FEATURES_PARAMS_DOCSTRING = """
continuous_module: TabularModule, optional
Module used to process continuous features.
categorical_module: TabularModule, optional
Module used to process categorical features.
text_embedding_module: TabularModule, optional
Module used to process text features.
"""
@docstring_parameter(
tabular_module_parameters=TABULAR_MODULE_PARAMS_DOCSTRING,
tabular_features_parameters=TABULAR_FEATURES_PARAMS_DOCSTRING,
)
class TabularFeatures(MergeTabular):
"""Input module that combines different types of features: continuous, categorical & text.
Parameters
----------
{tabular_features_parameters}
{tabular_module_parameters}
"""
CONTINUOUS_MODULE_CLASS: Type[TabularModule] = ContinuousFeatures
EMBEDDING_MODULE_CLASS: Type[TabularModule] = EmbeddingFeatures
SOFT_EMBEDDING_MODULE_CLASS: Type[TabularModule] = SoftEmbeddingFeatures
PRETRAINED_EMBEDDING_MODULE_CLASS: Type[TabularModule] = PretrainedEmbeddingFeatures
def __init__(
self,
continuous_module: Optional[TabularModule] = None,
categorical_module: Optional[TabularModule] = None,
pretrained_embedding_module: Optional[TabularModule] = None,
pre: Optional[TabularTransformationType] = None,
post: Optional[TabularTransformationType] = None,
aggregation: Optional[TabularAggregationType] = None,
schema: Optional[Schema] = None,
**kwargs,
):
to_merge = {}
if continuous_module:
to_merge["continuous_module"] = continuous_module
if categorical_module:
to_merge["categorical_module"] = categorical_module
if pretrained_embedding_module:
to_merge["pretrained_embedding_module"] = pretrained_embedding_module
assert to_merge != {}, "Please provide at least one input layer"
super(TabularFeatures, self).__init__(
to_merge, pre=pre, post=post, aggregation=aggregation, schema=schema, **kwargs
)
def project_continuous_features(
self, mlp_layers_dims: Union[List[int], int]
) -> "TabularFeatures":
"""Combine all concatenated continuous features with stacked MLP layers
Parameters
----------
mlp_layers_dims : Union[List[int], int]
The MLP layer dimensions
Returns
-------
TabularFeatures
Returns the same ``TabularFeatures`` object with the continuous features projected
"""
if isinstance(mlp_layers_dims, int):
mlp_layers_dims = [mlp_layers_dims]
continuous = self.to_merge["continuous_module"]
continuous.aggregation = "concat"
continuous = SequentialBlock(
continuous, MLPBlock(mlp_layers_dims), AsTabular("continuous_projection")
)
self.to_merge["continuous_module"] = continuous # type: ignore
return self
@classmethod
def from_schema( # type: ignore
cls,
schema: Schema,
continuous_tags: Optional[Union[TagsType, Tuple[Tags]]] = (Tags.CONTINUOUS,),
categorical_tags: Optional[Union[TagsType, Tuple[Tags]]] = (Tags.CATEGORICAL,),
pretrained_embeddings_tags: Optional[Union[TagsType, Tuple[Tags]]] = (Tags.EMBEDDING,),
aggregation: Optional[str] = None,
automatic_build: bool = True,
max_sequence_length: Optional[int] = None,
continuous_projection: Optional[Union[List[int], int]] = None,
continuous_soft_embeddings: bool = False,
**kwargs,
) -> "TabularFeatures":
"""Instantiates ``TabularFeatures`` from a ``DatasetSchema``
Parameters
----------
schema : DatasetSchema
Dataset schema
continuous_tags : Optional[Union[TagsType, Tuple[Tags]]], optional
Tags to filter the continuous features, by default Tags.CONTINUOUS
categorical_tags : Optional[Union[TagsType, Tuple[Tags]]], optional
Tags to filter the categorical features, by default Tags.CATEGORICAL
aggregation : Optional[str], optional
Feature aggregation option, by default None
automatic_build : bool, optional
Automatically infers input size from features, by default True
max_sequence_length : Optional[int], optional
Maximum sequence length for list features by default None
continuous_projection : Optional[Union[List[int], int]], optional
If set, concatenate all numerical features and project them by a number of MLP layers.
The argument accepts a list with the dimensions of the MLP layers, by default None
continuous_soft_embeddings : bool
Indicates if the soft one-hot encoding technique must be used to
represent continuous features, by default False
Returns
-------
TabularFeatures
Returns ``TabularFeatures`` from a dataset schema
"""
maybe_continuous_module, maybe_categorical_module, maybe_pretrained_module = (
None,
None,
None,
)
if continuous_tags:
if continuous_soft_embeddings:
maybe_continuous_module = cls.SOFT_EMBEDDING_MODULE_CLASS.from_schema(
schema,
tags=continuous_tags,
**kwargs,
)
else:
maybe_continuous_module = cls.CONTINUOUS_MODULE_CLASS.from_schema(
schema, tags=continuous_tags, **kwargs
)
if categorical_tags:
maybe_categorical_module = cls.EMBEDDING_MODULE_CLASS.from_schema(
schema, tags=categorical_tags, **kwargs
)
if pretrained_embeddings_tags:
maybe_pretrained_module = cls.PRETRAINED_EMBEDDING_MODULE_CLASS.from_schema(
schema, tags=pretrained_embeddings_tags, **kwargs
)
output = cls(
continuous_module=maybe_continuous_module,
categorical_module=maybe_categorical_module,
pretrained_embedding_module=maybe_pretrained_module,
aggregation=aggregation,
)
if automatic_build and schema:
output.build(
get_output_sizes_from_schema(
schema,
kwargs.get("batch_size", -1),
max_sequence_length=max_sequence_length,
),
schema=schema,
)
if continuous_projection:
if not automatic_build:
raise ValueError(
"Continuous feature projection can only be done with automatic_build"
)
output = output.project_continuous_features(continuous_projection)
return output
def forward_output_size(self, input_size):
output_sizes = {}
for in_layer in self.merge_values:
output_sizes.update(in_layer.forward_output_size(input_size))
return output_sizes
@property
def continuous_module(self) -> Optional[TabularModule]:
if "continuous_module" in self.to_merge:
return self.to_merge["continuous_module"]
return None
@property
def categorical_module(self) -> Optional[TabularModule]:
if "categorical_module" in self.to_merge:
return self.to_merge["categorical_module"]
return None
@property
def pretrained_module(self) -> Optional[TabularModule]:
if "pretrained_embedding_module" in self.to_merge:
return self.to_merge["pretrained_embedding_module"]
return None