The preprocessing module¶
This module contains the classes that are used to prepare the data before
being passed to the models. There is one Preprocessor per data mode or model
component (wide, deeptabular, deepimage and deeptext) with
the exception of the deeptext component. In this case, two processors are
available: one for the case when no Hugging Face model is used
(TextPreprocessor) and another one when a Hugging Face model is used
(HFPreprocessor).
WidePreprocessor ¶
Bases: BasePreprocessor
Preprocessor to prepare the wide input dataset
This Preprocessor prepares the data for the wide, linear component.
This linear model is implemented via an Embedding layer that is
connected to the output neuron. WidePreprocessor numerically
encodes all the unique values of all categorical columns wide_cols +
crossed_cols. See the Example below.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wide_cols
|
List[str]
|
List of strings with the name of the columns that will label
encoded and passed through the |
required |
crossed_cols
|
Optional[List[Tuple[str, str]]]
|
List of Tuples with the name of the columns that will be |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
wide_crossed_cols |
List
|
List with the names of all columns that will be label encoded |
encoding_dict |
Dict
|
Dictionary where the keys are the result of pasting |
inverse_encoding_dict |
Dict
|
the inverse encoding dictionary |
wide_dim |
int
|
Dimension of the wide model (i.e. dim of the linear layer) |
Examples:
>>> import pandas as pd
>>> from pytorch_widedeep.preprocessing import WidePreprocessor
>>> df = pd.DataFrame({'color': ['r', 'b', 'g'], 'size': ['s', 'n', 'l']})
>>> wide_cols = ['color']
>>> crossed_cols = [('color', 'size')]
>>> wide_preprocessor = WidePreprocessor(wide_cols=wide_cols, crossed_cols=crossed_cols)
>>> X_wide = wide_preprocessor.fit_transform(df)
>>> X_wide
array([[1, 4],
[2, 5],
[3, 6]])
>>> wide_preprocessor.encoding_dict
{'color_r': 1, 'color_b': 2, 'color_g': 3, 'color_size_r-s': 4, 'color_size_b-n': 5, 'color_size_g-l': 6}
>>> wide_preprocessor.inverse_transform(X_wide)
color color_size
0 r r-s
1 b b-n
2 g g-l
Source code in pytorch_widedeep/preprocessing/wide_preprocessor.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 | |
fit ¶
fit(df)
Fits the Preprocessor and creates required attributes
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input pandas dataframe |
required |
Returns:
| Type | Description |
|---|---|
WidePreprocessor
|
|
Source code in pytorch_widedeep/preprocessing/wide_preprocessor.py
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 | |
transform ¶
transform(df)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input pandas dataframe |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
transformed input dataframe |
Source code in pytorch_widedeep/preprocessing/wide_preprocessor.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | |
inverse_transform ¶
inverse_transform(encoded)
Takes as input the output from the transform method and it will
return the original values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoded
|
ndarray
|
numpy array with the encoded values that are the output from the
|
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Pandas dataframe with the original values |
Source code in pytorch_widedeep/preprocessing/wide_preprocessor.py
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 | |
fit_transform ¶
fit_transform(df)
Combines fit and transform
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input pandas dataframe |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
transformed input dataframe |
Source code in pytorch_widedeep/preprocessing/wide_preprocessor.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 | |
TabPreprocessor ¶
Bases: BasePreprocessor
Preprocessor to prepare the deeptabular component input dataset
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cat_embed_cols
|
Optional[Union[List[str], List[Tuple[str, int]]]]
|
List containing the name of the categorical columns that will be
represented by embeddings (e.g. ['education', 'relationship', ...]) or
a Tuple with the name and the embedding dimension (e.g.: [
('education',32), ('relationship',16), ...]). |
None
|
continuous_cols
|
Optional[List[str]]
|
List with the name of the continuous cols |
None
|
quantization_setup
|
Optional[Union[int, Dict[str, Union[int, List[float]]]]]
|
Continuous columns can be turned into categorical via |
None
|
cols_to_scale
|
Optional[Union[List[str], str]]
|
List with the names of the columns that will be standarised via
sklearn's |
None
|
auto_embed_dim
|
bool
|
Boolean indicating whether the embedding dimensions will be
automatically defined via rule of thumb. See |
True
|
embedding_rule
|
Literal[google, fastai_old, fastai_new]
|
If
|
'fastai_new'
|
default_embed_dim
|
int
|
Dimension for the embeddings if the embedding dimension is not
provided in the |
16
|
with_attention
|
bool
|
Boolean indicating whether the preprocessed data will be passed to an
attention-based model (more precisely a model where all embeddings
must have the same dimensions). If |
False
|
with_cls_token
|
bool
|
Boolean indicating if a |
False
|
shared_embed
|
bool
|
Boolean indicating if the embeddings will be "shared" when using
attention-based models. The idea behind |
False
|
verbose
|
int
|
|
1
|
scale
|
bool
|
|
False
|
already_standard
|
Optional[List[str]]
|
|
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs |
|
Attributes:
| Name | Type | Description |
|---|---|---|
cat_cols |
List[str]
|
List containing the names of the categorical columns after processing. |
cols_and_bins |
Optional[Dict[str, Union[int, List[float]]]]
|
Dictionary containing the quantization setup after processing if quantization is requested. This is derived from the quantization_setup parameter. |
quant_args |
Dict
|
Dictionary containing arguments passed to pandas.cut() function for quantization. |
scale_args |
Dict
|
Dictionary containing arguments passed to StandardScaler. |
label_encoder |
LabelEncoder
|
Instance of LabelEncoder used to encode categorical variables.
See |
cat_embed_input |
List
|
List of tuples with the column name, number of individual values for
that column and, if |
standardize_cols |
List
|
List of the columns that will be standardized. |
scaler |
StandardScaler
|
An instance of |
column_idx |
Dict
|
Dictionary where keys are column names and values are column indexes. This is necessary to slice tensors. |
quantizer |
Quantizer
|
An instance of |
is_fitted |
bool
|
Boolean indicating if the preprocessor has been fitted. |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from pytorch_widedeep.preprocessing import TabPreprocessor
>>> df = pd.DataFrame({'color': ['r', 'b', 'g'], 'size': ['s', 'n', 'l'], 'age': [25, 40, 55]})
>>> cat_embed_cols = [('color',5), ('size',5)]
>>> cont_cols = ['age']
>>> deep_preprocessor = TabPreprocessor(cat_embed_cols=cat_embed_cols, continuous_cols=cont_cols)
>>> X_tab = deep_preprocessor.fit_transform(df)
>>> deep_preprocessor.cat_embed_cols
[('color', 5), ('size', 5)]
>>> deep_preprocessor.column_idx
{'color': 0, 'size': 1, 'age': 2}
>>> cont_df = pd.DataFrame({"col1": np.random.rand(10), "col2": np.random.rand(10) + 1})
>>> cont_cols = ["col1", "col2"]
>>> tab_preprocessor = TabPreprocessor(continuous_cols=cont_cols, quantization_setup=3)
>>> ft_cont_df = tab_preprocessor.fit_transform(cont_df)
>>> # or...
>>> quantization_setup = {'col1': [0., 0.4, 1.], 'col2': [1., 1.4, 2.]}
>>> tab_preprocessor2 = TabPreprocessor(continuous_cols=cont_cols, quantization_setup=quantization_setup)
>>> ft_cont_df2 = tab_preprocessor2.fit_transform(cont_df)
Source code in pytorch_widedeep/preprocessing/tab_preprocessor.py
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 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 | |
fit ¶
fit(df)
Fits the Preprocessor and creates required attributes
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input pandas dataframe |
required |
Returns:
| Type | Description |
|---|---|
TabPreprocessor
|
|
Source code in pytorch_widedeep/preprocessing/tab_preprocessor.py
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 | |
transform ¶
transform(df)
Returns the processed dataframe as a np.ndarray
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input pandas dataframe |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
transformed input dataframe |
Source code in pytorch_widedeep/preprocessing/tab_preprocessor.py
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 | |
inverse_transform ¶
inverse_transform(encoded)
Takes as input the output from the transform method and it will
return the original values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoded
|
ndarray
|
array with the output of the |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Pandas dataframe with the original values |
Source code in pytorch_widedeep/preprocessing/tab_preprocessor.py
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 | |
fit_transform ¶
fit_transform(df)
Combines fit and transform
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input pandas dataframe |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
transformed input dataframe |
Source code in pytorch_widedeep/preprocessing/tab_preprocessor.py
476 477 478 479 480 481 482 483 484 485 486 487 488 489 | |
Quantizer ¶
Helper class to perform the quantization of continuous columns. It is
included in this docs for completion, since depending on the value of the
parameter 'quantization_setup' of the TabPreprocessor class, that
class might have an attribute of type Quantizer. However, this class is
designed to always run internally within the TabPreprocessor class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quantization_setup
|
Dict[str, Union[int, List[float]]]
|
Dictionary where the keys are the column names to quantize and the values are the either integers indicating the number of bins or a list of scalars indicating the bin edges. |
required |
Source code in pytorch_widedeep/preprocessing/tab_preprocessor.py
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 | |
TextPreprocessor ¶
Bases: BasePreprocessor
Preprocessor to prepare the deeptext input dataset
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text_col
|
str
|
column in the input dataframe containing the texts |
required |
max_vocab
|
int
|
Maximum number of tokens in the vocabulary |
30000
|
min_freq
|
int
|
Minimum frequency for a token to be part of the vocabulary |
5
|
maxlen
|
int
|
Maximum length of the tokenized sequences |
80
|
pad_first
|
bool
|
Indicates whether the padding index will be added at the beginning or the end of the sequences |
True
|
pad_idx
|
int
|
padding index. Fastai's Tokenizer leaves 0 for the 'unknown' token. |
1
|
already_processed
|
Optional[bool]
|
Boolean indicating if the sequence of elements is already processed or
prepared. If this is the case, this Preprocessor will simply tokenize
and pad the sequence. This parameter is thought for those cases where the input sequences are already fully processed or are directly not text (e.g. IDs) |
False
|
word_vectors_path
|
Optional[str]
|
Path to the pretrained word vectors |
None
|
n_cpus
|
Optional[int]
|
number of CPUs to used during the tokenization process |
None
|
verbose
|
int
|
Enable verbose output. |
1
|
Attributes:
| Name | Type | Description |
|---|---|---|
vocab |
Vocab
|
an instance of |
embedding_matrix |
ndarray
|
Array with the pretrained embeddings |
Examples:
>>> import pandas as pd
>>> from pytorch_widedeep.preprocessing import TextPreprocessor
>>> df_train = pd.DataFrame({'text_column': ["life is like a box of chocolates",
... "You never know what you're gonna get"]})
>>> text_preprocessor = TextPreprocessor(text_col='text_column', max_vocab=25, min_freq=1, maxlen=10)
>>> text_preprocessor.fit_transform(df_train)
The vocabulary contains 24 tokens
array([[ 1, 1, 1, 1, 10, 11, 12, 13, 14, 15],
[ 5, 9, 16, 17, 18, 9, 19, 20, 21, 22]], dtype=int32)
>>> df_te = pd.DataFrame({'text_column': ['you never know what is in the box']})
>>> text_preprocessor.transform(df_te)
array([[ 1, 1, 9, 16, 17, 18, 11, 0, 0, 13]], dtype=int32)
Source code in pytorch_widedeep/preprocessing/text_preprocessor.py
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 | |
fit ¶
fit(df)
Builds the vocabulary
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input pandas dataframe |
required |
Returns:
| Type | Description |
|---|---|
TextPreprocessor
|
|
Source code in pytorch_widedeep/preprocessing/text_preprocessor.py
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 | |
transform ¶
transform(df)
Returns the padded, 'numericalised' sequences
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input pandas dataframe |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Padded, 'numericalised' sequences |
Source code in pytorch_widedeep/preprocessing/text_preprocessor.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |
transform_sample ¶
transform_sample(text)
Returns the padded, 'numericalised' sequence
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
text to be tokenized and padded |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Padded, 'numericalised' sequence |
Source code in pytorch_widedeep/preprocessing/text_preprocessor.py
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
fit_transform ¶
fit_transform(df)
Combines fit and transform
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input pandas dataframe |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Padded, 'numericalised' sequences |
Source code in pytorch_widedeep/preprocessing/text_preprocessor.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 | |
inverse_transform ¶
inverse_transform(padded_seq)
Returns the original text plus the added 'special' tokens
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
padded_seq
|
ndarray
|
array with the output of the |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Pandas dataframe with the original text plus the added 'special' tokens |
Source code in pytorch_widedeep/preprocessing/text_preprocessor.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
HFPreprocessor ¶
Bases: BasePreprocessor
Text processor to prepare the deeptext input dataset that is a
wrapper around HuggingFace's tokenizers.
Following the main phylosophy of the pytorch-widedeep library, this
class is designed to be as flexible as possible. Therefore, it is coded
so that the user can use it as one would use any HuggingFace tokenizers,
or following the API call 'protocol' of the rest of the library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
The model name from the transformers library e.g. 'bert-base-uncased'. Currently supported models are those from the families: BERT, RoBERTa, DistilBERT, ALBERT and ELECTRA. |
required |
use_fast_tokenizer
|
bool
|
Whether to use the fast tokenizer from HuggingFace or not |
False
|
text_col
|
Optional[str]
|
The column in the input dataframe containing the text data. If this
tokenizer is used via the |
None
|
num_workers
|
Optional[int]
|
Number of workers to use when preprocessing the text data. If not
None, and |
None
|
preprocessing_rules
|
Optional[List[Callable[[str], str]]]
|
A list of functions to be applied to the text data before encoding. This can be useful to clean the text data before encoding. For example, removing html tags, special characters, etc. |
None
|
tokenizer_params
|
Optional[Dict[str, Any]]
|
Additional parameters to be passed to the HuggingFace's
|
None
|
encode_params
|
Optional[Dict[str, Any]]
|
Additional parameters to be passed to the |
None
|
**kwargs
|
Additional kwargs to be passed to the model, in particular to the
|
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
is_fitted |
bool
|
Boolean indicating if the preprocessor has been fitted. This is a HuggingFacea tokenizer, so it is always considered fitted and this attribute is manually set to True internally. This parameter exists for consistency with the rest of the library and because is needed for some functionality in the library. |
Examples:
>>> import pandas as pd
>>> from pytorch_widedeep.preprocessing import HFPreprocessor
>>> df = pd.DataFrame({"text": ["this is the first text", "this is the second text"]})
>>> hf_processor_1 = HFPreprocessor(model_name="bert-base-uncased", text_col="text")
>>> X_text_1 = hf_processor_1.fit_transform(df)
>>> texts = ["this is a new text", "this is another text"]
>>> hf_processor_2 = HFPreprocessor(model_name="bert-base-uncased")
>>> X_text_2 = hf_processor_2.encode(texts, max_length=10, padding="max_length", truncation=True)
Source code in pytorch_widedeep/preprocessing/hf_preprocessor.py
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 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 | |
encode ¶
encode(texts, **kwargs)
Encodes a list of texts. The method is a wrapper around the
batch_encode_plus method of the HuggingFace's tokenizer.
if 'use_fast_tokenizer' is True, the method will use the batch_encode_plus
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
texts
|
List[str]
|
List of texts to be encoded |
required |
**kwargs
|
Additional parameters to be passed to the |
{}
|
Returns:
| Type | Description |
|---|---|
array
|
The encoded texts |
Source code in pytorch_widedeep/preprocessing/hf_preprocessor.py
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 | |
decode ¶
decode(input_ids, skip_special_tokens)
Decodes a list of input_ids. The method is a wrapper around the
convert_ids_to_tokens and convert_tokens_to_string methods of the
HuggingFace's tokenizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_ids
|
NDArray[int64]
|
The input_ids to be decoded |
required |
skip_special_tokens
|
bool
|
Whether to skip the special tokens or not |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
The decoded texts |
Source code in pytorch_widedeep/preprocessing/hf_preprocessor.py
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 | |
fit ¶
fit(df)
This method is included for consistency with the rest of the library
in general and with the BasePreprocessor in particular. HuggingFace's
tokenizers and models are already trained. Therefore, the 'fit' method
here does nothing other than checking that the 'text_col' parameter is
not None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
The dataframe containing the text data in the column specified by the 'text_col' parameter |
required |
Source code in pytorch_widedeep/preprocessing/hf_preprocessor.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |
transform ¶
transform(df)
Encodes the text data in the input dataframe. This method simply
calls the encode method under the hood. Similar to the fit method,
this method is included for consistency with the rest of the library
in general and with the BasePreprocessor in particular.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
The dataframe containing the text data in the column specified by the 'text_col' parameter |
required |
Returns:
| Type | Description |
|---|---|
array
|
The encoded texts |
Source code in pytorch_widedeep/preprocessing/hf_preprocessor.py
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 | |
transform_sample ¶
transform_sample(text)
Encodes a single text sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text sample to be encoded |
required |
Returns:
| Type | Description |
|---|---|
array
|
The encoded text |
Source code in pytorch_widedeep/preprocessing/hf_preprocessor.py
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | |
fit_transform ¶
fit_transform(df)
Encodes the text data in the input dataframe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
The dataframe containing the text data in the column specified by the 'text_col' parameter |
required |
Returns:
| Type | Description |
|---|---|
array
|
The encoded texts |
Source code in pytorch_widedeep/preprocessing/hf_preprocessor.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
inverse_transform ¶
inverse_transform(input_ids, skip_special_tokens)
Decodes a list of input_ids. The method simply calls the decode method
under the hood.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_ids
|
NDArray[int64]
|
The input_ids to be decoded |
required |
skip_special_tokens
|
bool
|
Whether to skip the special tokens or not |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
The decoded texts |
Source code in pytorch_widedeep/preprocessing/hf_preprocessor.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | |
ImagePreprocessor ¶
Bases: BasePreprocessor
Preprocessor to prepare the deepimage input dataset.
The Preprocessing consists simply on resizing according to their aspect ratio
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_col
|
str
|
name of the column with the images filenames |
required |
img_path
|
str
|
path to the dicrectory where the images are stored |
required |
width
|
int
|
width of the resulting processed image. |
224
|
height
|
int
|
width of the resulting processed image. |
224
|
verbose
|
int
|
Enable verbose output. |
1
|
Attributes:
| Name | Type | Description |
|---|---|---|
aap |
AspectAwarePreprocessor
|
an instance of |
spp |
SimplePreprocessor
|
an instance of |
normalise_metrics |
Dict
|
Dict containing the normalisation metrics of the image dataset, i.e. mean and std for the R, G and B channels |
Examples:
>>> import pandas as pd
>>>
>>> from pytorch_widedeep.preprocessing import ImagePreprocessor
>>>
>>> path_to_image1 = 'tests/test_data_utils/images/galaxy1.png'
>>> path_to_image2 = 'tests/test_data_utils/images/galaxy2.png'
>>>
>>> df_train = pd.DataFrame({'images_column': [path_to_image1]})
>>> df_test = pd.DataFrame({'images_column': [path_to_image2]})
>>> img_preprocessor = ImagePreprocessor(img_col='images_column', img_path='.', verbose=0)
>>> resized_images = img_preprocessor.fit_transform(df_train)
>>> new_resized_images = img_preprocessor.transform(df_train)
NOTE:
Normalising metrics will only be computed when the fit_transform
method is run. Running transform only will not change the computed
metrics and running fit only simply instantiates the resizing
functions.
Source code in pytorch_widedeep/preprocessing/image_preprocessor.py
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 | |
transform ¶
transform(df)
Resizes the images to the input height and width.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input pandas dataframe with the |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Resized images to the input height and width |
Source code in pytorch_widedeep/preprocessing/image_preprocessor.py
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 | |
fit_transform ¶
fit_transform(df)
Combines fit and transform
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input pandas dataframe |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Resized images to the input height and width |
Source code in pytorch_widedeep/preprocessing/image_preprocessor.py
166 167 168 169 170 171 172 173 174 175 176 177 178 179 | |
DINPreprocessor ¶
Bases: BasePreprocessor
Preprocessor for Deep Interest Network (DIN) models.
This preprocessor handles the preparation of data for DIN models, including sequence building, label encoding, and handling of various types of input columns (categorical, continuous, and sequential).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id_col
|
str
|
Name of the column containing user IDs. |
required |
item_embed_col
|
Union[str, Tuple[str, int]]
|
Name of the column containing item IDs to be embedded, or a tuple of
(column_name, embedding_dim). If embedding_dim is not provided, it
will be automatically calculated using a rule of thumb specified by
|
required |
target_col
|
str
|
Name of the column containing the target variable. |
required |
max_seq_length
|
int
|
Maximum length of sequences to be created. |
required |
action_col
|
Optional[str]
|
Name of the column containing user actions (if applicable), for example a rating, or purchased/not-purchased, etc). This 'action_col' can also be the same as the 'target_col'. |
None
|
other_seq_embed_cols
|
Optional[List[str] | List[Tuple[str, int]]]
|
List of other columns to be treated as sequences. Each element in the list can be a string with the name of the column or a tuple with the name of the column and the embedding dimension. |
None
|
cat_embed_cols
|
Optional[Union[List[str], List[Tuple[str, int]]]]
|
This and the following parameters are identical to those used in the
TabPreprocessor. |
None
|
continuous_cols
|
Optional[List[str]]
|
List with the name of the continuous cols |
None
|
quantization_setup
|
Optional[Union[int, Dict[str, Union[int, List[float]]]]]
|
Continuous columns can be turned into categorical via |
None
|
cols_to_scale
|
Optional[Union[List[str], str]]
|
List with the names of the columns that will be standarised via
sklearn's |
None
|
auto_embed_dim
|
bool
|
Boolean indicating whether the embedding dimensions will be
automatically defined via rule of thumb. See |
True
|
embedding_rule
|
Literal['google', 'fastai_old', 'fastai_new']
|
If
|
'fastai_new'
|
default_embed_dim
|
int
|
Dimension for the embeddings if the embedding dimension is not
provided in the |
16
|
verbose
|
int
|
Verbosity level. |
1
|
scale
|
bool
|
|
False
|
already_standard
|
Optional[List[str]]
|
|
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs |
|
Attributes:
| Name | Type | Description |
|---|---|---|
is_fitted |
bool
|
Whether the preprocessor has been fitted. |
has_standard_tab_data |
bool
|
Whether the data includes standard tabular data. |
tab_preprocessor |
TabPreprocessor
|
Preprocessor for standard tabular data (if applicable). |
din_columns_idx |
Dict[str, int]
|
Dictionary mapping column names to their indices in the processed data. |
item_le |
LabelEncoder
|
Label encoder for item IDs. |
n_items |
int
|
Number of unique items. |
user_behaviour_config |
Tuple[List[str], int, int]
|
Configuration for user behavior sequences. |
action_le |
LabelEncoder
|
Label encoder for action column (if applicable). |
n_actions |
int
|
Number of unique actions (if applicable). |
action_seq_config |
Tuple[List[str], int]
|
Configuration for action sequences (if applicable). |
other_seq_le |
LabelEncoder
|
Label encoder for other sequence columns (if applicable). |
n_other_seq_cols |
Dict[str, int]
|
Number of unique values in each other sequence column. |
other_seq_config |
List[Tuple[List[str], int, int]]
|
Configuration for other sequence columns. |
Examples:
>>> import pandas as pd
>>> from pytorch_widedeep.preprocessing import DINPreprocessor
>>> data = {
... 'user_id': [1, 1, 1, 2, 2, 2, 3, 3, 3],
... 'item_id': [101, 102, 103, 101, 103, 104, 102, 103, 104],
... 'timestamp': [1, 2, 3, 1, 2, 3, 1, 2, 3],
... 'category': ['A', 'B', 'A', 'B', 'A', 'C', 'B', 'A', 'C'],
... 'price': [10.5, 15.0, 12.0, 10.5, 12.0, 20.0, 15.0, 12.0, 20.0],
... 'rating': [0, 1, 0, 1, 0, 1, 0, 1, 0]
... }
>>> df = pd.DataFrame(data)
>>> din_preprocessor = DINPreprocessor(
... user_id_col='user_id',
... item_embed_col='item_id',
... target_col='rating',
... max_seq_length=2,
... action_col='rating',
... other_seq_embed_cols=['category'],
... cat_embed_cols=['user_id'],
... continuous_cols=['price'],
... cols_to_scale=['price']
... )
>>> X, y = din_preprocessor.fit_transform(df)
Source code in pytorch_widedeep/preprocessing/din_preprocessor.py
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 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 | |
Chunked versions¶
Chunked versions of the preprocessors are also available. These are useful
when the data is too big to fit in memory. See also the load_from_folder
module in the library and the corresponding section here in the documentation.
Note that there is not a ChunkImagePreprocessor. This is because the
processing of the images will occur inside the ImageFromFolder class in
the load_from_folder module.
ChunkWidePreprocessor ¶
Bases: WidePreprocessor
Preprocessor to prepare the wide input dataset
This Preprocessor prepares the data for the wide, linear component.
This linear model is implemented via an Embedding layer that is
connected to the output neuron. ChunkWidePreprocessor numerically
encodes all the unique values of all categorical columns wide_cols +
crossed_cols. See the Example below.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wide_cols
|
List[str]
|
List of strings with the name of the columns that will label
encoded and passed through the |
required |
crossed_cols
|
Optional[List[Tuple[str, str]]]
|
List of Tuples with the name of the columns that will be |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
wide_crossed_cols |
List
|
List with the names of all columns that will be label encoded |
encoding_dict |
Dict
|
Dictionary where the keys are the result of pasting |
inverse_encoding_dict |
Dict
|
the inverse encoding dictionary |
wide_dim |
int
|
Dimension of the wide model (i.e. dim of the linear layer) |
Examples:
>>> import pandas as pd
>>> from pytorch_widedeep.preprocessing import ChunkWidePreprocessor
>>> chunk = pd.DataFrame({'color': ['r', 'b', 'g'], 'size': ['s', 'n', 'l']})
>>> wide_cols = ['color']
>>> crossed_cols = [('color', 'size')]
>>> chunk_wide_preprocessor = ChunkWidePreprocessor(wide_cols=wide_cols, crossed_cols=crossed_cols,
... n_chunks=1)
>>> X_wide = chunk_wide_preprocessor.fit_transform(chunk)
Source code in pytorch_widedeep/preprocessing/wide_preprocessor.py
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 | |
partial_fit ¶
partial_fit(chunk)
Fits the Preprocessor and creates required attributes
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk
|
DataFrame
|
Input pandas dataframe |
required |
Returns:
| Type | Description |
|---|---|
ChunkWidePreprocessor
|
|
Source code in pytorch_widedeep/preprocessing/wide_preprocessor.py
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 | |
fit ¶
fit(df)
Runs partial_fit. This is just to override the fit method in the base
class. This class is not designed or thought to run fit
Source code in pytorch_widedeep/preprocessing/wide_preprocessor.py
304 305 306 307 308 309 | |
ChunkTabPreprocessor ¶
Bases: TabPreprocessor
Preprocessor to prepare the deeptabular component input dataset
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_chunks
|
int
|
Number of chunks that the tabular dataset is divided by. |
required |
cat_embed_cols
|
Optional[Union[List[str], List[Tuple[str, int]]]]
|
List containing the name of the categorical columns that will be
represented by embeddings (e.g. ['education', 'relationship', ...]) or
a Tuple with the name and the embedding dimension (e.g.: [
('education',32), ('relationship',16), ...]). |
None
|
continuous_cols
|
Optional[List[str]]
|
List with the name of the continuous cols |
None
|
cols_and_bins
|
Optional[Dict[str, List[float]]]
|
Continuous columns can be turned into categorical via
|
None
|
cols_to_scale
|
Optional[Union[List[str], str]]
|
List with the names of the columns that will be standarised via
sklearn's |
None
|
default_embed_dim
|
int
|
Dimension for the embeddings if the embed_dim is not provided in the
|
16
|
with_attention
|
bool
|
Boolean indicating whether the preprocessed data will be passed to an
attention-based model (more precisely a model where all embeddings
must have the same dimensions). If |
False
|
with_cls_token
|
bool
|
Boolean indicating if a |
False
|
shared_embed
|
bool
|
Boolean indicating if the embeddings will be "shared" when using
attention-based models. The idea behind |
False
|
verbose
|
int
|
|
1
|
scale
|
bool
|
|
False
|
already_standard
|
Optional[List[str]]
|
|
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs |
|
Attributes:
| Name | Type | Description |
|---|---|---|
cat_cols |
List[str]
|
List containing the names of the categorical columns after processing. |
cols_and_bins |
Optional[Dict[str, Union[int, List[float]]]]
|
Dictionary containing the quantization setup after processing if quantization is requested. This is derived from the quantization_setup parameter. |
quant_args |
Dict
|
Dictionary containing arguments passed to pandas.cut() function for quantization. |
scale_args |
Dict
|
Dictionary containing arguments passed to StandardScaler. |
label_encoder |
LabelEncoder
|
Instance of LabelEncoder used to encode categorical variables.
See |
cat_embed_input |
List
|
List of tuples with the column name, number of individual values for
that column and, if |
standardize_cols |
List
|
List of the columns that will be standardized. |
scaler |
StandardScaler
|
An instance of |
column_idx |
Dict
|
Dictionary where keys are column names and values are column indexes. This is necessary to slice tensors. |
quantizer |
Quantizer
|
An instance of |
is_fitted |
bool
|
Boolean indicating if the preprocessor has been fitted. |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from pytorch_widedeep.preprocessing import ChunkTabPreprocessor
>>> np.random.seed(42)
>>> chunk_df = pd.DataFrame({'cat_col': np.random.choice(['A', 'B', 'C'], size=8),
... 'cont_col': np.random.uniform(1, 100, size=8)})
>>> cat_embed_cols = [('cat_col',4)]
>>> cont_cols = ['cont_col']
>>> tab_preprocessor = ChunkTabPreprocessor(
... n_chunks=1, cat_embed_cols=cat_embed_cols, continuous_cols=cont_cols
... )
>>> X_tab = tab_preprocessor.fit_transform(chunk_df)
>>> tab_preprocessor.cat_embed_cols
[('cat_col', 4)]
>>> tab_preprocessor.column_idx
{'cat_col': 0, 'cont_col': 1}
Source code in pytorch_widedeep/preprocessing/tab_preprocessor.py
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 | |
ChunkTextPreprocessor ¶
Bases: TextPreprocessor
Preprocessor to prepare the deeptext input dataset
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text_col
|
str
|
column in the input dataframe containing either the texts or the filenames where the text documents are stored |
required |
n_chunks
|
int
|
Number of chunks that the text dataset is divided by. |
required |
root_dir
|
Optional[str]
|
If 'text_col' contains the filenames with the text documents, this is the path to the directory where those documents are stored. |
None
|
max_vocab
|
int
|
Maximum number of tokens in the vocabulary |
30000
|
min_freq
|
int
|
Minimum frequency for a token to be part of the vocabulary |
5
|
maxlen
|
int
|
Maximum length of the tokenized sequences |
80
|
pad_first
|
bool
|
Indicates whether the padding index will be added at the beginning or the end of the sequences |
True
|
pad_idx
|
int
|
padding index. Fastai's Tokenizer leaves 0 for the 'unknown' token. |
1
|
word_vectors_path
|
Optional[str]
|
Path to the pretrained word vectors |
None
|
n_cpus
|
Optional[int]
|
number of CPUs to used during the tokenization process |
None
|
verbose
|
int
|
Enable verbose output. |
1
|
Attributes:
| Name | Type | Description |
|---|---|---|
vocab |
Vocab
|
an instance of |
embedding_matrix |
ndarray
|
Array with the pretrained embeddings if |
Examples:
>>> import pandas as pd
>>> from pytorch_widedeep.preprocessing import ChunkTextPreprocessor
>>> chunk_df = pd.DataFrame({'text_column': ["life is like a box of chocolates",
... "You never know what you're gonna get"]})
>>> chunk_text_preprocessor = ChunkTextPreprocessor(text_col='text_column', n_chunks=1,
... max_vocab=25, min_freq=1, maxlen=10, verbose=0, n_cpus=1)
>>> processed_chunk = chunk_text_preprocessor.fit_transform(chunk_df)
Source code in pytorch_widedeep/preprocessing/text_preprocessor.py
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 | |
ChunkHFPreprocessor ¶
Bases: HFPreprocessor
Text processor to prepare the deeptext input dataset that is a
wrapper around HuggingFace's tokenizers.
Hugginface Tokenizer's are already 'trained'. Therefore, unlike the
ChunkTextPreprocessor this is mostly identical to the HFPreprocessor
with the only difference that the class needs a 'text_col' parameter to
be passed. Also the parameter encode_params is not really optional when
using this class. It must be passed containing at least the
'max_length' encoding parameter. This is because we need to ensure that
all sequences have the same length when encoding in chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
The model name from the transformers library e.g. 'bert-base-uncased'. Currently supported models are those from the families: BERT, RoBERTa, DistilBERT, ALBERT and ELECTRA. |
required |
text_col
|
str
|
The column in the input dataframe containing the text data. When using
the |
required |
root_dir
|
Optional[str]
|
The root directory where the text files are located. This is only needed if the text data is stored in text files. If the text data is stored in a column in the input dataframe, this parameter is not needed. |
None
|
use_fast_tokenizer
|
bool
|
Whether to use the fast tokenizer from HuggingFace or not |
True
|
num_workers
|
Optional[int]
|
Number of workers to use when preprocessing the text data. If not
None, and |
None
|
preprocessing_rules
|
Optional[List[Callable[[str], str]]]
|
A list of functions to be applied to the text data before encoding. This can be useful to clean the text data before encoding. For example, removing html tags, special characters, etc. |
None
|
tokenizer_params
|
Optional[Dict[str, Any]]
|
Additional parameters to be passed to the HuggingFace's
|
None
|
encode_params
|
Optional[Dict[str, Any]]
|
Additional parameters to be passed to the |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
is_fitted |
bool
|
Boolean indicating if the preprocessor has been fitted. This is a HuggingFacea tokenizer, so it is always considered fitted and this attribute is manually set to True internally. This parameter exists for consistency with the rest of the library and because is needed for some functionality in the library. |
Source code in pytorch_widedeep/preprocessing/hf_preprocessor.py
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 | |