Linear Regression as Polars Expr
Linear Models Related Queries
Linear Regression Related Expressions in Polars.
Functions:
| Name | Description |
|---|---|
lin_reg |
Computes linear regression solution to the equation Ax = y where y is the target (or multiple targets). |
lin_reg_report |
Creates an ordinary least square report with more stats about each coefficient. |
lin_reg_w_rcond |
Uses SVD to compute linear regression. During the process, singular values will be set to 0 |
logistic_reg |
Fits a logistic regression and returns the coefficients. This uses the L-BFGS algorithm as the solver. |
recursive_lin_reg |
Using the first |
rolling_lin_reg |
Using every |
rolling_lin_reg_1d |
Exponentially weighted rolling regression for one predictor and an intercept. |
simple_lin_reg |
Simple least square with 1 predictive variable and 1 target. |
lin_reg(*x, target, add_bias=False, weights=None, return_pred=False, l1_reg=0.0, l2_reg=0.0, tol=1e-05, solver='qr', max_iter=200, null_policy='skip', positive=False, singular_x_tol=None)
Computes linear regression solution to the equation Ax = y where y is the target (or multiple targets). If l1_reg is > 0, then this performs Lasso regression. If l2_reg is > 0, this performs Ridge regression. If both are > 0, then this is elastic net regression. If none of the cases above is true, as is the default case, then a normal regression will be performed.
If add_bias is true, it will be the last coefficient in the output and output will have len(variables) + 1.
If you only want to do simple linear regression (one predictive x variable and one target) and null policy doesn't
matter, then simple_lin_reg is a faster alternative.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
str | Expr
|
The variables used to predict target |
()
|
target
|
str | Expr | List[str | Expr]
|
The target variable, or a list of targets for a multi-target linear regression |
required |
add_bias
|
bool
|
Whether to add a bias term |
False
|
weights
|
str | Expr | None
|
Whether to perform a weighted linear regression or not. If this is weighted, then it will ignore l1_reg or l2_reg parameters. This doesn't work if this is multi-target. |
None
|
return_pred
|
bool
|
If true, return prediction and residue. If false, return coefficients. Note that for coefficients, it reduces to one output (like max/min), but for predictions and residue, it will return the same number of rows as in input. |
False
|
l1_reg
|
float
|
Regularization factor for Lasso. This is ignored if this is multi-target. |
0.0
|
l2_reg
|
float
|
Regularization factor for Ridge. |
0.0
|
tol
|
float
|
For Lasso or elastic net regression, if maximum coordinate update is < tol, the algorithm is considered to have converged. If not, it will run for at most 2000 iterations. This doesn't work if this is multi-target. |
1e-05
|
solver
|
LRSolverMethods
|
Only applies when this is normal or l2 regression. One of ['svd', 'qr']. Both 'svd' and 'qr' can handle rank deficient cases relatively well. |
'qr'
|
max_iter
|
int
|
Only used for Non-negative or Elastic net regression. The max iteration for the algorithm. |
200
|
null_policy
|
NullPolicy
|
One of options shown here, but you can also pass in any numeric string. E.g you may pass '1.25' to fill nulls with 1.25. If the string cannot be converted to a float, an error will be thrown. Note: if the target column has null, the rows with nulls will always be dropped. Null-fill only applies to non-target columns. If this is multi-target, fill will fail if there are nulls in any of the targets. |
'skip'
|
positive
|
bool
|
If true, this will perform non-negative linear regression. Not used in multi-target case. |
False
|
singular_x_tol
|
float | None
|
Rank-deficiency gate for ordinary/ridge regression (solver in ['svd', 'qr', 'cholesky'];
not used for non-negative, lasso or elastic net). Lets degenerate designs (perfectly
collinear regressors, near-constant windows) return null instead of an arbitrary min-norm
or explosive coefficient vector — useful for per-group fits, e.g.
|
None
|
Source code in python/polars_ds/exprs/expr_linear.py
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 | |
lin_reg_report(*x, target, weights=None, add_bias=False, null_policy='raise', std_err='se')
Creates an ordinary least square report with more stats about each coefficient.
Note: if columns are not linearly independent, some numerical issue may occur. This uses the closed form solution to compute the least square report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
str | Expr
|
The variables used to predict target |
()
|
target
|
str | Expr
|
The target variable |
required |
weights
|
str | Expr | None
|
If not None, this will then compute the stats for a weights least square. |
None
|
add_bias
|
bool
|
Whether to add a bias term. If bias is added, it is always the last feature. |
False
|
null_policy
|
NullPolicy
|
One of options shown here, but you can also pass in any numeric string. E.g you may pass '1.25' to fill nulls with 1.25. If the string cannot be converted to a float, an error will be thrown. Note: if the target column has null, the rows with nulls will always be dropped. Null-fill only applies to non-target columns. |
'raise'
|
std_err
|
Literal['se', 'hc0', 'hc1', 'hc2', 'hc3']
|
One of "se", "hc0", "hc1", "hc2", "hc3", where "se" means we compute the standard error under the assumption of homoskedasticity, and the hc options are different options for heteroskedasticity. The hc0-hc3 are called Heteroskedasticity-Consistent Standard Errors, and their formulas can be found here: https://jslsoc.sitehost.iu.edu/files_research/testing_tests/hccm/00TAS.pdf. This won't be used if weights are used (The author is not super familiar with the theory). If any other string is provided, it will default to "se". |
'se'
|
Source code in python/polars_ds/exprs/expr_linear.py
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 | |
lin_reg_w_rcond(*x, target, add_bias=False, rcond=0.0, l2_reg=0.0, null_policy='raise')
Uses SVD to compute linear regression. During the process, singular values will be set to 0 if it is smaller than rcond * max singular value (of X). This will return the coefficients as well as singular values of X as the output. The number of nonzero singular values is the rank of X.
Note: the singular values return will be the values before applying the rcond cut off.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
str | Expr
|
The variables used to predict target |
()
|
target
|
str | Expr
|
The target variable |
required |
add_bias
|
bool
|
Whether to add a bias term |
False
|
rcond
|
float
|
Cut-off ratio for small singular values. If rcond < machine precision * MAX(M,N), it will be set to machine precision * MAX(M,N). |
0.0
|
l2_reg
|
float
|
The L2 regularization factor. If this is > 0, then a Ridge regression will be performed. |
0.0
|
null_policy
|
NullPolicy
|
One of options shown here, but you can also pass in any numeric string. E.g you may pass '1.25' to fill nulls with 1.25. If the string cannot be converted to a float, an error will be thrown. Note: if the target column has null, the rows with nulls will always be dropped. Null-fill only applies to non-target columns. |
'raise'
|
Source code in python/polars_ds/exprs/expr_linear.py
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 | |
logistic_reg(*x, target, add_bias=True, l1_reg=0.0, l2_reg=0.0, tol=1e-05, max_iter=200, null_policy='skip', return_pred=False)
Fits a logistic regression and returns the coefficients. This uses the L-BFGS algorithm as the solver. This does a data copy internally.
Only supports binary target and the target must be 0s and 1s and the user must ensure this. Otherwise, the output will be nonsensical.
If add_bias is true and return_pred is False, the bias term will be the last coefficient in the output and output will have len(variables) + 1.
Note: This is meant to be a quick logistic regression check and will not persist the model. You have to manually save the coefficents elsewhere.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
str | Expr
|
The variables used to predict target |
()
|
target
|
str | Expr
|
The target variable, or a list of targets for a multi-target linear regression |
required |
add_bias
|
bool
|
Whether to add a bias term |
True
|
l1_reg
|
float
|
L1 regularization term. If this is > 0, it will switch to OWL-QN method. |
0.0
|
l2_reg
|
float
|
L2 regularization factor. |
0.0
|
null_policy
|
NullPolicy
|
One of options shown here, but you can also pass in any numeric string. E.g you may pass '1.25' to fill nulls with 1.25. If the string cannot be converted to a float, an error will be thrown. Note: if the target column has null, the rows with nulls will always be dropped. Null-fill only applies to non-target columns. |
'skip'
|
tol
|
float
|
The algorithm stops if the norm of the gradient is < tol. |
1e-05
|
max_iter
|
int
|
Max iter for the algorithm. |
200
|
return_pred
|
bool
|
If true, this will return a column of predicted probabilities. If false, this will return the coefficients. |
False
|
Source code in python/polars_ds/exprs/expr_linear.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 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 | |
recursive_lin_reg(*x, target, start_with, add_bias=False, l2_reg=0.0, null_policy='raise')
Using the first start_with rows of data as basis, start computing the least square solutions
by updating the betas per row. A prediction for that row will also be included in the output.
This uses the famous Sherman-Morrison-Woodbury Formula under the hood.
Note: You have to be careful about the order of data when using this in aggregation contexts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
str | Expr
|
The variables used to predict target |
()
|
target
|
str | Expr
|
The target variable |
required |
start_with
|
int
|
Must be >= 1. You |
required |
add_bias
|
bool
|
Whether to add a bias term |
False
|
l2_reg
|
float
|
The L2 regularization factor. If this is > 0, then a Ridge regression will be performed. |
0.0
|
null_policy
|
NullPolicy
|
One of options shown here, but you can also pass in any numeric string. E.g you may pass '1.25' to
fill nulls with 1.25. If the string cannot be converted to a float, an error will be thrown. Note: if
the target column has null, the rows with nulls will always be dropped. Null-fill only applies to non-target
columns. If null_policy is |
'raise'
|
Source code in python/polars_ds/exprs/expr_linear.py
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 | |
rolling_lin_reg(*x, target, window_size, add_bias=False, l2_reg=0.0, min_valid_rows=None, null_policy='raise', half_life=None)
Using every window_size rows of data as feature matrix, and computes least square solutions
by rolling the window. A prediction for that row will also be included in the output.
Without exponential weighting, this uses the Sherman-Morrison-Woodbury formula.
With half_life, it updates weighted cross-products with periodic rebuilding.
Input order is preserved. Sort data before applying the expression in grouped contexts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
str | Expr
|
The variables used to predict target |
()
|
target
|
str | Expr
|
The target variable |
required |
window_size
|
int
|
Must be >= 2. Window size for the rolling regression |
required |
add_bias
|
bool
|
Whether to add a bias term |
False
|
l2_reg
|
float
|
The L2 regularization factor. If this is > 0, then a Ridge regression will be performed. |
0.0
|
min_valid_rows
|
int | None
|
Minimum number of valid rows to evaluate the model. This is only used when null policy is |
None
|
null_policy
|
NullPolicy
|
One of options shown here, but you can also pass in any numeric string. E.g you may pass '1.25' to fill nulls with 1.25. If the string cannot be converted to a float, an error will be thrown. Note: For rolling linear regression, null-fill only works when target doesn't have nulls, and WILL NOT drop rows where the target is null. |
'raise'
|
half_life
|
float | None
|
Optional positive, finite half-life for exponentially weighted least squares.
Measured in original row positions within each group. An observation of age
|
None
|
Notes
With exponential weighting, 'skip' excludes a row if any predictor or target is
null, NaN or infinite, while retaining its window position and age. 'raise'
rejects any such row, including during warm-up. A fit requires at least
min_valid_rows valid observations and enough independent observations for all
coefficients, including the intercept. With min_valid_rows=None, the default
is the number of predictors (at least one). The first window_size - 1 rows
always have null fields; a smaller minimum does not enable partial windows.
Empty inputs return empty outputs, and groups shorter than the window return
only null fields. Sorting is the caller's responsibility; each group is independent.
Output remains a struct with coeffs (intercept last) and pred. Insufficient or
numerically degenerate windows have null fields and can recover in later windows.
A missing current target does not prevent prediction when current predictors are
valid. Any invalid current predictor makes pred null. The prediction uses the
current window's coefficients, including the current target when it is valid.
Accumulation, solving and outputs follow LIN_REG_EXPR_F64. As in lin_reg, a relative Gram determinant
at or below 1e-12 (Float64) or 1e-6 (Float32) is treated as numerically degenerate.
Weights are normalized to the newest valid observation to avoid underflow
during missing stretches. Extremely small half-lives can still underflow
older weights relative to newer valid observations. See maths/rolling_ewls.md
in the repository for the recurrence, numerical safeguards and complexity.
Examples:
>>> panel.sort(["asset", "date"]).with_columns(
... rolling_lin_reg(
... "market_return",
... target="stock_return",
... window_size=504,
... half_life=126.0,
... min_valid_rows=126,
... add_bias=True,
... null_policy="skip",
... )
... .over("asset")
... .alias("fit")
... )
Source code in python/polars_ds/exprs/expr_linear.py
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 | |
rolling_lin_reg_1d(x, *, target, window_size, half_life, min_valid_rows=None)
Exponentially weighted rolling regression for one predictor and an intercept.
This specialized implementation uses a staged Polars plan inside the plugin
and closed-form scalar formulas. Apply .over(...) to the returned expression
for grouped data, after sorting each group into the intended rolling order.
Rows where either input is null, NaN or infinite are excluded from the fit but
retain their position and age in the window. The first window_size - 1
outputs are null. A missing current target does not prevent prediction, while
an invalid current predictor makes the prediction null.
The output is a struct with coeffs (slope followed by intercept) and
pred, matching :func:rolling_lin_reg. This path deliberately supports
only the one-predictor, intercept, exponentially weighted skip case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
str | Expr
|
The single predictor. |
required |
target
|
str | Expr
|
The target variable. |
required |
window_size
|
int
|
Number of original row positions in each rolling window. Must be at least 2. |
required |
half_life
|
float
|
Positive, finite exponential-weight half-life, measured in row positions. |
required |
min_valid_rows
|
int | None
|
Minimum valid observations required. Defaults to 2. |
None
|
Examples:
>>> panel.sort(["asset", "date"]).with_columns(
... rolling_lin_reg_1d(
... "market_return",
... target="stock_return",
... window_size=504,
... half_life=126.0,
... min_valid_rows=126,
... ).over("asset").alias("fit")
... )
Source code in python/polars_ds/exprs/expr_linear.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 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 | |
simple_lin_reg(x, target, add_bias=False, weights=None, return_pred=False)
Simple least square with 1 predictive variable and 1 target.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
str | Expr
|
The variables used to predict target |
required |
target
|
str | Expr
|
The target variable |
required |
add_bias
|
bool
|
Whether to add a bias term |
False
|
weights
|
str | Expr | None
|
Whether to perform a weighted linear regression or not. |
None
|
return_pred
|
bool
|
If true, return prediction and residue. If false, return coefficients. Note that for coefficients, it reduces to one output (like max/min), but for predictions and residue, it will return the same number of rows as in input. |
False
|
Source code in python/polars_ds/exprs/expr_linear.py
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 | |