structureboost 0.8.0__cp312-cp312-win_amd64.whl

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.
@@ -0,0 +1,18 @@
1
+ """structureboost is a Python package for Gradient Boosting using categorical structure"""
2
+
3
+ from . import graphs
4
+ from .structure_gb import StructureBoost
5
+ from .structure_gb_multi import StructureBoostMulti
6
+ from .structure_dt import StructureDecisionTree
7
+ from .structure_dt_multi import StructureDecisionTreeMulti
8
+ from .prob_regr_unit import ProbRegressorUnit
9
+ from .prob_regressor import PrestoBoost
10
+ from .coarsage import Coarsage
11
+ from .pdf_discrete import PdfDiscrete, average_densities
12
+ from .pdf_group import PdfGroup, log_loss_pdf, test_between_quantiles_pdf, test_in_pred_regions
13
+ from .pdf_set import PdfSet
14
+ from .pdf_conformal import PdfConformalizer
15
+ from .utils import get_basic_config, apply_defaults, default_config_dict, ice_plot, log_loss
16
+
17
+ __version__ = '0.8.0'
18
+
@@ -0,0 +1,239 @@
1
+ from . import graphs
2
+ import numpy as np
3
+ import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+
6
+
7
+ def get_basic_config_series(feature_vec, default_config):
8
+ config_dict = {}
9
+ graph_out = None
10
+ # pandas >= 3 stores text columns with a string dtype rather than object
11
+ if (pd.api.types.is_object_dtype(feature_vec.dtype) or
12
+ pd.api.types.is_string_dtype(feature_vec.dtype)):
13
+ config_dict['feature_type'] = 'categorical_str'
14
+ config_dict['graph'] = graphs.complete_graph(pd.unique(
15
+ feature_vec.dropna()))
16
+ categorical_method = default_config['default_categorical_method']
17
+ config_dict['split_method'] = categorical_method
18
+ if categorical_method == 'contraction':
19
+ config_dict['contraction_size'] = default_config[
20
+ 'default_contraction_size']
21
+ config_dict['max_splits_to_search'] = default_config[
22
+ 'default_contraction_max_splits_to_search']
23
+ if categorical_method == 'span_tree':
24
+ config_dict['num_span_trees'] = default_config[
25
+ 'default_num_span_trees']
26
+ else:
27
+ config_dict['feature_type'] = 'numerical'
28
+ config_dict['max_splits_to_search'] = default_config[
29
+ 'default_numerical_max_splits_to_search']
30
+ return config_dict, graph_out
31
+
32
+
33
+ def get_basic_config(X_tr, default_config, X_te=None):
34
+ """Returns a feature_configs based on a training set and some defaults.
35
+
36
+ This is a tool to avoid constructing the feature_configs from scratch.
37
+ Call `get_basic_config` with the results of `default_config_dict()`
38
+ as the second argument.
39
+ Then modify the resulting config to your liking.
40
+
41
+ Parameters
42
+ ----------
43
+
44
+ X_tr : DataFrame
45
+ A dataframe containing the features you plan to train on. The function
46
+ will analyze the values, make some assumptions, and apply the defaults
47
+ to give a starting configuration dict, which can either be used directly
48
+ of further modified.
49
+
50
+ default_config : dict
51
+ This should usually be the output of the `default_config_dict` (or a
52
+ modified version of it).
53
+
54
+ Examples
55
+ --------
56
+ >>> def_set = stb.default_config_dict()
57
+ >>> def_set
58
+ {'default_categorical_method': 'span_tree',
59
+ 'default_num_span_trees': 1,
60
+ 'default_contraction_size': 9,
61
+ 'default_contraction_max_splits_to_search': 25,
62
+ 'default_numerical_max_splits_to_search': 25}
63
+ >>> feat_cfg = stb.get_basic_config(X_train, def_set)
64
+ >>> feat_cfg
65
+ {'county': {'feature_type': 'categorical_str',
66
+ 'graph': <graphs.graph_undirected at 0x10ea75860>,
67
+ 'split_method': 'span_tree',
68
+ 'num_span_trees': 1},
69
+ 'month': {'feature_type': 'numerical', 'max_splits_to_search': 25}}
70
+ >>> stb_model = stb.StructureBoost(num_trees = 2500,
71
+ learning_rate=.02,
72
+ feature_configs=feat_cfg,
73
+ max_depth=2,
74
+ mode='classification')
75
+ >>> stb_model.fit(X_train, y_train)
76
+ """
77
+ feature_config_dict = {}
78
+ for colname in X_tr.columns:
79
+ if X_te is not None:
80
+ vec_to_use = pd.concat((X_tr[colname], X_te.colname))
81
+ else:
82
+ vec_to_use = X_tr[colname]
83
+ config, graph = get_basic_config_series(vec_to_use, default_config)
84
+ feature_config_dict[colname] = config
85
+ if graph is not None:
86
+ feature_config_dict[colname]['graph'] = graph
87
+ return feature_config_dict
88
+
89
+
90
+ def default_config_dict():
91
+ """Returns a dict of defaults to be used with `get_basic_config`
92
+
93
+ The dictionary returned will contain a set of default values.
94
+ These can be modified before the dictionary is used with the
95
+ `get_basic_config` function.
96
+
97
+ Returns
98
+ -------
99
+
100
+ config_dict : dict
101
+ A dictionary containing defaults to be used in `get_basic_config()`
102
+
103
+ Examples
104
+ --------
105
+ >>> def_set = stb.default_config_dict()
106
+ >>> def_set
107
+ {'default_categorical_method': 'span_tree',
108
+ 'default_num_span_trees': 1,
109
+ 'default_contraction_size': 9,
110
+ 'default_contraction_max_splits_to_search': 25,
111
+ 'default_numerical_max_splits_to_search': 25}
112
+ >>> feat_cfg = stb.get_basic_config(X_train, def_set)
113
+ >>> feat_cfg
114
+ {'county': {'feature_type': 'categorical_str',
115
+ 'graph': <graphs.graph_undirected at 0x10ea75860>,
116
+ 'split_method': 'span_tree',
117
+ 'num_span_trees': 1},
118
+ 'month': {'feature_type': 'numerical', 'max_splits_to_search': 25}}
119
+ >>> stb_model = stb.StructureBoost(num_trees = 2500,
120
+ learning_rate=.02,
121
+ feature_configs=feat_cfg,
122
+ max_depth=2,
123
+ mode='classification')
124
+ >>> stb_model.fit(X_train, y_train)
125
+ """
126
+ config_dict = {}
127
+ config_dict['default_categorical_method'] = 'span_tree'
128
+ config_dict['default_num_span_trees'] = 1
129
+ config_dict['default_contraction_size'] = 9
130
+ config_dict['default_contraction_max_splits_to_search'] = 25
131
+ config_dict['default_numerical_max_splits_to_search'] = 25
132
+ return config_dict
133
+
134
+
135
+ def apply_defaults(config_dict, default_conf):
136
+ for feature in config_dict.keys():
137
+ config_dict[feature] = apply_defaults_featurewise(
138
+ config_dict[feature], default_conf)
139
+ return config_dict
140
+
141
+
142
+ def apply_defaults_featurewise(feature_config_dict, default_conf):
143
+ if feature_config_dict['feature_type'] != 'numerical':
144
+ if 'split_method' not in feature_config_dict.keys():
145
+ feature_config_dict['split_method'] = default_conf[
146
+ 'default_categorical_method']
147
+ method = feature_config_dict['split_method']
148
+ if method == 'span_tree':
149
+ if 'num_span_tree' not in feature_config_dict.keys():
150
+ feature_config_dict['num_span_trees'] = default_conf[
151
+ 'default_num_span_trees']
152
+ if method == 'contraction':
153
+ if 'contraction_size' not in feature_config_dict.keys():
154
+ feature_config_dict['contraction_size'] = default_conf[
155
+ 'default_contraction_size']
156
+ if 'max_splits_to_search' not in feature_config_dict.keys():
157
+ feature_config_dict['max_splits_to_search'] = default_conf[
158
+ 'default_categorical_max_splits_to_search']
159
+ else:
160
+ if 'max_splits_to_search' not in feature_config_dict.keys():
161
+ feature_config_dict['max_splits_to_search'] = default_conf[
162
+ 'default_numerical_max_splits_to_search']
163
+ return(feature_config_dict)
164
+
165
+
166
+ def ice_plot(model, data_row, column, range_pts, add_nan=True):
167
+ pred_df = pd.DataFrame(columns=data_row.index)
168
+ pred_df.loc[0] = data_row.copy()
169
+ pred_df = pd.concat([pred_df]*len(range_pts), ignore_index=True)
170
+ pred_df[column] = range_pts
171
+ if add_nan:
172
+ new_df = pd.DataFrame(columns=data_row.index)
173
+ new_dr = data_row.copy()
174
+ new_dr[column] = np.nan
175
+ new_df.loc[0] = new_dr
176
+ pred_df = pd.concat((pred_df, new_df))
177
+ pred_vals = model.predict_proba(pred_df)[:, 1]
178
+ p = plt.plot(range_pts, pred_vals[:len(range_pts)])
179
+ if add_nan:
180
+ plt.hlines(pred_vals[-1],
181
+ xmin=range_pts[0],
182
+ xmax=range_pts[int(np.floor(len(range_pts)/4+1))],
183
+ linestyle='dotted', color=p[0].get_color())
184
+
185
+ def log_loss(truth, preds, eps=1e-15, rtol=1e-05, atol=1e-08):
186
+ """A log_loss that does not complain if some classes are missing.
187
+
188
+ Parameters
189
+ ----------
190
+
191
+ truth : numpy array or Series
192
+ The true values of the observations
193
+
194
+ preds : numpy array
195
+ Generally a 2d array, but a 1d array for binary problems is
196
+ permissible and will be interpreted as the probabilities that
197
+ the case in question is 1 (positive).
198
+
199
+ eps : float, default is 1e-15
200
+ The preds will be "clipped" to eps, 1-eps to avoid issues with
201
+ taking the logarithm of zero.
202
+
203
+ rtol, atol : floats
204
+ These are passed to the numpy.allclose function for checking
205
+ that the rows of `preds` sum to one.
206
+
207
+ """
208
+ if (type(preds)==pd.Series):
209
+ preds = preds.to_numpy()
210
+ if (type(truth)==pd.Series):
211
+ truth = truth.to_numpy()
212
+ if (preds.ndim == 2) and (preds.shape[1]==1):
213
+ preds = preds.reshape(-1)
214
+ if (truth.ndim == 2) and (truth.shape[1]==1):
215
+ truth = truth.reshape(-1)
216
+ preds = np.clip(preds, eps, 1-eps)
217
+ if (preds.ndim==1):
218
+ return (-np.mean(truth*np.log(preds) + (1-truth)*np.log(1-preds)))
219
+ elif (preds.ndim==2):
220
+ row_sums = np.sum(preds, axis=1)
221
+ close_to_one = np.allclose(row_sums, np.ones(len(row_sums)), rtol=rtol, atol=atol)
222
+ if not close_to_one:
223
+ w_str = "rows do not sum to one within specified tolerance (rtol, atol)"
224
+ warnings.warn(w_str)
225
+ truth = truth.astype(np.int64)
226
+ highest_val = np.max(truth)
227
+ if (highest_val > preds.shape[1]):
228
+ w_str = 'Value of {} found in truth, but preds has only {} columns'.format(
229
+ highest_val, preds.shape[1])
230
+ warnings.warn(w_str)
231
+ return None
232
+ else:
233
+ prob_of_pred_vec = np.array([preds[i,truth[i]] for i in range(preds.shape[0])])
234
+ return(-np.mean(np.log(prob_of_pred_vec)))
235
+ else:
236
+ w_str = "preds has more than 2 dimensions"
237
+ warnings.warn(w_str)
238
+ return None
239
+
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: structureboost
3
+ Version: 0.8.0
4
+ Summary: Gradient Boosting and Probabilistic Regression with categorical structure
5
+ Author-email: Brian Lucena <brian@numeristical.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/numeristical/structureboost
8
+ Project-URL: Documentation, https://structureboost.readthedocs.io/
9
+ Project-URL: Source, https://github.com/numeristical/structureboost
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Cython
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: numpy>=1.23.5
25
+ Requires-Dist: pandas>=1.5
26
+ Requires-Dist: scipy>=1.9
27
+ Requires-Dist: matplotlib>=3.5
28
+ Requires-Dist: joblib>=1.0
29
+ Requires-Dist: splinecalib>=0.0.13
30
+ Dynamic: license-file
31
+
32
+ # StructureBoost
33
+
34
+ StructureBoost is a package to do Gradient Boosting in a manner that exploits the **structure** of categorical variables.
35
+
36
+ Have you ever used "US state" as a variable in a prediction problem and thought "Why can't my algorithm use the geography of the states to make better predictions?"
37
+
38
+ Or you've used the month of the year as a predictor, but noticed that January should border December the same way that June borders July. (or hour of the day, or day of the week)
39
+
40
+ StructureBoost can help. Read the documentation and references below. Or dive into some [examples](https://github.com/numeristical/structureboost/tree/master/examples)
41
+
42
+ ## Video Lectures
43
+
44
+ There are some explanatory videos on the [Numeristical Youtube Channel](https://www.youtube.com/channel/UCfsbASar8nsLs4NbhQwuaVg)
45
+
46
+
47
+ ## Documentation
48
+ [Read the Docs](https://structureboost.readthedocs.io/)
49
+
50
+ ## References:
51
+
52
+ Lucena, B. "Exploiting Categorical Structure with Tree-Based Methods. Proceedings of the Twenty Third International Conference on Artificial Intelligence and Statistics, PMLR 108:2949-2958, 2020. [http://proceedings.mlr.press/v108/lucena20a/lucena20a.pdf](http://proceedings.mlr.press/v108/lucena20a/lucena20a.pdf)
53
+
54
+ Lucena, B. "StructureBoost: Efficient Gradient Boosting for Structured Categorical Variables." [https://arxiv.org/abs/2007.04446](https://arxiv.org/abs/2007.04446)
55
+
56
+ ## Development
57
+
58
+ The compiled modules are generated from the Cython sources (`structureboost/*.pyx`) at build time, so a C compiler is needed to build from source.
59
+
60
+ ```bash
61
+ pip install . # build and install
62
+ pytest # run the test suite against the installed package
63
+ python -m build # build an sdist and wheel into dist/
64
+ ```
65
+
66
+ Run `pytest` rather than `python -m pytest`: the latter puts the repository root on the import path, so the uncompiled `structureboost/` source folder would shadow the installed package.
67
+
68
+ ### Releasing
69
+
70
+ Releases are built and published by GitHub Actions (`.github/workflows/release.yml`); nothing is uploaded from a local machine.
71
+
72
+ 1. Update `__version__` in `structureboost/__init__.py` and merge to `master`.
73
+ 2. Tag the merged commit and push the tag:
74
+ ```bash
75
+ git tag v0.8.0
76
+ git push origin v0.8.0
77
+ ```
78
+ 3. The workflow checks that the tag matches `__version__`, builds and tests wheels for Linux, macOS and Windows (Python 3.10–3.14), uploads them to PyPI via trusted publishing, and creates a GitHub Release.
79
+
80
+ To test the wheel builds without publishing, run the `release` workflow by hand from the Actions tab.
@@ -0,0 +1,19 @@
1
+ structureboost/__init__.py,sha256=Fbr9hd4SFPpNkF__2ljshwjzocs3hZ-vPjlSi0kDMO8,790
2
+ structureboost/coarsage.cp312-win_amd64.pyd,sha256=NLQky3h8D-yK8UxecAcPjziU-1bScrg-qWdzNcdonBk,267264
3
+ structureboost/graphs.cp312-win_amd64.pyd,sha256=nb10QrvbKOllxYDEgzvEhcnH8-z6-q5mdtHaIHbGhMM,345088
4
+ structureboost/pdf_conformal.cp312-win_amd64.pyd,sha256=q0QVc_Qf4p_mwXn-0K11jRkEBoViuSmUVktzAEFVamU,119808
5
+ structureboost/pdf_discrete.cp312-win_amd64.pyd,sha256=YuKgoqfANOtjKC6xvZnVUDyZk1Gd_sXn78vH6-LiDok,195584
6
+ structureboost/pdf_group.cp312-win_amd64.pyd,sha256=rnKjCtqFZqNl14HiUzLlhn62eg-rOghZW4xvtSaFSTE,150016
7
+ structureboost/pdf_set.cp312-win_amd64.pyd,sha256=Eag3zwmypnwsxTmt0mvIvQAZw0BXk-AhlX8ZFwTubvk,82944
8
+ structureboost/prob_regr_unit.cp312-win_amd64.pyd,sha256=xlAhKqdgiSBhdHuZVQOx89f8VMyWkHJFplQ_JFo1ESA,69120
9
+ structureboost/prob_regressor.cp312-win_amd64.pyd,sha256=k_yDWewKJFVGV8EqtfNWA88jCyYyVaKB8P2Ts2t8L2A,165376
10
+ structureboost/structure_dt.cp312-win_amd64.pyd,sha256=MczWzheVIxOa_USpx1AlfXPl49hc_s5ptLk5XKrduLA,443904
11
+ structureboost/structure_dt_multi.cp312-win_amd64.pyd,sha256=pFdtSB2T1H1qaqhixvW-RKrIbkdxMprdqR9KT4Jy2NI,143360
12
+ structureboost/structure_gb.cp312-win_amd64.pyd,sha256=WHm1Pk6XXGuc9GqnO1zBD9nhDE1E1kCzuG9ZXrUvV-k,401408
13
+ structureboost/structure_gb_multi.cp312-win_amd64.pyd,sha256=fX3wJo17L97lmP8BpzfOnUmNybe7EpbN18V02fJV8wE,310272
14
+ structureboost/utils.py,sha256=hUIJfKaajZmYl-0DtkSJ4dvGwnJId3llPryAJ-18FQ0,10087
15
+ structureboost-0.8.0.dist-info/licenses/LICENSE,sha256=Dzx2woiuhBza01Exudyoh6UjCkb52i53MLc4_R3GcTk,1088
16
+ structureboost-0.8.0.dist-info/METADATA,sha256=br4OC_tB4gHoeUFd0CMAQnkNj5AVqqc_hO-68Hy50z0,3912
17
+ structureboost-0.8.0.dist-info/WHEEL,sha256=smAfYAdc4xihz0sI8rUsw5fnCPd2yjYFBM0up6OiEDE,101
18
+ structureboost-0.8.0.dist-info/top_level.txt,sha256=1vJFnxD3R2RXezddw9tkGn5JXXnMpT4HMsuVFpBZiMM,15
19
+ structureboost-0.8.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp312-cp312-win_amd64
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Brian Lucena
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ structureboost