lefts 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lefts-0.1.0/LICENSE +202 -0
- lefts-0.1.0/PKG-INFO +135 -0
- lefts-0.1.0/README.md +112 -0
- lefts-0.1.0/pyproject.toml +45 -0
- lefts-0.1.0/setup.cfg +4 -0
- lefts-0.1.0/src/lefts/__init__.py +11 -0
- lefts-0.1.0/src/lefts/helpers.py +42 -0
- lefts-0.1.0/src/lefts/interface.py +204 -0
- lefts-0.1.0/src/lefts/interpreter/__init__.py +0 -0
- lefts-0.1.0/src/lefts/interpreter/fit.py +222 -0
- lefts-0.1.0/src/lefts/interpreter/labels.py +117 -0
- lefts-0.1.0/src/lefts/interpreter/masks.py +96 -0
- lefts-0.1.0/src/lefts/interpreter/predict.py +140 -0
- lefts-0.1.0/src/lefts/nodes.py +106 -0
- lefts-0.1.0/src/lefts/validation.py +54 -0
- lefts-0.1.0/src/lefts.egg-info/PKG-INFO +135 -0
- lefts-0.1.0/src/lefts.egg-info/SOURCES.txt +24 -0
- lefts-0.1.0/src/lefts.egg-info/dependency_links.txt +1 -0
- lefts-0.1.0/src/lefts.egg-info/requires.txt +1 -0
- lefts-0.1.0/src/lefts.egg-info/top_level.txt +1 -0
- lefts-0.1.0/tests/test_feed.py +195 -0
- lefts-0.1.0/tests/test_fit.py +158 -0
- lefts-0.1.0/tests/test_labels.py +105 -0
- lefts-0.1.0/tests/test_masks.py +134 -0
- lefts-0.1.0/tests/test_predict.py +225 -0
- lefts-0.1.0/tests/test_validation.py +92 -0
lefts-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Copyright 2026 Niklas Mather
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
lefts-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lefts
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Composable transformations for model experimentation
|
|
5
|
+
Author-email: Niklas Mather <niksmather@gmail.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/nsmat/lefts
|
|
8
|
+
Project-URL: Repository, https://github.com/nsmat/lefts
|
|
9
|
+
Keywords: machine-learning,ensemble,cross-validation,polars,dsl
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: polars
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# Lefts: composable machine-learning model transformations
|
|
25
|
+
|
|
26
|
+
Lefts is a very simple domain specific language for building complex machine learning workflows from simple ones. Starting with your favourite machine learning models, you can use Lefts operations to:
|
|
27
|
+
- Build complex ensembles.
|
|
28
|
+
- Build complex cross validation and hyper-parametrisation procedures.
|
|
29
|
+
- Allow a model to create features or targets for another model.
|
|
30
|
+
- And any creative combination of the above.
|
|
31
|
+
|
|
32
|
+
Without making subsequent model fitting or evaluation or experimentation any more complex than it was with the original model. This implementation is built on top of the excellent Polars DataFrame library.
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# Commands
|
|
36
|
+
Lefts has five commands, which give it its name:
|
|
37
|
+
- **L**ift: trains multiple copies of a model across different subsets of data.
|
|
38
|
+
- **E**nsemble: Takes a set of models and makes them evaluate as one.
|
|
39
|
+
- **T**une: Allows a model to learn its hyperparameters from another.
|
|
40
|
+
- **F**eeds: Allows the output of one model to be used as a feature or target by another.
|
|
41
|
+
- **S**plit: Trains a model on a given train/test/validation split.
|
|
42
|
+
|
|
43
|
+
# Models
|
|
44
|
+
|
|
45
|
+
Lefts can operate on any model that is defined by:
|
|
46
|
+
- a fit method, which maps from training data into the model parameters
|
|
47
|
+
- a predict method, which maps from model parameters and test data into predictions.
|
|
48
|
+
|
|
49
|
+
A Lefts command creates a new model by transforming these functions into a new .fit and .predict. Because this new model also has a .fit and .predict, it can be transformed with further Lefts commands.
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
### Conventions
|
|
53
|
+
|
|
54
|
+
Lefts imposes some constraints on model interfaces.
|
|
55
|
+
- All hyperparameters are passed as arguments to the fit method.
|
|
56
|
+
- We expect that data is passed to fit and predict as Polars dataframes.
|
|
57
|
+
- The predict method returns an iterable, with the order of predictions matching the order on the input training data frame.
|
|
58
|
+
|
|
59
|
+
See the example notebooks to understand how to adapt your models to the required format.
|
|
60
|
+
|
|
61
|
+
# An example
|
|
62
|
+
|
|
63
|
+
The following code shows lefts can be used to create complex models out of more basic ones. We start with an LGBM Regression model, and train an ensemble of models to predict each quantile. The ensemble is trained in a monthly rolling retrain.
|
|
64
|
+
|
|
65
|
+
See notebooks/quantile_ensemble.py for the full code.
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
features = ["temp", "atemp", "hum", "windspeed", "hr", "weekday", "mnth"]
|
|
69
|
+
target = "cnt"
|
|
70
|
+
quantiles = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
|
|
71
|
+
test_period_start_dates = pl.datetime_range(
|
|
72
|
+
start = dt.datetime(2011, 3, 1),
|
|
73
|
+
end = dt.datetime(2012, 12, 1),
|
|
74
|
+
interval='1mo',
|
|
75
|
+
eager=True
|
|
76
|
+
).to_list()
|
|
77
|
+
|
|
78
|
+
quantile_models = []
|
|
79
|
+
for q in quantiles:
|
|
80
|
+
# Convert LGBMRegressor into the format required by lefts
|
|
81
|
+
base_model = leaf(tabular_model(
|
|
82
|
+
LGBMRegressor(objective="quantile", alpha=q),
|
|
83
|
+
features=features,
|
|
84
|
+
target=target,
|
|
85
|
+
),
|
|
86
|
+
label=f"q{q}",
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# 'Lift' each per-quantile model into a family of models, each with a different train and test period
|
|
90
|
+
rolling_retrain = lift(
|
|
91
|
+
base_model,
|
|
92
|
+
name=f"q{q}_rolling_retrain",
|
|
93
|
+
values=test_period_start_dates,
|
|
94
|
+
|
|
95
|
+
# A row is in a given train period if it is before the start of the test period
|
|
96
|
+
train_filter=lambda test_period_start_date: pl.col("datetime") < test_period_start_date,
|
|
97
|
+
# Each test period is one month long
|
|
98
|
+
test_filter=lambda test_period_start_date: pl.col("datetime").dt.month() == test_period_start_date.month,
|
|
99
|
+
aggregate_with=pl.coalesce,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
quantile_models.append(rolling_retrain)
|
|
103
|
+
|
|
104
|
+
model = ensemble("quantiles", *quantile_models)
|
|
105
|
+
|
|
106
|
+
# Fits |quantiles| x |test_period_start_dates| models
|
|
107
|
+
model.fit(df)
|
|
108
|
+
|
|
109
|
+
# Adds |quantiles| columns, each with the unique prediction associated with that test row.
|
|
110
|
+
predictions = model.predict(df)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Behind the scenes, the full workflow is constructed as a tree of lefts expression. You can see this tree by calling `model.print_tree()`
|
|
114
|
+
|
|
115
|
+
```
|
|
116
|
+
Ensemble 'quantiles' (198 models) → outputs: [q0.1_rolling_retrain, ..., q0.9_rolling_retrain]
|
|
117
|
+
├── Lift 'q0.1_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.1_rolling_retrain"
|
|
118
|
+
│ └── Leaf 'q0.1' (1 model)
|
|
119
|
+
├── Lift 'q0.2_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.2_rolling_retrain"
|
|
120
|
+
│ └── Leaf 'q0.2' (1 model)
|
|
121
|
+
├── Lift 'q0.3_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.3_rolling_retrain"
|
|
122
|
+
│ └── Leaf 'q0.3' (1 model)
|
|
123
|
+
├── Lift 'q0.4_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.4_rolling_retrain"
|
|
124
|
+
│ └── Leaf 'q0.4' (1 model)
|
|
125
|
+
├── Lift 'q0.5_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.5_rolling_retrain"
|
|
126
|
+
│ └── Leaf 'q0.5' (1 model)
|
|
127
|
+
├── Lift 'q0.6_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.6_rolling_retrain"
|
|
128
|
+
│ └── Leaf 'q0.6' (1 model)
|
|
129
|
+
├── Lift 'q0.7_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.7_rolling_retrain"
|
|
130
|
+
│ └── Leaf 'q0.7' (1 model)
|
|
131
|
+
├── Lift 'q0.8_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.8_rolling_retrain"
|
|
132
|
+
│ └── Leaf 'q0.8' (1 model)
|
|
133
|
+
└── Lift 'q0.9_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.9_rolling_retrain"
|
|
134
|
+
└── Leaf 'q0.9' (1 model)
|
|
135
|
+
```
|
lefts-0.1.0/README.md
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# Lefts: composable machine-learning model transformations
|
|
2
|
+
|
|
3
|
+
Lefts is a very simple domain specific language for building complex machine learning workflows from simple ones. Starting with your favourite machine learning models, you can use Lefts operations to:
|
|
4
|
+
- Build complex ensembles.
|
|
5
|
+
- Build complex cross validation and hyper-parametrisation procedures.
|
|
6
|
+
- Allow a model to create features or targets for another model.
|
|
7
|
+
- And any creative combination of the above.
|
|
8
|
+
|
|
9
|
+
Without making subsequent model fitting or evaluation or experimentation any more complex than it was with the original model. This implementation is built on top of the excellent Polars DataFrame library.
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# Commands
|
|
13
|
+
Lefts has five commands, which give it its name:
|
|
14
|
+
- **L**ift: trains multiple copies of a model across different subsets of data.
|
|
15
|
+
- **E**nsemble: Takes a set of models and makes them evaluate as one.
|
|
16
|
+
- **T**une: Allows a model to learn its hyperparameters from another.
|
|
17
|
+
- **F**eeds: Allows the output of one model to be used as a feature or target by another.
|
|
18
|
+
- **S**plit: Trains a model on a given train/test/validation split.
|
|
19
|
+
|
|
20
|
+
# Models
|
|
21
|
+
|
|
22
|
+
Lefts can operate on any model that is defined by:
|
|
23
|
+
- a fit method, which maps from training data into the model parameters
|
|
24
|
+
- a predict method, which maps from model parameters and test data into predictions.
|
|
25
|
+
|
|
26
|
+
A Lefts command creates a new model by transforming these functions into a new .fit and .predict. Because this new model also has a .fit and .predict, it can be transformed with further Lefts commands.
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
### Conventions
|
|
30
|
+
|
|
31
|
+
Lefts imposes some constraints on model interfaces.
|
|
32
|
+
- All hyperparameters are passed as arguments to the fit method.
|
|
33
|
+
- We expect that data is passed to fit and predict as Polars dataframes.
|
|
34
|
+
- The predict method returns an iterable, with the order of predictions matching the order on the input training data frame.
|
|
35
|
+
|
|
36
|
+
See the example notebooks to understand how to adapt your models to the required format.
|
|
37
|
+
|
|
38
|
+
# An example
|
|
39
|
+
|
|
40
|
+
The following code shows lefts can be used to create complex models out of more basic ones. We start with an LGBM Regression model, and train an ensemble of models to predict each quantile. The ensemble is trained in a monthly rolling retrain.
|
|
41
|
+
|
|
42
|
+
See notebooks/quantile_ensemble.py for the full code.
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
features = ["temp", "atemp", "hum", "windspeed", "hr", "weekday", "mnth"]
|
|
46
|
+
target = "cnt"
|
|
47
|
+
quantiles = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
|
|
48
|
+
test_period_start_dates = pl.datetime_range(
|
|
49
|
+
start = dt.datetime(2011, 3, 1),
|
|
50
|
+
end = dt.datetime(2012, 12, 1),
|
|
51
|
+
interval='1mo',
|
|
52
|
+
eager=True
|
|
53
|
+
).to_list()
|
|
54
|
+
|
|
55
|
+
quantile_models = []
|
|
56
|
+
for q in quantiles:
|
|
57
|
+
# Convert LGBMRegressor into the format required by lefts
|
|
58
|
+
base_model = leaf(tabular_model(
|
|
59
|
+
LGBMRegressor(objective="quantile", alpha=q),
|
|
60
|
+
features=features,
|
|
61
|
+
target=target,
|
|
62
|
+
),
|
|
63
|
+
label=f"q{q}",
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# 'Lift' each per-quantile model into a family of models, each with a different train and test period
|
|
67
|
+
rolling_retrain = lift(
|
|
68
|
+
base_model,
|
|
69
|
+
name=f"q{q}_rolling_retrain",
|
|
70
|
+
values=test_period_start_dates,
|
|
71
|
+
|
|
72
|
+
# A row is in a given train period if it is before the start of the test period
|
|
73
|
+
train_filter=lambda test_period_start_date: pl.col("datetime") < test_period_start_date,
|
|
74
|
+
# Each test period is one month long
|
|
75
|
+
test_filter=lambda test_period_start_date: pl.col("datetime").dt.month() == test_period_start_date.month,
|
|
76
|
+
aggregate_with=pl.coalesce,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
quantile_models.append(rolling_retrain)
|
|
80
|
+
|
|
81
|
+
model = ensemble("quantiles", *quantile_models)
|
|
82
|
+
|
|
83
|
+
# Fits |quantiles| x |test_period_start_dates| models
|
|
84
|
+
model.fit(df)
|
|
85
|
+
|
|
86
|
+
# Adds |quantiles| columns, each with the unique prediction associated with that test row.
|
|
87
|
+
predictions = model.predict(df)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Behind the scenes, the full workflow is constructed as a tree of lefts expression. You can see this tree by calling `model.print_tree()`
|
|
91
|
+
|
|
92
|
+
```
|
|
93
|
+
Ensemble 'quantiles' (198 models) → outputs: [q0.1_rolling_retrain, ..., q0.9_rolling_retrain]
|
|
94
|
+
├── Lift 'q0.1_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.1_rolling_retrain"
|
|
95
|
+
│ └── Leaf 'q0.1' (1 model)
|
|
96
|
+
├── Lift 'q0.2_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.2_rolling_retrain"
|
|
97
|
+
│ └── Leaf 'q0.2' (1 model)
|
|
98
|
+
├── Lift 'q0.3_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.3_rolling_retrain"
|
|
99
|
+
│ └── Leaf 'q0.3' (1 model)
|
|
100
|
+
├── Lift 'q0.4_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.4_rolling_retrain"
|
|
101
|
+
│ └── Leaf 'q0.4' (1 model)
|
|
102
|
+
├── Lift 'q0.5_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.5_rolling_retrain"
|
|
103
|
+
│ └── Leaf 'q0.5' (1 model)
|
|
104
|
+
├── Lift 'q0.6_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.6_rolling_retrain"
|
|
105
|
+
│ └── Leaf 'q0.6' (1 model)
|
|
106
|
+
├── Lift 'q0.7_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.7_rolling_retrain"
|
|
107
|
+
│ └── Leaf 'q0.7' (1 model)
|
|
108
|
+
├── Lift 'q0.8_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.8_rolling_retrain"
|
|
109
|
+
│ └── Leaf 'q0.8' (1 model)
|
|
110
|
+
└── Lift 'q0.9_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.9_rolling_retrain"
|
|
111
|
+
└── Leaf 'q0.9' (1 model)
|
|
112
|
+
```
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "lefts"
|
|
3
|
+
license = "Apache-2.0"
|
|
4
|
+
version = "0.1.0"
|
|
5
|
+
description = "Composable transformations for model experimentation"
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
authors = [
|
|
8
|
+
{ name = "Niklas Mather", email = "niksmather@gmail.com" }
|
|
9
|
+
]
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"polars",
|
|
13
|
+
]
|
|
14
|
+
keywords = ["machine-learning", "ensemble", "cross-validation", "polars", "dsl"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Science/Research",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.10",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/nsmat/lefts"
|
|
28
|
+
Repository = "https://github.com/nsmat/lefts"
|
|
29
|
+
|
|
30
|
+
[tool.ruff.lint]
|
|
31
|
+
ignore = ["E731"] # Allows the use of lambdas as variables
|
|
32
|
+
|
|
33
|
+
[dependency-groups]
|
|
34
|
+
dev = [
|
|
35
|
+
"pytest",
|
|
36
|
+
"ruff",
|
|
37
|
+
"ipykernel",
|
|
38
|
+
"jupyter",
|
|
39
|
+
"jupyterlab",
|
|
40
|
+
"nbstripout",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
[build-system]
|
|
44
|
+
requires = ["setuptools>=61.0"]
|
|
45
|
+
build-backend = "setuptools.build_meta"
|
lefts-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
import polars as pl
|
|
3
|
+
from typing import Any, Callable
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def tabular_model(
|
|
7
|
+
estimator,
|
|
8
|
+
features: list[str],
|
|
9
|
+
target: str,
|
|
10
|
+
) -> Callable[..., Any]:
|
|
11
|
+
"""
|
|
12
|
+
Wraps a sklearn-compatible estimator into a Lefts model factory.
|
|
13
|
+
|
|
14
|
+
The returned factory can be passed directly to `leaf(model_constructor=...)`.
|
|
15
|
+
|
|
16
|
+
Parameters
|
|
17
|
+
----------
|
|
18
|
+
estimator:
|
|
19
|
+
Any sklearn-compatible estimator (must implement .fit(X, y) and .predict(X)).
|
|
20
|
+
features:
|
|
21
|
+
Column names to use as model inputs.
|
|
22
|
+
target:
|
|
23
|
+
Column name of the target variable.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def factory(**hyperparameters):
|
|
27
|
+
est = copy.deepcopy(estimator)
|
|
28
|
+
if hyperparameters:
|
|
29
|
+
est.set_params(**hyperparameters)
|
|
30
|
+
|
|
31
|
+
class _Model:
|
|
32
|
+
def fit(self, training_set: pl.DataFrame):
|
|
33
|
+
X = training_set.select(features).to_numpy()
|
|
34
|
+
y = training_set[target].to_numpy()
|
|
35
|
+
est.fit(X, y)
|
|
36
|
+
|
|
37
|
+
def predict(self, df: pl.DataFrame):
|
|
38
|
+
return est.predict(df.select(features).to_numpy())
|
|
39
|
+
|
|
40
|
+
return _Model()
|
|
41
|
+
|
|
42
|
+
return factory
|