Skip to content

Commit 0cc4f54

Browse files
0.14.35
tests use accelerator="cpu"
1 parent 9028ee1 commit 0cc4f54

9 files changed

Lines changed: 122 additions & 24 deletions

File tree

notebooks/00_spotPython_tests.ipynb

Lines changed: 96 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4119,6 +4119,101 @@
41194119
"total_sum\n"
41204120
]
41214121
},
4122+
{
4123+
"cell_type": "code",
4124+
"execution_count": 1,
4125+
"metadata": {},
4126+
"outputs": [
4127+
{
4128+
"name": "stderr",
4129+
"output_type": "stream",
4130+
"text": [
4131+
"/Users/bartz/miniforge3/envs/spotCondaEnv/lib/python3.11/site-packages/lightning/pytorch/utilities/parsing.py:198: Attribute 'act_fn' is an instance of `nn.Module` and is already saved during checkpointing. It is recommended to ignore them using `self.save_hyperparameters(ignore=['act_fn'])`.\n",
4132+
"GPU available: True (mps), used: True\n",
4133+
"TPU available: False, using: 0 TPU cores\n",
4134+
"IPU available: False, using: 0 IPUs\n",
4135+
"HPU available: False, using: 0 HPUs\n",
4136+
"\n",
4137+
" | Name | Type | Params | In sizes | Out sizes\n",
4138+
"-------------------------------------------------------------\n",
4139+
"0 | layers | Sequential | 15.9 K | [8, 10] | [8, 1] \n",
4140+
"-------------------------------------------------------------\n",
4141+
"15.9 K Trainable params\n",
4142+
"0 Non-trainable params\n",
4143+
"15.9 K Total params\n",
4144+
"0.064 Total estimated model params size (MB)\n",
4145+
"/Users/bartz/miniforge3/envs/spotCondaEnv/lib/python3.11/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: The 'val_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=15` in the `DataLoader` to improve performance.\n",
4146+
"/Users/bartz/miniforge3/envs/spotCondaEnv/lib/python3.11/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: The 'train_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=15` in the `DataLoader` to improve performance.\n",
4147+
"`Trainer.fit` stopped: `max_epochs=2` reached.\n",
4148+
"/Users/bartz/miniforge3/envs/spotCondaEnv/lib/python3.11/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: The 'test_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=15` in the `DataLoader` to improve performance.\n"
4149+
]
4150+
},
4151+
{
4152+
"data": {
4153+
"text/html": [
4154+
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n",
4155+
"┃<span style=\"font-weight: bold\"> Test metric </span>┃<span style=\"font-weight: bold\"> DataLoader 0 </span>┃\n",
4156+
"┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━┩\n",
4157+
"│<span style=\"color: #008080; text-decoration-color: #008080\"> hp_metric </span>│<span style=\"color: #800080; text-decoration-color: #800080\"> 29018.087890625 </span>│\n",
4158+
"│<span style=\"color: #008080; text-decoration-color: #008080\"> val_loss </span>│<span style=\"color: #800080; text-decoration-color: #800080\"> 29018.087890625 </span>│\n",
4159+
"└───────────────────────────┴───────────────────────────┘\n",
4160+
"</pre>\n"
4161+
],
4162+
"text/plain": [
4163+
"┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n",
4164+
"\u001b[1m \u001b[0m\u001b[1m Test metric \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1m DataLoader 0 \u001b[0m\u001b[1m \u001b[0m┃\n",
4165+
"┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━┩\n",
4166+
"\u001b[36m \u001b[0m\u001b[36m hp_metric \u001b[0m\u001b[36m \u001b[0m│\u001b[35m \u001b[0m\u001b[35m 29018.087890625 \u001b[0m\u001b[35m \u001b[0m│\n",
4167+
"\u001b[36m \u001b[0m\u001b[36m val_loss \u001b[0m\u001b[36m \u001b[0m│\u001b[35m \u001b[0m\u001b[35m 29018.087890625 \u001b[0m\u001b[35m \u001b[0m│\n",
4168+
"└───────────────────────────┴───────────────────────────┘\n"
4169+
]
4170+
},
4171+
"metadata": {},
4172+
"output_type": "display_data"
4173+
}
4174+
],
4175+
"source": [
4176+
"from torch.utils.data import DataLoader\n",
4177+
"from spotPython.data.diabetes import Diabetes\n",
4178+
"from spotPython.light.regression.netlightregression import NetLightRegression\n",
4179+
"from torch import nn\n",
4180+
"import lightning as L\n",
4181+
"\n",
4182+
"\n",
4183+
"def test_net_light_regression_class():\n",
4184+
" BATCH_SIZE = 8\n",
4185+
"\n",
4186+
" dataset = Diabetes()\n",
4187+
" train_loader = DataLoader(dataset, batch_size=BATCH_SIZE)\n",
4188+
" test_loader = DataLoader(dataset, batch_size=BATCH_SIZE)\n",
4189+
" val_loader = DataLoader(dataset, batch_size=BATCH_SIZE)\n",
4190+
"\n",
4191+
" net_light_regression = NetLightRegression(\n",
4192+
" l1=128,\n",
4193+
" epochs=10,\n",
4194+
" batch_size=BATCH_SIZE,\n",
4195+
" initialization=\"Default\",\n",
4196+
" act_fn=nn.ReLU(),\n",
4197+
" optimizer=\"Adam\",\n",
4198+
" dropout_prob=0.1,\n",
4199+
" lr_mult=0.1,\n",
4200+
" patience=5,\n",
4201+
" _L_in=10,\n",
4202+
" _L_out=1,\n",
4203+
" _torchmetric=\"mean_squared_error\",\n",
4204+
" )\n",
4205+
" trainer = L.Trainer(\n",
4206+
" max_epochs=2,\n",
4207+
" enable_progress_bar=False,\n",
4208+
" )\n",
4209+
" trainer.fit(net_light_regression, train_loader, val_loader)\n",
4210+
" res = trainer.test(net_light_regression, test_loader)\n",
4211+
" # test if the entry 'hp_metric' is in the res dict\n",
4212+
" assert \"hp_metric\" in res[0].keys()\n",
4213+
"\n",
4214+
"test_net_light_regression_class()"
4215+
]
4216+
},
41224217
{
41234218
"cell_type": "code",
41244219
"execution_count": null,
@@ -4143,7 +4238,7 @@
41434238
"name": "python",
41444239
"nbconvert_exporter": "python",
41454240
"pygments_lexer": "ipython3",
4146-
"version": "3.11.8"
4241+
"version": "3.11.7"
41474242
}
41484243
},
41494244
"nbformat": 4,

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
77

88
[project]
99
name = "spotpython"
10-
version = "0.14.34"
10+
version = "0.14.35"
1111
authors = [
1212
{ name="T. Bartz-Beielstein", email="tbb@bartzundbartz.de" }
1313
]

src/spotPython/data/lightdatamodule.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
from typing import Optional
55

66

7-
87
class LightDataModule(L.LightningDataModule):
98
"""
109
A LightningDataModule for handling data.
@@ -94,7 +93,6 @@ def __init__(
9493
self.num_workers = num_workers
9594
self.scaler = scaler
9695

97-
9896
def prepare_data(self) -> None:
9997
"""Prepares the data for use."""
10098
# download
@@ -157,12 +155,12 @@ def setup(self, stage: Optional[str] = None) -> None:
157155
data_tensors_train = [data.clone().detach().requires_grad_(True) for data, target in self.data_train]
158156
target_tensors_train = [target.clone().detach() for data, target in self.data_train]
159157
self.data_train = TensorDataset(torch.stack(data_tensors_train), torch.stack(target_tensors_train))
160-
#print(self.data_train)
158+
# print(self.data_train)
161159
self.data_val = [(self.scaler.transform(data), target) for data, target in self.data_val]
162160
data_tensors_val = [data.clone().detach().requires_grad_(True) for data, target in self.data_val]
163161
target_tensors_val = [target.clone().detach() for data, target in self.data_val]
164162
self.data_val = TensorDataset(torch.stack(data_tensors_val), torch.stack(target_tensors_val))
165-
163+
166164
# Assign test dataset for use in dataloader(s)
167165
if stage == "test" or stage is None:
168166
print(f"test_size: {test_size} used for test dataset.")
@@ -174,7 +172,7 @@ def setup(self, stage: Optional[str] = None) -> None:
174172
data_tensors_test = [data.clone().detach().requires_grad_(True) for data, target in self.data_test]
175173
target_tensors_test = [target.clone().detach() for data, target in self.data_test]
176174
self.data_test = TensorDataset(torch.stack(data_tensors_test), torch.stack(target_tensors_test))
177-
175+
178176
# if stage == "predict" or stage is None:
179177
# print(f"test_size, full_train_size: {test_size}, {full_train_size}")
180178
# generator_predict = torch.Generator().manual_seed(self.test_seed)
@@ -194,9 +192,13 @@ def setup(self, stage: Optional[str] = None) -> None:
194192
)
195193
if self.scaler is not None:
196194
self.data_predict = [(self.scaler.transform(data), target) for data, target in self.data_predict]
197-
data_tensors_predict= [data.clone().detach().requires_grad_(True) for data, target in self.data_predict]
195+
data_tensors_predict = [
196+
data.clone().detach().requires_grad_(True) for data, target in self.data_predict
197+
]
198198
target_tensors_predict = [target.clone().detach() for data, target in self.data_predict]
199-
self.data_predict = TensorDataset(torch.stack(data_tensors_predict), torch.stack(target_tensors_predict))
199+
self.data_predict = TensorDataset(
200+
torch.stack(data_tensors_predict), torch.stack(target_tensors_predict)
201+
)
200202

201203
def train_dataloader(self) -> DataLoader:
202204
"""
@@ -297,5 +299,3 @@ def predict_dataloader(self) -> DataLoader:
297299
# apply fit_transform to the val data
298300
return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers)
299301
return DataLoader(self.data_predict, batch_size=len(self.data_predict), num_workers=self.num_workers)
300-
301-

src/spotPython/utils/init.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -407,7 +407,7 @@ def fun_control_init(
407407
"prep_model_name": prep_model_name,
408408
"progress_file": progress_file,
409409
"save_model": False,
410-
"scaler":scaler,
410+
"scaler": scaler,
411411
"scenario": scenario,
412412
"seed": seed,
413413
"show_batch_interval": 1_000_000,

src/spotPython/utils/scaler.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import torch
22

3+
34
class TorchStandardScaler:
45
"""
56
A class for scaling data using standardization with torch tensors.
67
"""
8+
79
def fit(self, x):
810
"""
911
Compute the mean and standard deviation of the input tensor.
@@ -16,7 +18,7 @@ def fit(self, x):
1618
raise TypeError("Input should be a torch tensor")
1719
self.mean = x.mean(0, keepdim=True)
1820
self.std = x.std(0, unbiased=False, keepdim=True)
19-
21+
2022
def transform(self, x):
2123
"""
2224
Scale the input tensor using the computed mean and standard deviation.
@@ -30,11 +32,11 @@ def transform(self, x):
3032
"""
3133
if not torch.is_tensor(x):
3234
raise TypeError("Input should be a torch tensor")
33-
if not hasattr(self, 'mean') or not hasattr(self, 'std'):
35+
if not hasattr(self, "mean") or not hasattr(self, "std"):
3436
raise RuntimeError("Must fit scaler before transforming data")
3537
x = (x - self.mean) / (self.std + 1e-7)
3638
return x
37-
39+
3840
def fit_transform(self, x):
3941
"""
4042
Fit the scaler to the input tensor and then scale the tensor.
@@ -47,11 +49,11 @@ def fit_transform(self, x):
4749
return self.transform(x)
4850

4951

50-
5152
class TorchMinMaxScaler:
5253
"""
5354
A class for scaling data using min-max normalization with PyTorch tensors.
5455
"""
56+
5557
def fit(self, x):
5658
"""
5759
Fit the scaler to the input data.
@@ -65,7 +67,7 @@ def fit(self, x):
6567
raise TypeError("Input should be a torch tensor")
6668
self.min = x.min(0, keepdim=True).values
6769
self.max = x.max(0, keepdim=True).values
68-
70+
6971
def transform(self, x):
7072
"""
7173
Transform the input data using the fitted scaler.
@@ -80,11 +82,11 @@ def transform(self, x):
8082
"""
8183
if not torch.is_tensor(x):
8284
raise TypeError("Input should be a torch tensor")
83-
if not hasattr(self, 'min') or not hasattr(self, 'max'):
85+
if not hasattr(self, "min") or not hasattr(self, "max"):
8486
raise RuntimeError("Must fit scaler before transforming data")
8587
x = (x - self.min) / (self.max - self.min + 1e-7)
8688
return x
87-
89+
8890
def fit_transform(self, x):
8991
"""
9092
Fit the scaler to the input data and transform it.
@@ -97,4 +99,4 @@ def fit_transform(self, x):
9799
- TypeError: If the input is not a torch tensor.
98100
"""
99101
self.fit(x)
100-
return self.transform(x)
102+
return self.transform(x)

test/test_net_light_regression_class.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ def test_net_light_regression_class():
3030
trainer = L.Trainer(
3131
max_epochs=2,
3232
enable_progress_bar=False,
33+
accelerator="cpu",
3334
)
3435
trainer.fit(net_light_regression, train_loader, val_loader)
3536
res = trainer.test(net_light_regression, test_loader)

test/test_optimizer_handler.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def test_optimizer_handler_adam():
2727
_L_out=1,
2828
_torchmetric="mean_squared_error",
2929
)
30-
trainer = L.Trainer(max_epochs=2, enable_progress_bar=False)
30+
trainer = L.Trainer(accelerator="cpu", max_epochs=2, enable_progress_bar=False)
3131
trainer.fit(net_light_base, train_loader, val_loader)
3232
# Adam uses a lr which is calculated as lr=lr_mult * 0.001, so this value
3333
# should be 0.1 * 0.001 = 0.0001
@@ -55,7 +55,7 @@ def test_optimizer_handler_adadelta():
5555
_L_out=1,
5656
_torchmetric="mean_squared_error",
5757
)
58-
trainer = L.Trainer(max_epochs=2, enable_progress_bar=False)
58+
trainer = L.Trainer(accelerator="cpu", max_epochs=2, enable_progress_bar=False)
5959
trainer.fit(net_light_base, train_loader, val_loader)
6060
# Adadelta uses a lr which is calculated as lr=lr_mult * 1.0, so this value
6161
# should be 1.0 * 0.1 = 0.1

test/test_testmodel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010

1111
def test_testmodel():
12-
fun_control = fun_control_init(_L_in=10, _L_out=1, _torchmetric="mean_squared_error")
12+
fun_control = fun_control_init(_L_in=10, _L_out=1, _torchmetric="mean_squared_error", accelerator="cpu")
1313

1414
dataset = Diabetes()
1515
set_control_key_value(control_dict=fun_control, key="data_set", value=dataset, replace=True)

test/test_trainmodel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010

1111
def test_trainmodel():
12-
fun_control = fun_control_init(_L_in=10, _L_out=1, _torchmetric="mean_squared_error")
12+
fun_control = fun_control_init(_L_in=10, _L_out=1, _torchmetric="mean_squared_error", accelerator="cpu")
1313

1414
dataset = Diabetes()
1515
set_control_key_value(control_dict=fun_control, key="data_set", value=dataset, replace=True)

0 commit comments

Comments
 (0)