Skip to content

Commit 2129a3f

Browse files
author
Github Actions
committed
bastiscode: Adding tabular regression pipeline (#85)
1 parent a495490 commit 2129a3f

28 files changed

+899
-48
lines changed
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
"""
2+
======================
3+
Tabular Regression
4+
======================
5+
6+
The following example shows how to fit a sample classification model
7+
with AutoPyTorch
8+
"""
9+
import os
10+
import tempfile as tmp
11+
import typing
12+
import warnings
13+
14+
from sklearn.datasets import make_regression
15+
16+
from autoPyTorch.data.tabular_feature_validator import TabularFeatureValidator
17+
18+
os.environ['JOBLIB_TEMP_FOLDER'] = tmp.gettempdir()
19+
os.environ['OMP_NUM_THREADS'] = '1'
20+
os.environ['OPENBLAS_NUM_THREADS'] = '1'
21+
os.environ['MKL_NUM_THREADS'] = '1'
22+
23+
warnings.simplefilter(action='ignore', category=UserWarning)
24+
warnings.simplefilter(action='ignore', category=FutureWarning)
25+
26+
from sklearn import model_selection, preprocessing
27+
28+
from autoPyTorch.api.tabular_regression import TabularRegressionTask
29+
from autoPyTorch.datasets.tabular_dataset import TabularDataset
30+
from autoPyTorch.utils.hyperparameter_search_space_update import HyperparameterSearchSpaceUpdates
31+
32+
33+
def get_search_space_updates():
34+
"""
35+
Search space updates to the task can be added using HyperparameterSearchSpaceUpdates
36+
Returns:
37+
HyperparameterSearchSpaceUpdates
38+
"""
39+
updates = HyperparameterSearchSpaceUpdates()
40+
updates.append(node_name="data_loader",
41+
hyperparameter="batch_size",
42+
value_range=[16, 512],
43+
default_value=32)
44+
updates.append(node_name="lr_scheduler",
45+
hyperparameter="CosineAnnealingLR:T_max",
46+
value_range=[50, 60],
47+
default_value=55)
48+
updates.append(node_name='network_backbone',
49+
hyperparameter='ResNetBackbone:dropout',
50+
value_range=[0, 0.5],
51+
default_value=0.2)
52+
return updates
53+
54+
55+
if __name__ == '__main__':
56+
############################################################################
57+
# Data Loading
58+
# ============
59+
60+
# Get the training data for tabular regression
61+
# X, y = datasets.fetch_openml(name="cholesterol", return_X_y=True)
62+
63+
# Use dummy data for now since there are problems with categorical columns
64+
X, y = make_regression(
65+
n_samples=5000,
66+
n_features=4,
67+
n_informative=3,
68+
n_targets=1,
69+
shuffle=True,
70+
random_state=0
71+
)
72+
73+
X_train, X_test, y_train, y_test = model_selection.train_test_split(
74+
X,
75+
y,
76+
random_state=1,
77+
)
78+
79+
# Scale the regression targets to have zero mean and unit variance.
80+
# This is important for Neural Networks since predicting large target values would require very large weights.
81+
# One can later rescale the network predictions like this: y_pred = y_pred_scaled * y_train_std + y_train_mean
82+
y_train_mean = y_train.mean()
83+
y_train_std = y_train.std()
84+
85+
y_train_scaled = (y_train - y_train_mean) / y_train_std
86+
y_test_scaled = (y_test - y_train_mean) / y_train_std
87+
88+
############################################################################
89+
# Build and fit a regressor
90+
# ==========================
91+
api = TabularRegressionTask(
92+
delete_tmp_folder_after_terminate=False,
93+
search_space_updates=get_search_space_updates()
94+
)
95+
api.search(
96+
X_train=X_train,
97+
y_train=y_train_scaled,
98+
X_test=X_test.copy(),
99+
y_test=y_test_scaled.copy(),
100+
optimize_metric='r2',
101+
total_walltime_limit=500,
102+
func_eval_time_limit=50,
103+
traditional_per_total_budget=0
104+
)
105+
106+
############################################################################
107+
# Print the final ensemble performance
108+
# ====================================
109+
print(api.run_history, api.trajectory)
110+
y_pred_scaled = api.predict(X_test)
111+
112+
# Rescale the Neural Network predictions into the original target range
113+
y_pred = y_pred_scaled * y_train_std + y_train_mean
114+
score = api.score(y_pred, y_test)
115+
116+
print(score)
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": null,
6+
"metadata": {
7+
"collapsed": false
8+
},
9+
"outputs": [],
10+
"source": [
11+
"%matplotlib inline"
12+
]
13+
},
14+
{
15+
"cell_type": "markdown",
16+
"metadata": {},
17+
"source": [
18+
"\n# Tabular Regression\n\nThe following example shows how to fit a sample classification model\nwith AutoPyTorch\n"
19+
]
20+
},
21+
{
22+
"cell_type": "code",
23+
"execution_count": null,
24+
"metadata": {
25+
"collapsed": false
26+
},
27+
"outputs": [],
28+
"source": [
29+
"import os\nimport tempfile as tmp\nimport typing\nimport warnings\n\nfrom sklearn.datasets import make_regression\n\nfrom autoPyTorch.data.tabular_feature_validator import TabularFeatureValidator\n\nos.environ['JOBLIB_TEMP_FOLDER'] = tmp.gettempdir()\nos.environ['OMP_NUM_THREADS'] = '1'\nos.environ['OPENBLAS_NUM_THREADS'] = '1'\nos.environ['MKL_NUM_THREADS'] = '1'\n\nwarnings.simplefilter(action='ignore', category=UserWarning)\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\nfrom sklearn import model_selection, preprocessing\n\nfrom autoPyTorch.api.tabular_regression import TabularRegressionTask\nfrom autoPyTorch.datasets.tabular_dataset import TabularDataset\nfrom autoPyTorch.utils.hyperparameter_search_space_update import HyperparameterSearchSpaceUpdates\n\n\ndef get_search_space_updates():\n \"\"\"\n Search space updates to the task can be added using HyperparameterSearchSpaceUpdates\n Returns:\n HyperparameterSearchSpaceUpdates\n \"\"\"\n updates = HyperparameterSearchSpaceUpdates()\n updates.append(node_name=\"data_loader\",\n hyperparameter=\"batch_size\",\n value_range=[16, 512],\n default_value=32)\n updates.append(node_name=\"lr_scheduler\",\n hyperparameter=\"CosineAnnealingLR:T_max\",\n value_range=[50, 60],\n default_value=55)\n updates.append(node_name='network_backbone',\n hyperparameter='ResNetBackbone:dropout',\n value_range=[0, 0.5],\n default_value=0.2)\n return updates\n\n\nif __name__ == '__main__':\n ############################################################################\n # Data Loading\n # ============\n\n # Get the training data for tabular regression\n # X, y = datasets.fetch_openml(name=\"cholesterol\", return_X_y=True)\n\n # Use dummy data for now since there are problems with categorical columns\n X, y = make_regression(\n n_samples=5000,\n n_features=4,\n n_informative=3,\n n_targets=1,\n shuffle=True,\n random_state=0\n )\n\n X_train, X_test, y_train, y_test = model_selection.train_test_split(\n X,\n y,\n random_state=1,\n )\n\n # Scale the regression targets to have zero mean and unit variance.\n # This is important for Neural Networks since predicting large target values would require very large weights.\n # One can later rescale the network predictions like this: y_pred = y_pred_scaled * y_train_std + y_train_mean\n y_train_mean = y_train.mean()\n y_train_std = y_train.std()\n\n y_train_scaled = (y_train - y_train_mean) / y_train_std\n y_test_scaled = (y_test - y_train_mean) / y_train_std\n\n ############################################################################\n # Build and fit a regressor\n # ==========================\n api = TabularRegressionTask(\n delete_tmp_folder_after_terminate=False,\n search_space_updates=get_search_space_updates()\n )\n api.search(\n X_train=X_train,\n y_train=y_train_scaled,\n X_test=X_test.copy(),\n y_test=y_test_scaled.copy(),\n optimize_metric='r2',\n total_walltime_limit=500,\n func_eval_time_limit=50,\n traditional_per_total_budget=0\n )\n\n ############################################################################\n # Print the final ensemble performance\n # ====================================\n print(api.run_history, api.trajectory)\n y_pred_scaled = api.predict(X_test)\n\n # Rescale the Neural Network predictions into the original target range\n y_pred = y_pred_scaled * y_train_std + y_train_mean\n score = api.score(y_pred, y_test)\n\n print(score)"
30+
]
31+
}
32+
],
33+
"metadata": {
34+
"kernelspec": {
35+
"display_name": "Python 3",
36+
"language": "python",
37+
"name": "python3"
38+
},
39+
"language_info": {
40+
"codemirror_mode": {
41+
"name": "ipython",
42+
"version": 3
43+
},
44+
"file_extension": ".py",
45+
"mimetype": "text/x-python",
46+
"name": "python",
47+
"nbconvert_exporter": "python",
48+
"pygments_lexer": "ipython3",
49+
"version": "3.8.7"
50+
}
51+
},
52+
"nbformat": 4,
53+
"nbformat_minor": 0
54+
}
Loading

refactor_development/_modules/autoPyTorch/api/tabular_classification.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -390,7 +390,7 @@ <h1>Source code for autoPyTorch.api.tabular_classification</h1><div class="highl
390390
</p>
391391
<p>
392392
&copy; Copyright 2014-2019, Machine Learning Professorship Freiburg.<br/>
393-
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 3.5.0.<br/>
393+
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 3.5.1.<br/>
394394
</p>
395395
</div>
396396
</footer>

refactor_development/_modules/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ <h1>All modules for which code is available</h1>
128128
</p>
129129
<p>
130130
&copy; Copyright 2014-2019, Machine Learning Professorship Freiburg.<br/>
131-
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 3.5.0.<br/>
131+
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 3.5.1.<br/>
132132
</p>
133133
</div>
134134
</footer>

refactor_development/_sources/examples/example_image_classification.rst.txt

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -77,22 +77,21 @@ Image Classification
7777
Pipeline Random Config:
7878
________________________________________
7979
Configuration:
80-
image_augmenter:GaussianBlur:sigma_min, Value: 0.3669408750205385
81-
image_augmenter:GaussianBlur:sigma_offset, Value: 1.089417074756883
82-
image_augmenter:GaussianBlur:use_augmenter, Value: True
80+
image_augmenter:GaussianBlur:use_augmenter, Value: False
8381
image_augmenter:GaussianNoise:use_augmenter, Value: False
8482
image_augmenter:RandomAffine:use_augmenter, Value: False
85-
image_augmenter:RandomCutout:use_augmenter, Value: False
83+
image_augmenter:RandomCutout:p, Value: 0.8490799303808481
84+
image_augmenter:RandomCutout:use_augmenter, Value: True
8685
image_augmenter:Resize:use_augmenter, Value: False
87-
image_augmenter:ZeroPadAndCrop:percent, Value: 0.03654863814289566
88-
normalizer:__choice__, Value: 'NoNormalizer'
86+
image_augmenter:ZeroPadAndCrop:percent, Value: 0.2993076189415605
87+
normalizer:__choice__, Value: 'ImageNormalizer'
8988

9089
Fitting the pipeline...
9190
________________________________________
9291
ImageClassificationPipeline
9392
________________________________________
9493
0-) normalizer:
95-
NoNormalizer
94+
ImageNormalizer
9695

9796
1-) preprocessing:
9897
EarlyPreprocessing
@@ -164,7 +163,7 @@ Image Classification
164163
165164
.. rst-class:: sphx-glr-timing
166165

167-
**Total running time of the script:** ( 0 minutes 5.940 seconds)
166+
**Total running time of the script:** ( 0 minutes 7.334 seconds)
168167

169168

170169
.. _sphx_glr_download_examples_example_image_classification.py:

refactor_development/_sources/examples/example_tabular_classification.rst.txt

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ with AutoPyTorch
3636

3737
.. code-block:: none
3838
39-
<smac.runhistory.runhistory.RunHistory object at 0x7f8679d7a9d0> [TrajEntry(train_perf=2147483648, incumbent_id=1, incumbent=Configuration:
39+
<smac.runhistory.runhistory.RunHistory object at 0x7fd25a7cde50> [TrajEntry(train_perf=2147483648, incumbent_id=1, incumbent=Configuration:
4040
data_loader:batch_size, Value: 32
4141
encoder:__choice__, Value: 'OneHotEncoder'
4242
feature_preprocessor:__choice__, Value: 'NoFeaturePreprocessor'
@@ -65,8 +65,9 @@ with AutoPyTorch
6565
optimizer:AdamOptimizer:weight_decay, Value: 0.0
6666
optimizer:__choice__, Value: 'AdamOptimizer'
6767
scaler:__choice__, Value: 'StandardScaler'
68+
trainer:StandardTrainer:weighted_loss, Value: True
6869
trainer:__choice__, Value: 'StandardTrainer'
69-
, ta_runs=0, ta_time_used=0.0, wallclock_time=0.0018706321716308594, budget=0), TrajEntry(train_perf=0.14035087719298245, incumbent_id=1, incumbent=Configuration:
70+
, ta_runs=0, ta_time_used=0.0, wallclock_time=0.0015573501586914062, budget=0), TrajEntry(train_perf=0.17543859649122806, incumbent_id=1, incumbent=Configuration:
7071
data_loader:batch_size, Value: 32
7172
encoder:__choice__, Value: 'OneHotEncoder'
7273
feature_preprocessor:__choice__, Value: 'NoFeaturePreprocessor'
@@ -95,9 +96,10 @@ with AutoPyTorch
9596
optimizer:AdamOptimizer:weight_decay, Value: 0.0
9697
optimizer:__choice__, Value: 'AdamOptimizer'
9798
scaler:__choice__, Value: 'StandardScaler'
99+
trainer:StandardTrainer:weighted_loss, Value: True
98100
trainer:__choice__, Value: 'StandardTrainer'
99-
, ta_runs=1, ta_time_used=5.345165252685547, wallclock_time=6.850844860076904, budget=5.555555555555555)]
100-
{'accuracy': 0.8786127167630058}
101+
, ta_runs=1, ta_time_used=3.7913620471954346, wallclock_time=5.133898019790649, budget=5.555555555555555)]
102+
{'accuracy': 0.8728323699421965}
101103
102104
103105
@@ -188,7 +190,7 @@ with AutoPyTorch
188190
189191
.. rst-class:: sphx-glr-timing
190192

191-
**Total running time of the script:** ( 9 minutes 10.874 seconds)
193+
**Total running time of the script:** ( 8 minutes 58.645 seconds)
192194

193195

194196
.. _sphx_glr_download_examples_example_tabular_classification.py:

0 commit comments

Comments
 (0)