The rec
module¶
This module contains models are that specifically designed for recommendation systems.
While the rest of the models can be accessed from the pytorch_widedeep.models
module, models
in this module need to be specifically imported from the rec
module, e.g.:
from pytorch_widedeep.models.rec import DeepFactorizationMachine
The list of models here is not meant to be exhaustive, but it includes some common architectures such as factorization machines, field aware factorization machines or extreme factorization machines. More models will be added in the future.
DeepFactorizationMachine ¶
Bases: BaseTabularModelWithAttention
Deep Factorization Machine (DeepFM) for recommendation systems, which is an adaptation of 'Factorization Machines' by Steffen Rendle. Presented in 'DeepFM: A Factorization-Machine based Neural Network for CTR Prediction' by Huifeng Guo, Ruiming Tang, Yunming Yey, Zhenguo Li, Xiuqiang He. 2017.
The implementation in this library takes advantage of all the functionalities available to encode categorical and continuous features. The model can be used with only the factorization machine
Note that this class implements only the 'Deep' component of the model described in the paper. The linear component is not implemented 'internally' and, if one wants to include it, it can be easily added using the 'wide' (aka linear) component available in this library. See the examples in the examples folder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column_idx
|
Dict[str, int]
|
Dictionary mapping column names to their corresponding index. |
required |
num_factors
|
int
|
Number of factors for the factorization machine. |
required |
reduce_sum
|
bool
|
Whether to reduce the sum in the factorization machine output. |
True
|
cat_embed_input
|
Optional[List[Tuple[str, int]]]
|
List of tuples with categorical column names and number of unique values. |
None
|
cat_embed_dropout
|
Optional[float]
|
Categorical embeddings dropout. If |
None
|
use_cat_bias
|
Optional[bool]
|
Boolean indicating if bias will be used for the categorical embeddings.
If |
None
|
cat_embed_activation
|
Optional[str]
|
Activation function for the categorical embeddings, if any. Currently 'tanh', 'relu', 'leaky_relu' and 'gelu' are supported |
None
|
continuous_cols
|
Optional[List[str]]
|
List with the name of the numeric (aka continuous) columns |
None
|
cont_norm_layer
|
Optional[Literal['batchnorm', 'layernorm']]
|
Type of normalization layer applied to the continuous features.
Options are: 'layernorm' and 'batchnorm'. if |
None
|
embed_continuous_method
|
Optional[Literal['piecewise', 'periodic', 'standard']]
|
Method to use to embed the continuous features. Options are: 'standard', 'periodic' or 'piecewise'. The 'standard' embedding method is based on the FT-Transformer implementation presented in the paper: Revisiting Deep Learning Models for Tabular Data. The 'periodic' and_'piecewise'_ methods were presented in the paper: On Embeddings for Numerical Features in Tabular Deep Learning. Please, read the papers for details. |
'standard'
|
cont_embed_dropout
|
Optional[float]
|
Dropout for the continuous embeddings. If |
None
|
cont_embed_activation
|
Optional[str]
|
Activation function for the continuous embeddings if any. Currently
'tanh', 'relu', 'leaky_relu' and 'gelu' are supported.
If |
None
|
quantization_setup
|
Optional[Dict[str, List[float]]]
|
This parameter is used when the 'piecewise' method is used to embed the continuous cols. It is a dict where keys are the name of the continuous columns and values are lists with the boundaries for the quantization of the continuous_cols. See the examples for details. If If the 'piecewise' method is used, this parameter is required. |
None
|
n_frequencies
|
Optional[int]
|
This is the so called 'k' in their paper On Embeddings for Numerical Features in Tabular Deep Learning, and is the number of 'frequencies' that will be used to represent each continuous column. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
sigma
|
Optional[float]
|
This is the sigma parameter in the paper mentioned when describing the previous parameters and it is used to initialise the 'frequency weights'. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
share_last_layer
|
Optional[bool]
|
This parameter is not present in the before mentioned paper but it is implemented in
the official repo.
If |
None
|
full_embed_dropout
|
Optional[bool]
|
If |
None
|
mlp_hidden_dims
|
Optional[List[int]]
|
List with the number of neurons per dense layer in the mlp. |
None
|
mlp_activation
|
Optional[str]
|
Activation function for the dense layers of the MLP. Currently 'tanh', 'relu', 'leaky_relu' and 'gelu' are supported |
None
|
mlp_dropout
|
Optional[float]
|
float or List of floats with the dropout between the dense layers. e.g: [0.5,0.5] |
None
|
mlp_batchnorm
|
Optional[bool]
|
Boolean indicating whether or not batch normalization will be applied to the dense layers |
None
|
mlp_batchnorm_last
|
Optional[bool]
|
Boolean indicating whether or not batch normalization will be applied to the last of the dense layers |
None
|
mlp_linear_first
|
Optional[bool]
|
Boolean indicating the order of the operations in the dense
layer. If |
None
|
Attributes:
Name | Type | Description |
---|---|---|
mlp |
MLP
|
MLP component of the model if the mlp_hidden_dims parameter is not None. If None, the model will only return the output of the factorization machine. |
Examples:
>>> from typing import Dict, List, Tuple
>>> import torch
>>> from torch import Tensor
>>> from pytorch_widedeep.models.rec import DeepFactorizationMachine
>>> X = torch.randint(0, 10, (16, 2))
>>> column_idx: Dict[str, int] = {"col1": 0, "col2": 1}
>>> cat_embed_input: List[Tuple[str, int]] = [("col1", 10), ("col2", 10)]
>>> fm = DeepFactorizationMachine(
... column_idx=column_idx,
... num_factors=8,
... cat_embed_input=cat_embed_input,
... mlp_hidden_dims=[16, 8]
... )
>>> out = fm(X)
Source code in pytorch_widedeep/models/rec/deepfm.py
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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 |
|
DeepFieldAwareFactorizationMachine ¶
Bases: BaseTabularModelWithAttention
Deep Field Aware Factorization Machine (DeepFFM) for recommendation systems. Adaptation of the paper 'Field-aware Factorization Machines in a Real-world Online Advertising System', Juan et al. 2017.
This class implements only the 'Deep' component of the model described in the paper. The linear component is not implemented 'internally' and, if one wants to include it, it can be easily added using the 'wide'/linear component in this library. See the examples in the examples folder.
Note that in this case, only categorical features are accepted. This is because the embeddings of each feature will be learned using all other features. Therefore these embeddings have to be all of the same nature. This does not occur if we mix categorical and continuous features.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column_idx
|
Dict[str, int]
|
Dictionary mapping column names to their corresponding index. |
required |
num_factors
|
int
|
Number of factors for the factorization machine. |
required |
reduce_sum
|
bool
|
Whether to reduce the sum in the factorization machine output. |
True
|
cat_embed_input
|
Optional[List[Tuple[str, int]]]
|
List of tuples with categorical column names and number of unique values. |
None
|
cat_embed_dropout
|
Optional[float]
|
Categorical embeddings dropout. If |
None
|
use_cat_bias
|
Optional[bool]
|
Boolean indicating if bias will be used for the categorical embeddings.
If |
None
|
cat_embed_activation
|
Optional[str]
|
Activation function for the categorical embeddings, if any. Currently 'tanh', 'relu', 'leaky_relu' and 'gelu' are supported |
None
|
mlp_hidden_dims
|
Optional[List[int]]
|
List with the number of neurons per dense layer in the mlp. |
None
|
mlp_activation
|
Optional[str]
|
Activation function for the dense layers of the MLP. Currently 'tanh', 'relu', 'leaky_relu' and 'gelu' are supported |
None
|
mlp_dropout
|
Optional[float]
|
float or List of floats with the dropout between the dense layers. e.g: [0.5,0.5] |
None
|
mlp_batchnorm
|
Optional[bool]
|
Boolean indicating whether or not batch normalization will be applied to the dense layers |
None
|
mlp_batchnorm_last
|
Optional[bool]
|
Boolean indicating whether or not batch normalization will be applied to the last of the dense layers |
None
|
mlp_linear_first
|
Optional[bool]
|
Boolean indicating the order of the operations in the dense
layer. If |
None
|
Attributes:
Name | Type | Description |
---|---|---|
n_features |
int
|
Number of unique features/columns |
n_tokens |
int
|
Number of unique values (tokens) in the full dataset (corpus) |
encoders |
ModuleList
|
List of |
mlp |
Module
|
Multi-layer perceptron. If |
Examples:
>>> import torch
>>> from torch import Tensor
>>> from typing import Dict, List, Tuple
>>> from pytorch_widedeep.models.rec import DeepFieldAwareFactorizationMachine
>>> X = torch.randint(0, 10, (16, 2))
>>> column_idx: Dict[str, int] = {"col1": 0, "col2": 1}
>>> cat_embed_input: List[Tuple[str, int]] = [("col1", 10), ("col2", 10)]
>>> ffm = DeepFieldAwareFactorizationMachine(
... column_idx=column_idx,
... num_factors=4,
... cat_embed_input=cat_embed_input,
... mlp_hidden_dims=[16, 8]
... )
>>> output = ffm(X)
Source code in pytorch_widedeep/models/rec/deepffm.py
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 240 241 |
|
DeepInterestNetwork ¶
Bases: BaseWDModelComponent
Adaptation of the Deep Interest Network (DIN) for recommendation systems as described in the paper: 'Deep Interest Network for Click-Through Rate Prediction' by Guorui Zhou et al. 2018.
Note that all the categorical- and continuous-related parameters refer to the categorical and continuous columns that are not part of the sequential columns and will be treated as standard tabular data.
This model requires some specific data preparation that allows for quite a
lot of flexibility. Therefore, I have included a preprocessor
(DINPreprocessor
) in the preprocessing module that will take care of
the data preparation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column_idx
|
Dict[str, int]
|
Dictionary mapping column names to their corresponding index. |
required |
target_item_col
|
str
|
Name of the target item column. Note that this is not the target column. This algorithm relies on a sequence representation of interactions. The target item would be the next item in the sequence of interactions (e.g. item 6th in a sequence of 5 items), and our goal is to predict a given action on it. |
'target_item'
|
user_behavior_confiq
|
Tuple[List[str], int, int]
|
Configuration for user behavior sequence columns. Tuple containing:
- List of column names that correspond to the user behavior sequence |
required |
action_seq_config
|
Optional[Tuple[List[str], int]]
|
Configuration for a so-called action sequence columns (for example a
rating, or purchased/not-purchased, etc). Tuple containing: |
None
|
other_seq_cols_confiq
|
Optional[List[Tuple[List[str], int, int]]]
|
Configuration for other sequential columns. List of tuples containing: |
None
|
attention_unit_activation
|
Literal['prelu', 'dice']
|
Activation function to use in the attention unit. |
"prelu"
|
cat_embed_input
|
Optional[List[Tuple[str, int, int]]]
|
Configuration for other columns. List of tuples containing: Note: From here in advance the remaining parameters are related to the categorical and continuous columns that are not part of the sequential columns and will be treated as standard tabular data. |
None
|
cat_embed_dropout
|
Optional[float]
|
Categorical embeddings dropout. If |
None
|
use_cat_bias
|
Optional[bool]
|
Boolean indicating if bias will be used for the categorical embeddings.
If |
None
|
cat_embed_activation
|
Optional[str]
|
Activation function for the categorical embeddings, if any. Currently 'tanh', 'relu', 'leaky_relu' and 'gelu' are supported |
None
|
continuous_cols
|
Optional[List[str]]
|
List with the name of the numeric (aka continuous) columns |
None
|
cont_norm_layer
|
Optional[Literal['batchnorm', 'layernorm']]
|
Type of normalization layer applied to the continuous features.
Options are: 'layernorm' and 'batchnorm'. if |
None
|
embed_continuous
|
Optional[bool]
|
Boolean indicating if the continuous columns will be embedded using
one of the available methods: 'standard', 'periodic'
or 'piecewise'. If |
None
|
embed_continuous_method
|
Optional[Literal['piecewise', 'periodic', 'standard']]
|
Method to use to embed the continuous features. Options are: 'standard', 'periodic' or 'piecewise'. The 'standard' embedding method is based on the FT-Transformer implementation presented in the paper: Revisiting Deep Learning Models for Tabular Data. The 'periodic' and_'piecewise'_ methods were presented in the paper: On Embeddings for Numerical Features in Tabular Deep Learning. Please, read the papers for details. |
None
|
cont_embed_dim
|
Optional[int]
|
Size of the continuous embeddings. If the continuous columns are
embedded, |
None
|
cont_embed_dropout
|
Optional[float]
|
Dropout for the continuous embeddings. If |
None
|
cont_embed_activation
|
Optional[str]
|
Activation function for the continuous embeddings if any. Currently
'tanh', 'relu', 'leaky_relu' and 'gelu' are supported.
If |
None
|
quantization_setup
|
Optional[Dict[str, List[float]]]
|
This parameter is used when the 'piecewise' method is used to embed the continuous cols. It is a dict where keys are the name of the continuous columns and values are lists with the boundaries for the quantization of the continuous_cols. See the examples for details. If If the 'piecewise' method is used, this parameter is required. |
None
|
n_frequencies
|
Optional[int]
|
This is the so called 'k' in their paper On Embeddings for Numerical Features in Tabular Deep Learning, and is the number of 'frequencies' that will be used to represent each continuous column. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
sigma
|
Optional[float]
|
This is the sigma parameter in the paper mentioned when describing the previous parameters and it is used to initialise the 'frequency weights'. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
share_last_layer
|
Optional[bool]
|
This parameter is not present in the before mentioned paper but it is implemented in
the official repo.
If |
None
|
full_embed_dropout
|
Optional[bool]
|
If |
None
|
mlp_hidden_dims
|
Optional[List[int]]
|
List with the number of neurons per dense layer in the mlp. |
None
|
mlp_activation
|
Optional[str]
|
Activation function for the dense layers of the MLP. Currently 'tanh', 'relu', 'leaky_relu', 'gelu' and 'preglu' are supported |
None
|
mlp_dropout
|
Optional[float]
|
float or List of floats with the dropout between the dense layers. e.g: [0.5,0.5] |
None
|
mlp_batchnorm
|
Optional[bool]
|
Boolean indicating whether or not batch normalization will be applied to the dense layers |
None
|
mlp_batchnorm_last
|
Optional[bool]
|
Boolean indicating whether or not batch normalization will be applied to the last of the dense layers |
None
|
mlp_linear_first
|
Optional[bool]
|
Boolean indicating the order of the operations in the dense
layer. If |
None
|
Attributes:
Name | Type | Description |
---|---|---|
user_behavior_indexes |
List[int]
|
List with the indexes of the user behavior columns |
user_behavior_embed |
BaseTabularModelWithAttention
|
Embedding layer for the user |
action_seq_indexes |
List[int]
|
List with the indexes of the rating sequence columns if the action_seq_config parameter is not None |
action_embed |
BaseTabularModelWithAttention
|
Embedding layer for the rating sequence columns if the action_seq_config parameter is not None |
other_seq_cols_indexes |
Dict[str, List[int]]
|
Dictionary with the indexes of the other sequential columns if the other_seq_cols_confiq parameter is not None |
other_seq_cols_embed |
ModuleDict
|
Dictionary with the embedding layers for the other sequential columns if the other_seq_cols_confiq parameter is not None |
other_cols_idx |
List[int]
|
List with the indexes of the other columns if the other_cols_config parameter is not None |
other_col_embed |
BaseTabularModel
|
Embedding layer for the other columns if the other_cols_config parameter is not None |
mlp |
Optional[MLP]
|
MLP component of the model. If None, no MLP will be used. This should almost always be not None. |
Examples:
>>> import torch
>>> import numpy as np
>>> from torch import Tensor
>>> from typing import Dict, List, Tuple
>>> from pytorch_widedeep.models.rec import DeepInterestNetwork
>>> np_seed = np.random.seed(42)
>>> torch_seed = torch.manual_seed(42)
>>> num_users = 10
>>> num_items = 5
>>> num_contexts = 3
>>> seq_length = 3
>>> num_samples = 10
>>> user_ids = np.random.randint(0, num_users, num_samples)
>>> target_item_ids = np.random.randint(0, num_items, num_samples)
>>> context_ids = np.random.randint(0, num_contexts, num_samples)
>>> user_behavior = np.array(
... [
... np.random.choice(num_items, seq_length, replace=False)
... for _ in range(num_samples)
... ]
... )
>>> X_arr = np.column_stack((user_ids, target_item_ids, context_ids, user_behavior))
>>> X = torch.tensor(X_arr, dtype=torch.long)
>>> column_idx: Dict[str, int] = {
... "user_id": 0,
... "target_item": 1,
... "context": 2,
... "item_1": 3,
... "item_2": 4,
... "item_3": 5,
... }
>>> user_behavior_config: Tuple[List[str], int, int] = (
... ["item_1", "item_2", "item_3"],
... num_items,
... 8,
... )
>>> cat_embed_input: List[Tuple[str, int, int]] = [
... ("user_id", num_users, 8),
... ("context", num_contexts, 4),
... ]
>>> model = DeepInterestNetwork(
... column_idx=column_idx,
... target_item_col="target_item",
... user_behavior_confiq=user_behavior_config,
... cat_embed_input=cat_embed_input,
... mlp_hidden_dims=[16, 8],
... )
>>> output = model(X)
Source code in pytorch_widedeep/models/rec/din.py
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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 |
|
ExtremeDeepFactorizationMachine ¶
Bases: BaseTabularModelWithAttention
Adaptation of 'xDeepFM implementation: xDeepFM: Combining Explicit and Implicit Feature Interactions for Recommender Systems' by Jianxun Lian, Xiaohuan Zhou, Fuzheng Zhang, Zhongxia Chen, Xing Xie, Guangzhong Sun and Enhong Chen, 2018
The implementation in this library takes advantage of all the functionalities available to encode categorical and continuous features. The model can be used with only the factorization machine
Note that this class implements only the 'Deep' component of the model described in the paper. The linear component is not implemented 'internally' and, if one wants to include it, it can be easily added using the 'wide'/linear component in this library. See the examples in the examples folder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column_idx
|
Dict[str, int]
|
Dictionary mapping column names to their corresponding index. |
required |
input_dim
|
int
|
Embedding input dimensions |
required |
reduce_sum
|
bool
|
Whether to reduce the sum in the factorization machine output. |
True
|
cin_layer_dims
|
List[int]
|
List with the number of units per CIN layer. e.g: [128, 64] |
required |
cat_embed_input
|
Optional[List[Tuple[str, int]]]
|
List of tuples with categorical column names and number of unique values. |
None
|
cat_embed_dropout
|
Optional[float]
|
Categorical embeddings dropout. If |
None
|
use_cat_bias
|
Optional[bool]
|
Boolean indicating if bias will be used for the categorical embeddings.
If |
None
|
cat_embed_activation
|
Optional[str]
|
Activation function for the categorical embeddings, if any. Currently 'tanh', 'relu', 'leaky_relu' and 'gelu' are supported |
None
|
continuous_cols
|
Optional[List[str]]
|
List with the name of the numeric (aka continuous) columns |
None
|
cont_norm_layer
|
Optional[Literal['batchnorm', 'layernorm']]
|
Type of normalization layer applied to the continuous features.
Options are: 'layernorm' and 'batchnorm'. if |
None
|
embed_continuous_method
|
Optional[Literal['piecewise', 'periodic', 'standard']]
|
Method to use to embed the continuous features. Options are: 'standard', 'periodic' or 'piecewise'. The 'standard' embedding method is based on the FT-Transformer implementation presented in the paper: Revisiting Deep Learning Models for Tabular Data. The 'periodic' and_'piecewise'_ methods were presented in the paper: On Embeddings for Numerical Features in Tabular Deep Learning. Please, read the papers for details. |
'standard'
|
cont_embed_dropout
|
Optional[float]
|
Dropout for the continuous embeddings. If |
None
|
cont_embed_activation
|
Optional[str]
|
Activation function for the continuous embeddings if any. Currently
'tanh', 'relu', 'leaky_relu' and 'gelu' are supported.
If |
None
|
quantization_setup
|
Optional[Dict[str, List[float]]]
|
This parameter is used when the 'piecewise' method is used to embed the continuous cols. It is a dict where keys are the name of the continuous columns and values are lists with the boundaries for the quantization of the continuous_cols. See the examples for details. If If the 'piecewise' method is used, this parameter is required. |
None
|
n_frequencies
|
Optional[int]
|
This is the so called 'k' in their paper On Embeddings for Numerical Features in Tabular Deep Learning, and is the number of 'frequencies' that will be used to represent each continuous column. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
sigma
|
Optional[float]
|
This is the sigma parameter in the paper mentioned when describing the previous parameters and it is used to initialise the 'frequency weights'. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
share_last_layer
|
Optional[bool]
|
This parameter is not present in the before mentioned paper but it is implemented in
the official repo.
If |
None
|
full_embed_dropout
|
Optional[bool]
|
If |
None
|
mlp_hidden_dims
|
Optional[List[int]]
|
List with the number of neurons per dense layer in the mlp. |
None
|
mlp_activation
|
Optional[str]
|
Activation function for the dense layers of the MLP. Currently 'tanh', 'relu', 'leaky_relu' and 'gelu' are supported |
None
|
mlp_dropout
|
Optional[float]
|
float or List of floats with the dropout between the dense layers. e.g: [0.5,0.5] |
None
|
mlp_batchnorm
|
Optional[bool]
|
Boolean indicating whether or not batch normalization will be applied to the dense layers |
None
|
mlp_batchnorm_last
|
Optional[bool]
|
Boolean indicating whether or not batch normalization will be applied to the last of the dense layers |
None
|
mlp_linear_first
|
Optional[bool]
|
Boolean indicating the order of the operations in the dense
layer. If |
None
|
Attributes:
Name | Type | Description |
---|---|---|
n_features |
int
|
Number of unique features/columns |
cin |
CompressedInteractionNetwork
|
Instance of the |
mlp |
MLP
|
Instance of the |
Examples:
>>> import torch
>>> from pytorch_widedeep.models.rec import ExtremeDeepFactorizationMachine
>>> X_tab = torch.randint(0, 10, (16, 2))
>>> column_idx = {"col1": 0, "col2": 1}
>>> cat_embed_input = [("col1", 10), ("col2", 10)]
>>> xdeepfm = ExtremeDeepFactorizationMachine(
... column_idx=column_idx,
... input_dim=4,
... cin_layer_dims=[8, 16],
... cat_embed_input=cat_embed_input,
... mlp_hidden_dims=[16, 8]
... )
>>> output = xdeepfm(X_tab)
Source code in pytorch_widedeep/models/rec/xdeepfm.py
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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
|
AutoInt ¶
Bases: BaseTabularModelWithAttention
Defines an AutoInt
model that can be used as the deeptabular
component
of a Wide & Deep model or independently by itself.
This class implements the AutoInt: Automatic Feature Interaction Learning via Self-Attentive Neural Networks architecture, which learns feature interactions through multi-head self-attention networks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column_idx
|
Dict[str, int]
|
Dict containing the index of the columns that will be passed through
the |
required |
input_dim
|
int
|
Dimension of the input embeddings |
required |
num_heads
|
int
|
Number of attention heads |
4
|
num_layers
|
int
|
Number of interacting layers (attention + residual) |
2
|
reduction
|
Literal['mean', 'cat']
|
How to reduce the output of the attention layers. Options are: 'mean': mean of attention outputs 'cat': concatenation of attention outputs |
'mean'
|
cat_embed_input
|
Optional[List[Tuple[str, int]]]
|
List of Tuples with the column name, number of unique values and embedding dimension. e.g. [(education, 11, 32), ...] |
None
|
cat_embed_dropout
|
Optional[float]
|
Categorical embeddings dropout. If |
None
|
use_cat_bias
|
Optional[bool]
|
Boolean indicating if bias will be used for the categorical embeddings |
None
|
cat_embed_activation
|
Optional[str]
|
Activation function for the categorical embeddings |
None
|
continuous_cols
|
Optional[List[str]]
|
List with the name of the numeric (aka continuous) columns |
None
|
cont_norm_layer
|
Optional[Literal['batchnorm', 'layernorm']]
|
Type of normalization layer applied to the continuous features.
Options are: 'layernorm' and 'batchnorm'. if |
None
|
embed_continuous_method
|
Optional[Literal['standard', 'piecewise', 'periodic']]
|
Method to use to embed the continuous features. Options are: 'standard', 'periodic' or 'piecewise'. The 'standard' embedding method is based on the FT-Transformer implementation presented in the paper: Revisiting Deep Learning Models for Tabular Data. The 'periodic' and_'piecewise'_ methods were presented in the paper: On Embeddings for Numerical Features in Tabular Deep Learning. Please, read the papers for details. |
None
|
cont_embed_dropout
|
Optional[float]
|
Dropout for the continuous embeddings. If |
None
|
cont_embed_activation
|
Optional[str]
|
Activation function for the continuous embeddings if any. Currently
'tanh', 'relu', 'leaky_relu' and 'gelu' are supported.
If |
None
|
quantization_setup
|
Optional[Dict[str, List[float]]]
|
This parameter is used when the 'piecewise' method is used to embed the continuous cols. It is a dict where keys are the name of the continuous columns and values are lists with the boundaries for the quantization of the continuous_cols. See the examples for details. If If the 'piecewise' method is used, this parameter is required. |
None
|
n_frequencies
|
Optional[int]
|
This is the so called 'k' in their paper On Embeddings for Numerical Features in Tabular Deep Learning, and is the number of 'frequencies' that will be used to represent each continuous column. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
sigma
|
Optional[float]
|
This is the sigma parameter in the paper mentioned when describing the previous parameters and it is used to initialise the 'frequency weights'. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
share_last_layer
|
Optional[bool]
|
This parameter is not present in the before mentioned paper but it is implemented in
the official repo.
If |
None
|
full_embed_dropout
|
Optional[bool]
|
If |
None
|
Attributes:
Name | Type | Description |
---|---|---|
attention_layers |
ModuleList
|
List of multi-head attention layers |
Examples:
>>> import torch
>>> from pytorch_widedeep.models.rec import AutoInt
>>> X_tab = torch.cat((torch.empty(5, 4).random_(4), torch.rand(5, 1)), axis=1)
>>> colnames = ["a", "b", "c", "d", "e"]
>>> cat_embed_input = [(u, i, j) for u, i, j in zip(colnames[:4], [4] * 4, [8] * 4)]
>>> column_idx = {k: v for v, k in enumerate(colnames)}
>>> model = AutoInt(
... column_idx=column_idx,
... input_dim=32,
... cat_embed_input=cat_embed_input,
... continuous_cols=["e"],
... embed_continuous_method="standard",
... num_heads=4,
... num_layers=2
... )
>>> out = model(X_tab)
Source code in pytorch_widedeep/models/rec/autoint.py
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 |
|
AutoIntPlus ¶
Bases: BaseTabularModelWithAttention
Defines an AutoIntPlus
model that can be used as the deeptabular
component
of a Wide & Deep model or independently by itself.
This class implements an enhanced version of the AutoInt architecture, adding a parallel or stacked deep network and an optional gating mechanism to control the contribution of the attention-based and MLP branches.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column_idx
|
Dict[str, int]
|
Dict containing the index of the columns that will be passed through the model. Required to slice the tensors. e.g. {'education': 0, 'relationship': 1, 'workclass': 2, ...}. |
required |
input_dim
|
int
|
Dimension of the input embeddings |
required |
num_heads
|
int
|
Number of attention heads |
4
|
num_layers
|
int
|
Number of interacting layers (attention + residual) |
2
|
reduction
|
Literal['mean', 'cat']
|
How to reduce the output of the attention layers. Options are: 'mean': mean of attention outputs 'cat': concatenation of attention outputs |
'mean'
|
structure
|
Literal['stacked', 'parallel']
|
Structure of the model. Either 'parallel' or 'stacked'. If 'parallel', the output will be the concatenation of the attention and deep networks. If 'stacked', the attention output will be fed into the deep network. |
'parallel'
|
gated
|
bool
|
If True and structure is 'parallel', uses a gating mechanism to combine the attention and deep networks. Note: requires reduction='mean'. |
True
|
cat_embed_input
|
Optional[List[Tuple[str, int]]]
|
List of Tuples with the column name, number of unique values and embedding dimension. e.g. [(education, 11, 32), ...] |
None
|
cat_embed_dropout
|
Optional[float]
|
Categorical embeddings dropout. If |
None
|
use_cat_bias
|
Optional[bool]
|
Boolean indicating if bias will be used for the categorical embeddings |
None
|
cat_embed_activation
|
Optional[str]
|
Activation function for the categorical embeddings |
None
|
continuous_cols
|
Optional[List[str]]
|
List with the name of the numeric (aka continuous) columns |
None
|
cont_norm_layer
|
Optional[Literal['batchnorm', 'layernorm']]
|
Type of normalization layer applied to the continuous features.
Options are: 'layernorm' and 'batchnorm'. if |
None
|
embed_continuous_method
|
Optional[Literal['standard', 'piecewise', 'periodic']]
|
Method to use to embed the continuous features. Options are: 'standard', 'periodic' or 'piecewise'. The 'standard' embedding method is based on the FT-Transformer implementation presented in the paper: Revisiting Deep Learning Models for Tabular Data. The 'periodic' and_'piecewise'_ methods were presented in the paper: On Embeddings for Numerical Features in Tabular Deep Learning. Please, read the papers for details. |
None
|
cont_embed_dropout
|
Optional[float]
|
Dropout for the continuous embeddings. If |
None
|
cont_embed_activation
|
Optional[str]
|
Activation function for the continuous embeddings if any. Currently
'tanh', 'relu', 'leaky_relu' and 'gelu' are supported.
If |
None
|
quantization_setup
|
Optional[Dict[str, List[float]]]
|
This parameter is used when the 'piecewise' method is used to embed the continuous cols. It is a dict where keys are the name of the continuous columns and values are lists with the boundaries for the quantization of the continuous_cols. See the examples for details. If If the 'piecewise' method is used, this parameter is required. |
None
|
n_frequencies
|
Optional[int]
|
This is the so called 'k' in their paper On Embeddings for Numerical Features in Tabular Deep Learning, and is the number of 'frequencies' that will be used to represent each continuous column. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
sigma
|
Optional[float]
|
This is the sigma parameter in the paper mentioned when describing the previous parameters and it is used to initialise the 'frequency weights'. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
share_last_layer
|
Optional[bool]
|
This parameter is not present in the before mentioned paper but it is implemented in
the official repo.
If |
None
|
full_embed_dropout
|
Optional[bool]
|
If |
None
|
mlp_hidden_dims
|
List[int]
|
List with the number of neurons per dense layer in the mlp. |
[100, 100]
|
mlp_activation
|
str
|
Activation function for the dense layers of the MLP. Currently 'tanh', 'relu', 'leaky_relu' and 'gelu' are supported |
'relu'
|
mlp_dropout
|
Union[float, List[float]]
|
float or List of floats with the dropout between the dense layers. e.g: [0.5,0.5] |
0.1
|
mlp_batchnorm
|
bool
|
Boolean indicating whether or not batch normalization will be applied to the dense layers |
False
|
mlp_batchnorm_last
|
bool
|
Boolean indicating whether or not batch normalization will be applied to the last of the dense layers |
False
|
mlp_linear_first
|
bool
|
Boolean indicating the order of the operations in the dense
layer. If |
True
|
Attributes:
Name | Type | Description |
---|---|---|
attention_layers |
ModuleList
|
List of multi-head attention layers |
deep_network |
Module
|
The deep network component (MLP) |
gate |
(Module, optional)
|
The gating network (if gated=True) |
Examples:
>>> import torch
>>> from pytorch_widedeep.models.rec import AutoIntPlus
>>> X_tab = torch.cat((torch.empty(5, 4).random_(4), torch.rand(5, 1)), axis=1)
>>> colnames = ["a", "b", "c", "d", "e"]
>>> cat_embed_input = [(u, i, j) for u, i, j in zip(colnames[:4], [4] * 4, [8] * 4)]
>>> column_idx = {k: v for v, k in enumerate(colnames)}
>>> model = AutoIntPlus(
... column_idx=column_idx,
... input_dim=32,
... cat_embed_input=cat_embed_input,
... continuous_cols=["e"],
... embed_continuous_method="standard",
... num_heads=4,
... num_layers=2,
... structure="parallel",
... gated=True,
... mlp_hidden_dims=[64, 32]
... )
>>> out = model(X_tab)
Source code in pytorch_widedeep/models/rec/autoint_plus.py
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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
|
Transformer ¶
Bases: Module
Basic Encoder-Only Transformer Model for sequence
classification/regression. As all other models in the library this model
can be used as the deeptext
component of a Wide & Deep model or
independently by itself.
NOTE:
This model is introduced in the context of recommendation systems and
thought for sequences of any nature (e.g. items). It can, of course,
still be used for text.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vocab_size
|
int
|
Number of words in the vocabulary |
required |
input_dim
|
int
|
Dimension of the token embeddings Param aliases: |
required |
seq_length
|
int
|
Input sequence length |
required |
n_heads
|
int
|
Number of attention heads per Transformer block |
required |
n_blocks
|
int
|
Number of Transformer blocks |
required |
attn_dropout
|
float
|
Dropout that will be applied to the Multi-Head Attention layers |
0.1
|
ff_dropout
|
float
|
Dropout that will be applied to the FeedForward network |
0.1
|
ff_factor
|
int
|
Multiplicative factor applied to the first layer of the FF network in each Transformer block, This is normally set to 4. |
4
|
activation
|
str
|
Transformer Encoder activation function. 'tanh', 'relu', 'leaky_relu', 'gelu', 'geglu' and 'reglu' are supported |
'gelu'
|
padding_idx
|
int
|
index of the padding token in the padded-tokenised sequences. |
0
|
with_cls_token
|
bool
|
Boolean indicating if a |
False
|
with_pos_encoding
|
bool
|
Boolean indicating if positional encoding will be used |
True
|
pos_encoding_dropout
|
float
|
Positional encoding dropout |
0.1
|
pos_encoder
|
Optional[Module]
|
This model uses by default a standard positional encoding approach. However, any custom positional encoder can also be used and pass to the Transformer model via the 'pos_encoder' parameter |
None
|
Attributes:
Name | Type | Description |
---|---|---|
embedding |
Module
|
Standard token embedding layer |
pos_encoder |
Module
|
Positional Encoder |
encoder |
Module
|
Sequence of Transformer blocks |
Examples:
>>> import torch
>>> from pytorch_widedeep.models.rec import Transformer
>>> X = torch.cat((torch.zeros([5,1]), torch.empty(5, 4).random_(1,4)), axis=1)
>>> model = Transformer(vocab_size=4, seq_length=5, input_dim=8, n_heads=1, n_blocks=1)
>>> out = model(X)
Source code in pytorch_widedeep/models/rec/basic_transformer.py
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 |
|
DeepCrossNetwork ¶
Bases: BaseTabularModelWithoutAttention
Defines a DeepCrossNetwork
model that can be used as the deeptabular
component of a Wide & Deep model or independently by itself.
This class implements the Deep & Cross Network for Ad Click Predictions architecture, which automatically combines features to generate feature interactions in an explicit fashion and at each layer.
The cross layer implements the following equation:
where:
- \(\odot\) represents element-wise multiplication
- \(x_l\), \(x_{l+1}\) are the outputs from the \(l^{th}\) and \((l+1)^{th}\) cross layers
- \(W_l\), \(b_l\) are the weight and bias parameters
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column_idx
|
Dict[str, int]
|
Dict containing the index of the columns that will be passed through
the |
required |
n_cross_layers
|
int
|
Number of cross layers in the cross network |
3
|
cat_embed_input
|
Optional[List[Tuple[str, int, int]]]
|
List of Tuples with the column name, number of unique values and embedding dimension. e.g. [(education, 11, 32), ...] |
None
|
cat_embed_dropout
|
Optional[float]
|
Categorical embeddings dropout. If |
None
|
use_cat_bias
|
Optional[bool]
|
Boolean indicating if bias will be used for the categorical embeddings |
None
|
cat_embed_activation
|
Optional[str]
|
Activation function for the categorical embeddings |
None
|
continuous_cols
|
Optional[List[str]]
|
List with the name of the numeric (aka continuous) columns |
None
|
cont_norm_layer
|
Optional[Literal['batchnorm', 'layernorm']]
|
Type of normalization layer applied to the continuous features.
Options are: 'layernorm' and 'batchnorm'. if |
None
|
embed_continuous_method
|
Optional[Literal['standard', 'piecewise', 'periodic']]
|
Method to use to embed the continuous features. Options are: 'standard', 'periodic' or 'piecewise'. The 'standard' embedding method is based on the FT-Transformer implementation presented in the paper: Revisiting Deep Learning Models for Tabular Data. The 'periodic' and_'piecewise'_ methods were presented in the paper: On Embeddings for Numerical Features in Tabular Deep Learning. Please, read the papers for details. |
None
|
cont_embed_dropout
|
Optional[float]
|
Dropout for the continuous embeddings. If |
None
|
cont_embed_activation
|
Optional[str]
|
Activation function for the continuous embeddings if any. Currently
'tanh', 'relu', 'leaky_relu' and 'gelu' are supported.
If |
None
|
quantization_setup
|
Optional[Dict[str, List[float]]]
|
This parameter is used when the 'piecewise' method is used to embed the continuous cols. It is a dict where keys are the name of the continuous columns and values are lists with the boundaries for the quantization of the continuous_cols. See the examples for details. If If the 'piecewise' method is used, this parameter is required. |
None
|
n_frequencies
|
Optional[int]
|
This is the so called 'k' in their paper On Embeddings for Numerical Features in Tabular Deep Learning, and is the number of 'frequencies' that will be used to represent each continuous column. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
sigma
|
Optional[float]
|
This is the sigma parameter in the paper mentioned when describing the previous parameters and it is used to initialise the 'frequency weights'. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
share_last_layer
|
Optional[bool]
|
This parameter is not present in the before mentioned paper but it is implemented in
the official repo.
If |
None
|
full_embed_dropout
|
Optional[bool]
|
If |
None
|
mlp_hidden_dims
|
List[int]
|
List with the number of neurons per dense layer in the mlp. |
[200, 100]
|
mlp_activation
|
str
|
Activation function for the dense layers of the MLP. Currently 'tanh', 'relu', 'leaky_relu' and 'gelu' are supported |
'relu'
|
mlp_dropout
|
Union[float, List[float]]
|
float or List of floats with the dropout between the dense layers. e.g: [0.5,0.5] |
0.1
|
mlp_batchnorm
|
bool
|
Boolean indicating whether or not batch normalization will be applied to the dense layers |
False
|
mlp_batchnorm_last
|
bool
|
Boolean indicating whether or not batch normalization will be applied to the last of the dense layers |
False
|
mlp_linear_first
|
bool
|
Boolean indicating the order of the operations in the dense
layer. If |
True
|
Attributes:
Name | Type | Description |
---|---|---|
cross_network |
Module
|
The cross network component |
deep_network |
Module
|
The deep network component (MLP) |
Examples:
>>> import torch
>>> from pytorch_widedeep.models.rec import DeepCrossNetwork
>>> X_tab = torch.cat((torch.empty(5, 4).random_(4), torch.rand(5, 1)), axis=1)
>>> colnames = ["a", "b", "c", "d", "e"]
>>> cat_embed_input = [(u, i, j) for u, i, j in zip(colnames[:4], [4] * 4, [8] * 4)]
>>> column_idx = {k: v for v, k in enumerate(colnames)}
>>> model = DeepCrossNetwork(
... column_idx=column_idx,
... cat_embed_input=cat_embed_input,
... continuous_cols=["e"],
... n_cross_layers=2,
... mlp_hidden_dims=[16, 8]
... )
>>> out = model(X_tab)
Source code in pytorch_widedeep/models/rec/dcn.py
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 |
|
DeepCrossNetworkV2 ¶
Bases: BaseTabularModelWithoutAttention
Defines a DeepCrossNetworkV2
model that can be used as the deeptabular
component of a Wide & Deep model or independently by itself.
This class implements the DCN V2: Improved Deep & Cross Network and Practical Lessons for Web-scale Learning to Rank Systems architecture, which enhances the original DCN by introducing a more expressive cross network that uses multiple experts and matrix decomposition techniques to improve model capacity while maintaining computational efficiency.
The cross layer implements the following equation:
where:
- \(\odot\) represents element-wise multiplication
- \(U_l^i\), \(C_l^i\), \(V_l^i\) are the decomposed weight matrices for expert \(i\) at layer \(l\)
- \(g\) is the activation function (ReLU)
- \(b_l\) is the bias term
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column_idx
|
Dict[str, int]
|
Dict containing the index of the columns that will be passed through
the |
required |
num_cross_layers
|
int
|
Number of cross layers in the cross network |
2
|
low_rank
|
Optional[int]
|
Rank of the weight matrix decomposition. If None, full-rank weights are used |
None
|
num_experts
|
int
|
Number of expert networks in mixture of experts |
2
|
expert_dropout
|
float
|
Dropout rate for expert outputs |
0.0
|
structure
|
Literal['stacked', 'parallel']
|
Structure of the model. Either 'parallel' or 'stacked'. If 'parallel', the output will be the concatenation of the cross network and deep network outputs. If 'stacked', the cross network output will be fed into the deep network. |
'parallel'
|
cat_embed_input
|
Optional[List[Tuple[str, int, int]]]
|
List of Tuples with the column name, number of unique values and embedding dimension. e.g. [(education, 11, 32), ...] |
None
|
cat_embed_dropout
|
Optional[float]
|
Categorical embeddings dropout. If |
None
|
use_cat_bias
|
Optional[bool]
|
Boolean indicating if bias will be used for the categorical embeddings |
None
|
cat_embed_activation
|
Optional[str]
|
Activation function for the categorical embeddings |
None
|
continuous_cols
|
Optional[List[str]]
|
List with the name of the numeric (aka continuous) columns |
None
|
cont_norm_layer
|
Optional[Literal['batchnorm', 'layernorm']]
|
Type of normalization layer applied to the continuous features.
Options are: 'layernorm' and 'batchnorm'. if |
None
|
embed_continuous_method
|
Optional[Literal['standard', 'piecewise', 'periodic']]
|
Method to use to embed the continuous features. Options are: 'standard', 'periodic' or 'piecewise'. The 'standard' embedding method is based on the FT-Transformer implementation presented in the paper: Revisiting Deep Learning Models for Tabular Data. The 'periodic' and_'piecewise'_ methods were presented in the paper: On Embeddings for Numerical Features in Tabular Deep Learning. Please, read the papers for details. |
None
|
cont_embed_dropout
|
Optional[float]
|
Dropout for the continuous embeddings. If |
None
|
cont_embed_activation
|
Optional[str]
|
Activation function for the continuous embeddings if any. Currently
'tanh', 'relu', 'leaky_relu' and 'gelu' are supported.
If |
None
|
quantization_setup
|
Optional[Dict[str, List[float]]]
|
This parameter is used when the 'piecewise' method is used to embed the continuous cols. It is a dict where keys are the name of the continuous columns and values are lists with the boundaries for the quantization of the continuous_cols. See the examples for details. If If the 'piecewise' method is used, this parameter is required. |
None
|
n_frequencies
|
Optional[int]
|
This is the so called 'k' in their paper On Embeddings for Numerical Features in Tabular Deep Learning, and is the number of 'frequencies' that will be used to represent each continuous column. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
sigma
|
Optional[float]
|
This is the sigma parameter in the paper mentioned when describing the previous parameters and it is used to initialise the 'frequency weights'. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
share_last_layer
|
Optional[bool]
|
This parameter is not present in the before mentioned paper but it is implemented in
the official repo.
If |
None
|
full_embed_dropout
|
Optional[bool]
|
If |
None
|
mlp_hidden_dims
|
List[int]
|
List with the number of neurons per dense layer in the mlp. |
[200, 100]
|
mlp_activation
|
str
|
Activation function for the dense layers of the MLP. Currently 'tanh', 'relu', 'leaky_relu' and 'gelu' are supported |
'relu'
|
mlp_dropout
|
Union[float, List[float]]
|
float or List of floats with the dropout between the dense layers. e.g: [0.5,0.5] |
0.1
|
mlp_batchnorm
|
bool
|
Boolean indicating whether or not batch normalization will be applied to the dense layers |
False
|
mlp_batchnorm_last
|
bool
|
Boolean indicating whether or not batch normalization will be applied to the last of the dense layers |
False
|
mlp_linear_first
|
bool
|
Boolean indicating the order of the operations in the dense
layer. If |
True
|
Attributes:
Name | Type | Description |
---|---|---|
cross_network |
Module
|
The cross network component with mixture of experts |
deep_network |
Module
|
The deep network component (MLP) |
Examples:
>>> import torch
>>> from pytorch_widedeep.models.rec import DeepCrossNetworkV2
>>> X_tab = torch.cat((torch.empty(5, 4).random_(4), torch.rand(5, 1)), axis=1)
>>> colnames = ["a", "b", "c", "d", "e"]
>>> cat_embed_input = [(u, i, j) for u, i, j in zip(colnames[:4], [4] * 4, [8] * 4)]
>>> column_idx = {k: v for v, k in enumerate(colnames)}
>>> model = DeepCrossNetworkV2(
... column_idx=column_idx,
... cat_embed_input=cat_embed_input,
... continuous_cols=["e"],
... num_cross_layers=2,
... low_rank=32,
... num_experts=4,
... mlp_hidden_dims=[16, 8]
... )
>>> out = model(X_tab)
Source code in pytorch_widedeep/models/rec/dcnv2.py
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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 |
|
GatedDeepCrossNetwork ¶
Bases: BaseTabularModelWithoutAttention
Defines a GatedDeepCrossNetwork
model that can be used as the deeptabular
component of a Wide & Deep model or independently by itself.
This class implements the Gated Deep & Cross Network (GDCN) architecture as described in the paper Towards Deeper, Lighter and Interpretable Cross Network for CTR Prediction. The GDCN enhances the original DCN by introducing a gating mechanism in the cross network. The gating mechanism controls feature interactions by learning which interactions are more important.
The cross layer implements the following equation:
where:
- \(\odot\) represents element-wise multiplication
- \(W^c\) and \(W^g\) are the cross and gate weight matrices respectively
- \(\sigma\) is the sigmoid activation function
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column_idx
|
Dict[str, int]
|
Dict containing the index of the columns that will be passed through
the |
required |
num_cross_layers
|
int
|
Number of cross layers in the cross network |
3
|
structure
|
Literal['stacked', 'parallel']
|
Structure of the model. Either 'parallel' or 'stacked'. If 'parallel', the output will be the concatenation of the cross network and deep network outputs. If 'stacked', the cross network output will be fed into the deep network. |
'parallel'
|
cat_embed_input
|
Optional[List[Tuple[str, int, int]]]
|
List of Tuples with the column name, number of unique values and embedding dimension. e.g. [(education, 11, 32), ...] |
None
|
cat_embed_dropout
|
Optional[float]
|
Categorical embeddings dropout. If |
None
|
use_cat_bias
|
Optional[bool]
|
Boolean indicating if bias will be used for the categorical embeddings.
If |
None
|
cat_embed_activation
|
Optional[str]
|
Activation function for the categorical embeddings, if any. Currently 'tanh', 'relu', 'leaky_relu' and 'gelu' are supported |
None
|
continuous_cols
|
Optional[List[str]]
|
List with the name of the numeric (aka continuous) columns |
None
|
cont_norm_layer
|
Optional[Literal['batchnorm', 'layernorm']]
|
Type of normalization layer applied to the continuous features.
Options are: 'layernorm' and 'batchnorm'. if |
None
|
embed_continuous_method
|
Optional[Literal['standard', 'piecewise', 'periodic']]
|
Method to use to embed the continuous features. Options are: 'standard', 'periodic' or 'piecewise'. The 'standard' embedding method is based on the FT-Transformer implementation presented in the paper: Revisiting Deep Learning Models for Tabular Data. The 'periodic' and_'piecewise'_ methods were presented in the paper: On Embeddings for Numerical Features in Tabular Deep Learning. Please, read the papers for details. |
None
|
cont_embed_dropout
|
Optional[float]
|
Dropout for the continuous embeddings. If |
None
|
cont_embed_activation
|
Optional[str]
|
Activation function for the continuous embeddings if any. Currently
'tanh', 'relu', 'leaky_relu' and 'gelu' are supported.
If |
None
|
quantization_setup
|
Optional[Dict[str, List[float]]]
|
This parameter is used when the 'piecewise' method is used to embed the continuous cols. It is a dict where keys are the name of the continuous columns and values are lists with the boundaries for the quantization of the continuous_cols. See the examples for details. If If the 'piecewise' method is used, this parameter is required. |
None
|
n_frequencies
|
Optional[int]
|
This is the so called 'k' in their paper On Embeddings for Numerical Features in Tabular Deep Learning, and is the number of 'frequencies' that will be used to represent each continuous column. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
sigma
|
Optional[float]
|
This is the sigma parameter in the paper mentioned when describing the previous parameters and it is used to initialise the 'frequency weights'. See their Eq 2 in the paper for details. If the 'periodic' method is used, this parameter is required. |
None
|
share_last_layer
|
Optional[bool]
|
This parameter is not present in the before mentioned paper but it is implemented in
the official repo.
If |
None
|
full_embed_dropout
|
Optional[bool]
|
If |
None
|
mlp_hidden_dims
|
List[int]
|
List with the number of neurons per dense layer in the mlp. |
[200, 100]
|
mlp_activation
|
str
|
Activation function for the dense layers of the MLP. Currently 'tanh', 'relu', 'leaky_relu' and 'gelu' are supported |
'relu'
|
mlp_dropout
|
Union[float, List[float]]
|
float or List of floats with the dropout between the dense layers. e.g: [0.5,0.5] |
0.1
|
mlp_batchnorm
|
bool
|
Boolean indicating whether or not batch normalization will be applied to the dense layers |
False
|
mlp_batchnorm_last
|
bool
|
Boolean indicating whether or not batch normalization will be applied to the last of the dense layers |
False
|
mlp_linear_first
|
bool
|
Boolean indicating the order of the operations in the dense
layer. If |
True
|
Attributes:
Name | Type | Description |
---|---|---|
cross_network |
Module
|
The gated cross network component |
deep_network |
Module
|
The deep network component (MLP) |
Examples:
>>> import torch
>>> from pytorch_widedeep.models.rec import GatedDeepCrossNetwork
>>> X_tab = torch.cat((torch.empty(5, 4).random_(4), torch.rand(5, 1)), axis=1)
>>> colnames = ["a", "b", "c", "d", "e"]
>>> cat_embed_input = [(u, i, j) for u, i, j in zip(colnames[:4], [4] * 4, [8] * 4)]
>>> column_idx = {k: v for v, k in enumerate(colnames)}
>>> model = GatedDeepCrossNetwork(
... column_idx=column_idx,
... cat_embed_input=cat_embed_input,
... continuous_cols=["e"],
... num_cross_layers=2,
... mlp_hidden_dims=[16, 8]
... )
>>> out = model(X_tab)
Source code in pytorch_widedeep/models/rec/gdcn.py
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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 |
|