Pipeline
Polars Native Machine Learning Pipeline
Modules:
| Name | Description |
|---|---|
pipeline |
Machine Learning / Time series Pipelines with native Polars support. |
transforms |
This module provides classic ML dataset transforms. Note all functions here are single-use only, meaning |
pipeline
Machine Learning / Time series Pipelines with native Polars support.
Classes:
| Name | Description |
|---|---|
Blueprint |
Blueprints for a ML/data transformation pipeline. In other words, this is a description of |
ExprStep |
Container for either one of these polars transforms: |
PLContext |
|
Pipeline |
A ML/data transform pipeline. Pipelines should always come from the materialize call from a |
Blueprint
Blueprints for a ML/data transformation pipeline. In other words, this is a description of what a pipeline will be. No learning/fitting is done until self.materialize() is called.
If the input df is lazy, the pipeline will collect at the time of fit.
Note: although polars selectors work for most transformations and in most cases, it is still recommended that the user should use explicit expressions instead of selectors for most transformations.
Methods:
| Name | Description |
|---|---|
__init__ |
Creates a blueprint object. |
append_fit_func |
Adds a custom transform that requires a fit step in the blueprint. |
append_step_from_dict |
Append a step to the blueprint by taking in a dictionary with keys |
cast_bools |
Cast all boolean columns in the dataframe to the given type. |
center |
Centers the columns by subtracting each with its mean. |
conditional_impute |
Conditionally imputes values in the given columns. This transform will collect if input is lazy. |
drop |
Drops the columns from the dataset. |
explode |
Transform that represents |
filter |
Filters on the dataframe using native polars expressions or SQL boolean expressions. |
fit |
Alias for self.materialize() |
group_by_agg |
Performs a group by and agg on the data. |
group_by_dynamic_agg |
See polars group_by_dynamic documentation for an explanation on the input arguments. |
impute |
Imputes null values in the given columns. Note: this doesn't fill NaN. If filling for NaN is needed, |
int_to_float |
Maps all integer columns to float. |
iv_encode |
Use Information Value to encode a discrete variable x with respect to target. This assumes x |
linear_impute |
Imputes the target column by training a simple linear regression using the other features. This will |
materialize |
Materialize the blueprint, which means that it will fit and learn all the paramters needed. |
nan_to_null |
Maps NaN values in all columns to null. |
one_hot_encode |
Find the unique values in the string/categorical columns and one-hot encode them. This will NOT |
ordinal_encode |
Find the unique values in the string/categorical columns and one-hot encode them. This will NOT |
polynomial_features |
Generates polynomial combinations out of the features given, at the given degree. |
rank_hot_encode |
Given a ranking, e.g. ["bad", "neutral", "good"], where "bad", "neutral" and "good" are values coming |
rename |
Renames the columns by the mapping. |
robust_scale |
Performs robust scaling on the given columns |
scale |
Scales values in the given columns. |
select |
Selects the columns from the dataset. |
select_by_std |
Fits and keeps columns that have standard deviation between |
sort |
Sorts the dataframe by the columns. |
sql_transform |
Runs the SQL on the dataframe when it reaches this step. The user must ensure that |
target_encode |
Target encode the given variables. |
transform |
Fits the blueprint with the dataframe that it is initialized with, and |
winsorize |
Learns the lower and upper percentile from the columns, then clip each end at those values. |
with_columns |
Run Polars with_columns for the expressions. |
woe_encode |
Use Weight of Evidence to encode a discrete variable x with respect to target. This assumes x |
Source code in python/polars_ds/pipeline/pipeline.py
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 712 713 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 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 | |
__init__(df, name='test', target=None, exclude=None, lowercase=False, uppercase=False)
Creates a blueprint object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager Polars dataframe |
required |
name
|
str
|
Name of the blueprint. |
'test'
|
target
|
str | None
|
Optionally indicate the target column in the ML pipeline. This will automatically prevent any transformation from changing the target column. (To be implemented: this should also automatically fill any transformation that requires a target name) |
None
|
exclude
|
List[str] | None
|
Any other column to exclude from global transformation. Note: this is only needed if you are not specifiying the exact columns to transform. E.g. when you are using a selector like cs.numeric() for all numeric columns. If this is the case and target is not set nor excluded, then the transformation may be applied to the target as well, which is not desired in most cases. Therefore, it is highly recommended you initialize with target name. |
None
|
lowercase
|
bool
|
Whether to insert a lowercase column name step before all other transformations. This takes precedence over uppercase. |
False
|
uppercase
|
bool
|
Whether to insert a uppercase column name step before all other transformations. This only happens if lowercase is False |
False
|
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
append_fit_func(func, cols, **kwargs)
Adds a custom transform that requires a fit step in the blueprint.
Any custom function must satistfy the following function signature: my_func(df:Union[pl.DataFrame, pl.LazyFrame], cols: List[str], ...) -> List[pl.Expr] where ... means kwargs. The fit step "learns" the parameters needed to translate the transform into concrete expressions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
A callable with signature (pl.DataFrame | pl.LazyFrame, cols: List[str], ...) -> ExprTransform, |
required | |
cols
|
IntoExprColumn
|
The columns to be fed into the func. Note that in func's signature, a list of strings should be expected. But here, cols can be any polars selector expression. The reason is that during "fit", cols is turned into concrete column names. |
required |
**kwargs
|
Any other arguments to func must be passed as kwargs |
{}
|
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
append_step_from_dict(dictionary)
Append a step to the blueprint by taking in a dictionary with keys name, args, and kwargs, where
the value of args must be a List[Any] and the value of kwargs must be a dict[str, Any].
Source code in python/polars_ds/pipeline/pipeline.py
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 | |
cast_bools(dtype=pl.UInt8)
Cast all boolean columns in the dataframe to the given type.
Source code in python/polars_ds/pipeline/pipeline.py
367 368 369 370 371 372 | |
center(cols)
Centers the columns by subtracting each with its mean.
Paramters
cols Any Polars expression that can be understood as columns.
Source code in python/polars_ds/pipeline/pipeline.py
500 501 502 503 504 505 506 507 508 509 510 | |
conditional_impute(rules_dict, method='mean')
Conditionally imputes values in the given columns. This transform will collect if input is lazy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rules_dict
|
Dict[str, str | Expr]
|
Dictionary where keys are column names (must be string), and values are SQL/Polars Conditions that when true, those values in the column will be imputed, and the value to impute will be learned on the data where the condition is false. |
required |
method
|
SimpleImputeMethod
|
One of |
'mean'
|
Source code in python/polars_ds/pipeline/pipeline.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 | |
drop(cols)
Drops the columns from the dataset.
Paramters
cols Any Polars expression that can be understood as columns.
Source code in python/polars_ds/pipeline/pipeline.py
608 609 610 611 612 613 614 615 616 617 618 | |
explode(columns)
Transform that represents df.explode(columns)
Source code in python/polars_ds/pipeline/pipeline.py
896 897 898 899 900 901 902 903 904 905 906 907 908 | |
filter(by)
Filters on the dataframe using native polars expressions or SQL boolean expressions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
by
|
str | Expr
|
Native polars boolean expression or SQL strings |
required |
Source code in python/polars_ds/pipeline/pipeline.py
337 338 339 340 341 342 343 344 345 346 347 348 349 | |
fit(X=None, y=None, **kwargs)
Alias for self.materialize()
Source code in python/polars_ds/pipeline/pipeline.py
1072 1073 1074 1075 1076 | |
group_by_agg(by, agg, maintain_order=False)
Performs a group by and agg on the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
by
|
IntoExprColumn
|
The columns to group by |
required |
agg
|
List[Expr]
|
The aggregation functions to run |
required |
maintain_order
|
bool
|
Whether to maintain the group by order |
False
|
Source code in python/polars_ds/pipeline/pipeline.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 | |
group_by_dynamic_agg(index_column, agg, every, period=None, offset=None, include_boundaries=False, closed='left', label='left', group_by=None, start_by='window')
See polars group_by_dynamic documentation for an explanation on the input arguments.
https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.group_by_dynamic.html#polars.DataFrame.group_by_dynamic
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
impute(cols, method='mean')
Imputes null values in the given columns. Note: this doesn't fill NaN. If filling for NaN is needed, please manually do that.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cols
|
IntoExprColumn
|
Any Polars expression that can be understood as columns. |
required |
method
|
SimpleImputeMethod
|
One of |
'mean'
|
Source code in python/polars_ds/pipeline/pipeline.py
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | |
int_to_float(f32=True)
Maps all integer columns to float.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f32
|
bool
|
If true, map all integer columns to f32 columns. Otherwise they will be casted to f64 columns. |
True
|
Source code in python/polars_ds/pipeline/pipeline.py
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | |
iv_encode(cols=None, target=None, default=None)
Use Information Value to encode a discrete variable x with respect to target. This assumes x is discrete and castable to String. A value of 1 is added to all events/non-events (goods/bads) to smooth the computation.
Note: nulls will be encoded as well.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cols
|
IntoExprColumn | None
|
Any Polars expression that can be understood as columns. Columns of type != string/categorical will not produce any expression. If None, all string/categorical columns will be used. |
None
|
target
|
str | Expr | None
|
The target column |
None
|
default
|
EncoderDefaultStrategy | float | None
|
If a new value is encountered during transform (unseen in training dataset), it will be mapped to default.
If this is a string, it can be |
None
|
Reference
https://www.listendata.com/2015/03/weight-of-evidence-woe-and-information.html
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
linear_impute(features, target=None, add_bias=False)
Imputes the target column by training a simple linear regression using the other features. This will cast the target column to f64.
Note: The linear regression will skip nulls whenever there is a null in the features or in the target. Additionally, if NaN or Inf exists in data, the linear regression result may be invalid or an error will be thrown. It is recommended to use this only after imputing and dealing with NaN and Infs for all feature columns first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
IntoExprColumn
|
Any Polars expression that can be understood as numerical columns which will be used as features |
required |
target
|
str | Expr | None
|
The target column |
None
|
add_bias
|
bool
|
Whether to add a bias term to the linear regression |
False
|
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
materialize(return_df=False, **kwargs)
Materialize the blueprint, which means that it will fit and learn all the paramters needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
return_df
|
bool
|
If true, return the entire query plan, a lazy df, together with the Pipeline object |
False
|
**kwargs
|
All kwargs here will be passed to polars.LazyFrame.collect() |
{}
|
Source code in python/polars_ds/pipeline/pipeline.py
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 1065 1066 1067 1068 1069 1070 | |
nan_to_null()
Maps NaN values in all columns to null.
Source code in python/polars_ds/pipeline/pipeline.py
415 416 417 418 419 420 | |
one_hot_encode(cols=None, separator='_', drop_first=False, drop_cols=True)
Find the unique values in the string/categorical columns and one-hot encode them. This will NOT consider nulls as one of the unique values. Append pl.col(c).is_null().cast(pl.UInt8) expression to the pipeline if you want null indicators.
If cols is None, this will pick all string and categorical columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cols
|
IntoExprColumn | None
|
Any Polars expression that can be understood as columns. If None, all string/categorical columns will be encoded. |
None
|
separator
|
str
|
E.g. if column name is |
'_'
|
drop_first
|
bool
|
Whether to drop the first distinct value (in terms of str/categorical order). This helps with reducing dimension and prevents some issues from linear dependency. |
False
|
drop_cols
|
bool
|
Whether to drop the original columns after the transform |
True
|
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
ordinal_encode(cols=None, unknown_value=None, null_value=None)
Find the unique values in the string/categorical columns and one-hot encode them. This will NOT consider nulls as one of the unique values. Append pl.col(c).is_null().cast(pl.UInt8) expression to the pipeline if you want null indicators.
If cols is None, this will pick all string and categorical columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cols
|
IntoExprColumn | None
|
A list of strings representing column names. |
None
|
unknown_value
|
float | None
|
What to assign to values not seen in the initial dataset used to fit. None means null. |
None
|
null_value
|
float | None
|
What to assign to values that are null in dataset. |
None
|
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
polynomial_features(cols, degree, interaction_only=True)
Generates polynomial combinations out of the features given, at the given degree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cols
|
List[str]
|
A list of strings representing column names. Input to this function cannot be Polars expressions. |
required |
degree
|
int
|
The degree of the polynomial combination |
required |
interaction_only
|
bool
|
It true, only combinations that involve 2 or more variables will be used. |
True
|
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
rank_hot_encode(col, ranking, default_rank=None, drop_cols=True)
Given a ranking, e.g. ["bad", "neutral", "good"], where "bad", "neutral" and "good" are values coming
from the column col, this will return two new columns, the first is ">=neutral", which
will be 1 for all values in ("neutral", "good") and 0 otherwise, and the second new column is ">=good", which
will be 1 for all values in ("good") and 0 otherwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
str | Expr
|
The name of a single column |
required |
ranking
|
List[str]
|
A list of string representing the ranking of the values |
required |
default_rank
|
int | None
|
Default rank for all null/unseen values |
None
|
drop_cols
|
bool
|
Whether to drop the original column |
True
|
Source code in python/polars_ds/pipeline/pipeline.py
709 710 711 712 713 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 | |
rename(rename_dict)
Renames the columns by the mapping.
Paramters
rename_dict The name mapping
Source code in python/polars_ds/pipeline/pipeline.py
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 | |
robust_scale(cols, q_low, q_high)
Performs robust scaling on the given columns
Paramters
cols Any Polars expression that can be understood as columns. q_low The lower quantile value q_high The higher quantile value
Source code in python/polars_ds/pipeline/pipeline.py
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 | |
scale(cols, method='standard')
Scales values in the given columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cols
|
IntoExprColumn
|
Any Polars expression that can be understood as columns. |
required |
method
|
SimpleScaleMethod
|
One of |
'standard'
|
Source code in python/polars_ds/pipeline/pipeline.py
468 469 470 471 472 473 474 475 476 477 478 479 480 | |
select(*cols)
Selects the columns from the dataset.
Paramters
cols Any Polars expression that can be understood as columns.
Source code in python/polars_ds/pipeline/pipeline.py
512 513 514 515 516 517 518 519 520 521 522 | |
select_by_std(min_, max_)
Fits and keeps columns that have standard deviation between min_ and max_.
Non-numeric columns will always be selected. Only numeric columns with std outside
the min_ max_ bounds will be removed. This will never exclude the target if target
is set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_
|
float
|
Min standard deviation to select, inclusive. |
required |
max_
|
float
|
Max standard deviation to select, exclusive |
required |
Source code in python/polars_ds/pipeline/pipeline.py
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 | |
sort(by, descending, maintain_order=True)
Sorts the dataframe by the columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
by
|
IntoExprColumn
|
The columns to sort by |
required |
descending
|
bool | List[bool]
|
Whether the sort should be descending for the corresponding sort column |
required |
maintain_order
|
bool
|
Whether the sort should maintain order or not |
True
|
Source code in python/polars_ds/pipeline/pipeline.py
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 | |
sql_transform(sql)
Runs the SQL on the dataframe when it reaches this step. The user must ensure that the SQL is valid Polars SQL and all columns referred in the SQL exist at this point. The name "df" should be used to refer to the current state of the dataframe in the SQL. E.g. select * from df where A is True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sql
|
str
|
The SQL to run on the dataframe. Note: this step doesn't immedinately check the validity of the SQL statement. |
required |
Source code in python/polars_ds/pipeline/pipeline.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 | |
target_encode(cols=None, target=None, min_samples_leaf=20, smoothing=10.0, default=None)
Target encode the given variables.
Note: nulls will be encoded as well.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cols
|
IntoExprColumn | None
|
Any Polars expression that can be understood as columns. Columns of type != string/categorical will not produce any expression. If None, all string/categorical columns will be used. |
None
|
target
|
str | Expr | None
|
The target column |
None
|
min_samples_leaf
|
int
|
A regularization factor |
20
|
smoothing
|
float
|
Smoothing effect to balance categorical average vs prior |
10.0
|
default
|
EncoderDefaultStrategy | float | None
|
If a new value is encountered during transform (unseen in training dataset), it will be mapped to default.
If this is a string, it can be |
None
|
Reference
https://contrib.scikit-learn.org/category_encoders/targetencoder.html
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
transform(df, **kwargs)
Fits the blueprint with the dataframe that it is initialized with, and transforms the input dataframe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Any Polars dataframe |
required |
**kwargs
|
Will be passed to Pipeline's |
{}
|
Source code in python/polars_ds/pipeline/pipeline.py
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 | |
winsorize(cols, q_low=0.05, q_high=0.95, method='nearest')
Learns the lower and upper percentile from the columns, then clip each end at those values. If you wish to clip by constant values, you may append expression like pl.col(c).clip(c1, c2), where c1 and c2 are constants decided by the user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cols
|
IntoExprColumn
|
Any Polars expression that can be understood as columns. Columns must be numerical. |
required |
q_low
|
float
|
The lower quantile value |
0.05
|
q_high
|
float
|
The higher quantile value |
0.95
|
method
|
QuantileMethod
|
Method to compute quantile. One of |
'nearest'
|
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
with_columns(*exprs)
Run Polars with_columns for the expressions.
Source code in python/polars_ds/pipeline/pipeline.py
872 873 874 875 876 877 | |
woe_encode(cols=None, target=None, default=None)
Use Weight of Evidence to encode a discrete variable x with respect to target. This assumes x is discrete and castable to String. A value of 1 is added to all events/non-events (goods/bads) to smooth the computation. This is -1 * output of the package category_encoder's WOEEncoder.
Note: nulls will be encoded as well.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cols
|
IntoExprColumn | None
|
Any Polars expression that can be understood as columns. Columns of type != string/categorical will not produce any expression. If None, all string/categorical columns will be used. |
None
|
target
|
str | Expr | None
|
The target column |
None
|
default
|
EncoderDefaultStrategy | float | None
|
If a new value is encountered during transform (unseen in training dataset), it will be mapped to default.
If this is a string, it can be |
None
|
Reference
https://www.listendata.com/2015/03/weight-of-evidence-woe-and-information.html
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
ExprStep
Container for either one of these polars transforms:
- df.select(...)
- df.with_columns(...)
- df.filter(...)
Source code in python/polars_ds/pipeline/_step.py
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 | |
PLContext
Bases: Enum
Methods:
| Name | Description |
|---|---|
build_step |
Build a step from an already deserialized dict. The dict may contain values of type list[str], |
Source code in python/polars_ds/pipeline/_step.py
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 | |
build_step(deser_dict)
Build a step from an already deserialized dict. The dict may contain values of type list[str], which requires further deserialization by polars from str to pl.Expr.
Source code in python/polars_ds/pipeline/_step.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | |
Pipeline
dataclass
A ML/data transform pipeline. Pipelines should always come from the materialize call from a blueprint. In other words, a pipeline is a fitted blueprint.
Methods:
| Name | Description |
|---|---|
ensure_features_io |
Whether or not this pipeline should check the features coming in and out during transform. |
from_json |
Recreates a pipeline from a dictionary created by the |
to_json |
Turns self into a JSON string. |
transform |
Transforms the df using the learned expressions. |
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
ensure_features_io(ensure_in=True, ensure_out=True)
Whether or not this pipeline should check the features coming in and out during transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ensure_in
|
bool
|
If true, the input df (during transform) must have the exact same features as when this pipeline was fitted (blueprint.materialize()). Setting this false means the input may have additional columns, and so this adds flexibility in the pipeline. |
True
|
ensure_out
|
bool
|
If true, only the output features during blueprint.materialize() will be kept at the end of the pipeline. |
True
|
Source code in python/polars_ds/pipeline/pipeline.py
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | |
from_json(json_str)
staticmethod
Recreates a pipeline from a dictionary created by the to_json call.
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
to_json(path=None, **kwargs)
Turns self into a JSON string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | None
|
If none, will return a json string. If given, this will be used as the path to save the pipeline and None will be returned. |
None
|
kwargs
|
Keyword arguments to Python's default json |
{}
|
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
transform(df, return_lazy=False, set_features_out=False, **kwargs)
Transforms the df using the learned expressions.
Paramters
df
If none, transform the df that the pipe is initialized with. Otherwise, perform
the learned transformations on the incoming df.
return_lazy
If true, return the lazy plan for the transformations
set_features_out
If true, set self.feature_names_out_ to the output features from this transform run.
**kwargs
When return_lazy is True, kwargs will be passed to polars.LazyFrame.collect()
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
StepRepr
dataclass
A representation of a step
Source code in python/polars_ds/pipeline/pipeline.py
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 | |
transforms
This module provides classic ML dataset transforms. Note all functions here are single-use only, meaning that the data learned (e.g. mean value in mean imputation) will not be preserved. For pipeline usage, which preserves the learned values and optimizes the transform query, see pipeline.py.
Functions:
| Name | Description |
|---|---|
center |
Center the given columns so that they will have 0 mean. |
conditional_impute |
Conditionally imputes values in the given columns. This transform will collect if input is lazy. |
impute |
Impute null values in the given columns. This transform will collect if input is lazy. |
iv_encode |
Use Information Value to encode a discrete variable x with respect to target. This assumes x |
linear_impute |
Imputes the target column by training a simple linear regression using the other features. This will |
one_hot_encode |
Find the unique values in the string/categorical columns and one-hot encode them. This will NOT |
ordinal_encode |
Converts numeric / string columns into integer encodings starting from 0 to n-1, where |
polynomial_features |
Generates polynomial combinations out of the features given, at the given degree. |
rank_hot_encode |
Given a ranking, e.g. ["bad", "neutral", "good"], where "bad", "neutral" and "good" are values coming |
robust_scale |
Like min-max scaling, but scales each column by the quantile value at q1 and q2. |
scale |
Scales values in the given columns. This transform will collect if input is lazy. |
select_by_std |
Fits and selects from |
target_encode |
Target encode the given variables. This will overwrite the columns that will be encoded. |
winsorize |
Learns the lower and upper percentile from the columns, then clip each end at those values. |
woe_encode |
Use Weight of Evidence to encode a discrete variable x with respect to target. This assumes x |
center(df, cols)
Center the given columns so that they will have 0 mean.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager dataframe |
required |
cols
|
List[str]
|
A list of strings representing column names |
required |
Source code in python/polars_ds/pipeline/transforms.py
158 159 160 161 162 163 164 165 166 167 168 169 170 | |
conditional_impute(df, rules_dict, method='mean')
Conditionally imputes values in the given columns. This transform will collect if input is lazy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager dataframe |
required |
rules_dict
|
Dict[str, str | Expr]
|
Dictionary where keys are column names (must be string), and values are SQL/Polars Conditions that when true, those values in the column will be imputed, and the value to impute will be learned on the data where the condition is false. |
required |
method
|
SimpleImputeMethod
|
One of |
'mean'
|
Source code in python/polars_ds/pipeline/transforms.py
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 | |
impute(df, cols, method='mean')
Impute null values in the given columns. This transform will collect if input is lazy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager dataframe |
required |
cols
|
List[str]
|
A list of strings representing column names |
required |
method
|
SimpleImputeMethod
|
One of |
'mean'
|
Source code in python/polars_ds/pipeline/transforms.py
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 | |
iv_encode(df, cols, /, target, default='null')
Use Information Value to encode a discrete variable x with respect to target. This assumes x is discrete and castable to String. A value of 1 is added to all events/non-events (goods/bads) to smooth the computation.
Note: Nulls will always be mapped to the default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager dataframe |
required |
cols
|
List[str]
|
A list of strings representing column names. Columns of type != string/categorical will not produce any expression. |
required |
target
|
str | Expr | Series
|
The target column |
required |
default
|
EncoderDefaultStrategy | float | None
|
If a new value is encountered during transform (unseen in training dataset), it will be mapped to default.
If this is a string, it can be |
'null'
|
Reference
https://www.listendata.com/2015/03/weight-of-evidence-woe-and-information.html
Source code in python/polars_ds/pipeline/transforms.py
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 | |
linear_impute(df, features, target, add_bias=False)
Imputes the target column by training a simple linear regression using the other features. This will cast the target column to f64.
Note: The linear regression will skip nulls whenever there is a null in the features or in the target. Additionally, if NaN or Inf exists in data, the linear regression result may be invalid or an error will be thrown. It is recommended to use this only after imputing and dealing with NaN and Infs for all feature columns first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager dataframe |
required |
features
|
List[str]
|
A list of strings representing column names that will be used as features in the linear regression |
required |
target
|
str | Expr
|
The target column |
required |
add_bias
|
bool
|
Whether to add a bias term to the linear regression |
False
|
Source code in python/polars_ds/pipeline/transforms.py
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 | |
one_hot_encode(df, cols, separator='_', drop_first=False)
Find the unique values in the string/categorical columns and one-hot encode them. This will NOT consider nulls as one of the unique values. Append a one-hot null indicator if you want to encode nulls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager dataframe |
required |
cols
|
List[str]
|
A list of strings representing column names. Columns of type != string/categorical will not produce any expression. |
required |
separator
|
str
|
E.g. if column name is |
'_'
|
drop_first
|
bool
|
Whether to drop the first distinct value (in terms of str/categorical order). This helps with reducing dimension and prevents some issues from linear dependency. |
False
|
Source code in python/polars_ds/pipeline/transforms.py
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 | |
ordinal_encode(df, cols, unknown_value=None, null_value=None)
Converts numeric / string columns into integer encodings starting from 0 to n-1, where n is the number of distinct values in the column.
Note: if assigning an integer based on sorting does not make sense for
your use case, then please directly use pl.col().replace_strict(mapping)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager dataframe |
required |
cols
|
List[str]
|
A list of strings representing column names. |
required |
unknown_value
|
float | None
|
What to assign to values not present in training dataset. None means null. Must be a number. |
None
|
null_value
|
float | None
|
What to assign to values that are null. Must be a number. |
None
|
Source code in python/polars_ds/pipeline/transforms.py
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 | |
polynomial_features(cols, /, degree, interaction_only=False)
Generates polynomial combinations out of the features given, at the given degree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cols
|
List[str]
|
A list of strings representing column names. |
required |
degree
|
int
|
The degree of the polynomial combination |
required |
interaction_only
|
bool
|
It true, only combinations that involve 2 or more variables will be used. |
False
|
Source code in python/polars_ds/pipeline/transforms.py
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 | |
rank_hot_encode(col, ranking, default_rank=None)
Given a ranking, e.g. ["bad", "neutral", "good"], where "bad", "neutral" and "good" are values coming
from the column col, this will return two new columns, the first is ">=neutral", which
will be 1 for all values in ("neutral", "good") and 0 otherwise, and the second new column is ">=good", which
will be 1 for all values in ("good") and 0 otherwise.
This currently only works on string columns.
Values not in the provided ranking will have -1 in all the new columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
str
|
The name of a single column |
required |
ranking
|
List[str]
|
A list of string representing the ranking of the values |
required |
default_rank
|
int | None
|
Default rank for all null/unseen values |
None
|
Source code in python/polars_ds/pipeline/transforms.py
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 | |
robust_scale(df, cols, q_low=0.25, q_high=0.75, method='midpoint')
Like min-max scaling, but scales each column by the quantile value at q1 and q2.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager dataframe |
required |
cols
|
List[str]
|
A list of strings representing column names |
required |
q_low
|
float
|
The lower quantile value |
0.25
|
q_high
|
float
|
The higher quantile value |
0.75
|
method
|
QuantileMethod
|
Method to compute quantile. One of |
'midpoint'
|
Source code in python/polars_ds/pipeline/transforms.py
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 | |
scale(df, cols, method='standard')
Scales values in the given columns. This transform will collect if input is lazy.
Note: if method = 'min_max' and min = max, or method = 'standard' and std = 0.0, or method = 'abs_max' and |min| = |max| = 0.0, then the column(s) will not be transformed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager dataframe |
required |
cols
|
List[str]
|
A list of strings representing column names |
required |
method
|
SimpleScaleMethod
|
One of |
'standard'
|
Source code in python/polars_ds/pipeline/transforms.py
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 | |
select_by_std(df, cols, /, min_, max_)
Fits and selects from cols columns that have standard deviation between min_ and max_.
Non-numeric columns in cols will always be selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager dataframe |
required |
cols
|
List[str]
|
A list of strings representing column names. |
required |
min_
|
float
|
Min standard deviation to select, inclusive. |
required |
max_
|
float
|
Max standard deviation to select, exclusive |
required |
Source code in python/polars_ds/pipeline/transforms.py
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 | |
target_encode(df, cols, /, target, min_samples_leaf=20, smoothing=10.0, default='null')
Target encode the given variables. This will overwrite the columns that will be encoded.
Note: Nulls will always be mapped to the default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager dataframe |
required |
cols
|
List[str]
|
A list of strings representing column names. Columns of type != string/categorical will not produce any expression. |
required |
target
|
str | Expr | Series
|
The target column |
required |
min_samples_leaf
|
int
|
A regularization factor |
20
|
smoothing
|
float
|
Smoothing effect to balance categorical average vs prior |
10.0
|
default
|
EncoderDefaultStrategy | float | None
|
If a new value is encountered during transform (unseen in training dataset), it will be mapped to default.
If this is a string, it can be |
'null'
|
Reference
https://contrib.scikit-learn.org/category_encoders/targetencoder.html
Source code in python/polars_ds/pipeline/transforms.py
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 | |
winsorize(df, cols, q_low=0.05, q_high=0.95, method='nearest')
Learns the lower and upper percentile from the columns, then clip each end at those values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager dataframe |
required |
cols
|
List[str]
|
A list of strings representing column names |
required |
q_low
|
float
|
The lower quantile value |
0.05
|
q_high
|
float
|
The higher quantile value |
0.95
|
method
|
QuantileMethod
|
Method to compute quantile. One of |
'nearest'
|
Source code in python/polars_ds/pipeline/transforms.py
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 | |
woe_encode(df, cols, /, target, default='null')
Use Weight of Evidence to encode a discrete variable x with respect to target. This assumes x is discrete and castable to String. A value of 1 is added to all events/non-events (goods/bads) to smooth the computation. This is -1 * output of the package category_encoder's WOEEncoder.
Note: Nulls will always be mapped to the default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
PolarsFrame
|
Either a lazy or an eager dataframe |
required |
cols
|
List[str]
|
A list of strings representing column names. Columns of type != string/categorical will not produce any expression. |
required |
target
|
str | Expr | Series
|
The target column |
required |
default
|
EncoderDefaultStrategy | float | None
|
If a new value is encountered during transform (unseen in training dataset), it will be mapped to default.
If this is a string, it can be |
'null'
|
Reference
https://www.listendata.com/2015/03/weight-of-evidence-woe-and-information.html
Source code in python/polars_ds/pipeline/transforms.py
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 | |